@devvit/public-api 0.11.8-next-2025-02-19-cb929a523.0 → 0.11.8-next-2025-02-19-fd8ef88c8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/apis/reddit/RedditAPIClient.d.ts +14 -2
- package/apis/reddit/RedditAPIClient.d.ts.map +1 -1
- package/apis/reddit/RedditAPIClient.js +15 -0
- package/apis/reddit/models/Flair.d.ts +8 -0
- package/apis/reddit/models/Flair.d.ts.map +1 -1
- package/apis/reddit/models/Flair.js +31 -1
- package/apis/reddit/tests/flair.api.test.d.ts.map +1 -0
- package/meta.json +15 -5
- package/meta.min.json +26 -6
- package/package.json +7 -7
- package/public-api.d.ts +727 -706
- package/public-api.iife.js +51 -3
- package/public-api.min.js +6 -5
- package/public-api.min.js.map +3 -3
- package/version.json +1 -1
package/public-api.min.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
var Ic=Object.create;var Qa=Object.defineProperty;var Ec=Object.getOwnPropertyDescriptor;var Ac=Object.getOwnPropertyNames;var Tc=Object.getPrototypeOf,Rc=Object.prototype.hasOwnProperty;var Ya=i=>{throw TypeError(i)};var Qt=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var Oc=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ac(e))!Rc.call(i,s)&&s!==t&&Qa(i,s,{get:()=>e[s],enumerable:!(r=Ec(e,s))||r.enumerable});return i};var ed=(i,e,t)=>(t=i!=null?Ic(Tc(i)):{},Oc(e||!i||!i.__esModule?Qa(t,"default",{value:i,enumerable:!0}):t,i));var Uo=(i,e,t)=>e.has(i)||Ya("Cannot "+t);var n=(i,e,t)=>(Uo(i,e,"read from private field"),t?t.call(i):e.get(i)),l=(i,e,t)=>e.has(i)?Ya("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),a=(i,e,t,r)=>(Uo(i,e,"write to private field"),r?r.call(i,t):e.set(i,t),t),h=(i,e,t)=>(Uo(i,e,"access private method"),t);var td=(i,e,t,r)=>({set _(s){a(i,e,s,t)},get _(){return n(i,e,r)}});var ca=Qt((Xb,gl)=>{var qm=Object.prototype.toString;gl.exports=function(e){if(e===void 0)return"undefined";if(e===null)return"null";var t=typeof e;if(t==="boolean")return"boolean";if(t==="string")return"string";if(t==="number")return"number";if(t==="symbol")return"symbol";if(t==="function")return Qm(e)?"generatorfunction":"function";if($m(e))return"array";if(tp(e))return"buffer";if(ep(e))return"arguments";if(Zm(e))return"date";if(Km(e))return"error";if(Xm(e))return"regexp";switch(pl(e)){case"Symbol":return"symbol";case"Promise":return"promise";case"WeakMap":return"weakmap";case"WeakSet":return"weakset";case"Map":return"map";case"Set":return"set";case"Int8Array":return"int8array";case"Uint8Array":return"uint8array";case"Uint8ClampedArray":return"uint8clampedarray";case"Int16Array":return"int16array";case"Uint16Array":return"uint16array";case"Int32Array":return"int32array";case"Uint32Array":return"uint32array";case"Float32Array":return"float32array";case"Float64Array":return"float64array"}if(Ym(e))return"generator";switch(t=qm.call(e),t){case"[object Object]":return"object";case"[object Map Iterator]":return"mapiterator";case"[object Set Iterator]":return"setiterator";case"[object String Iterator]":return"stringiterator";case"[object Array Iterator]":return"arrayiterator"}return t.slice(8,-1).toLowerCase().replace(/\s/g,"")};function pl(i){return typeof i.constructor=="function"?i.constructor.name:null}function $m(i){return Array.isArray?Array.isArray(i):i instanceof Array}function Km(i){return i instanceof Error||typeof i.message=="string"&&i.constructor&&typeof i.constructor.stackTraceLimit=="number"}function Zm(i){return i instanceof Date?!0:typeof i.toDateString=="function"&&typeof i.getDate=="function"&&typeof i.setDate=="function"}function Xm(i){return i instanceof RegExp?!0:typeof i.flags=="string"&&typeof i.ignoreCase=="boolean"&&typeof i.multiline=="boolean"&&typeof i.global=="boolean"}function Qm(i,e){return pl(i)==="GeneratorFunction"}function Ym(i){return typeof i.throw=="function"&&typeof i.return=="function"&&typeof i.next=="function"}function ep(i){try{if(typeof i.length=="number"&&typeof i.callee=="function")return!0}catch(e){if(e.message.indexOf("callee")!==-1)return!0}return!1}function tp(i){return i.constructor&&typeof i.constructor.isBuffer=="function"?i.constructor.isBuffer(i):!1}});var bl=Qt((Qb,fl)=>{"use strict";var hl=Symbol.prototype.valueOf,ip=ca();function rp(i,e){switch(ip(i)){case"array":return i.slice();case"object":return Object.assign({},i);case"date":return new i.constructor(Number(i));case"map":return new Map(i);case"set":return new Set(i);case"buffer":return ap(i);case"symbol":return dp(i);case"arraybuffer":return sp(i);case"float32array":case"float64array":case"int16array":case"int32array":case"int8array":case"uint16array":case"uint32array":case"uint8clampedarray":case"uint8array":return op(i);case"regexp":return np(i);case"error":return Object.create(i);default:return i}}function np(i){let e=i.flags!==void 0?i.flags:/\w+$/.exec(i)||void 0,t=new i.constructor(i.source,e);return t.lastIndex=i.lastIndex,t}function sp(i){let e=new i.constructor(i.byteLength);return new Uint8Array(e).set(new Uint8Array(i)),e}function op(i,e){return new i.constructor(i.buffer,i.byteOffset,i.length)}function ap(i){let e=i.length,t=Buffer.allocUnsafe?Buffer.allocUnsafe(e):Buffer.from(e);return i.copy(t),t}function dp(i){return hl?Object(hl.call(i)):{}}fl.exports=rp});var vl=Qt((Yb,yl)=>{"use strict";yl.exports=function(e){return e!=null&&typeof e=="object"&&Array.isArray(e)===!1}});var Sl=Qt((ey,Cl)=>{"use strict";var lp=vl();function kl(i){return lp(i)===!0&&Object.prototype.toString.call(i)==="[object Object]"}Cl.exports=function(e){var t,r;return!(kl(e)===!1||(t=e.constructor,typeof t!="function")||(r=t.prototype,kl(r)===!1)||r.hasOwnProperty("isPrototypeOf")===!1)}});var wl=Qt((ty,Pl)=>{"use strict";var up=bl(),cp=ca(),mp=Sl();function ma(i,e){switch(cp(i)){case"object":return pp(i,e);case"array":return gp(i,e);default:return up(i)}}function pp(i,e){if(typeof e=="function")return e(i);if(e||mp(i)){let t=new i.constructor;for(let r in i)t[r]=ma(i[r],e);return t}return i}function gp(i,e){let t=new i.constructor(i.length);for(let r=0;r<i.length;r++)t[r]=ma(i[r],e);return t}Pl.exports=ma});var gc=Qt(fo=>{"use strict";fo.byteLength=Vp;fo.toByteArray=Jp;fo.fromByteArray=$p;var Oe=[],Pe=[],Wp=typeof Uint8Array<"u"?Uint8Array:Array,Va="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Vt=0,mc=Va.length;Vt<mc;++Vt)Oe[Vt]=Va[Vt],Pe[Va.charCodeAt(Vt)]=Vt;var Vt,mc;Pe[45]=62;Pe[95]=63;function pc(i){var e=i.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var t=i.indexOf("=");t===-1&&(t=e);var r=t===e?0:4-t%4;return[t,r]}function Vp(i){var e=pc(i),t=e[0],r=e[1];return(t+r)*3/4-r}function Gp(i,e,t){return(e+t)*3/4-t}function Jp(i){var e,t=pc(i),r=t[0],s=t[1],o=new Wp(Gp(i,r,s)),d=0,c=s>0?r-4:r,m;for(m=0;m<c;m+=4)e=Pe[i.charCodeAt(m)]<<18|Pe[i.charCodeAt(m+1)]<<12|Pe[i.charCodeAt(m+2)]<<6|Pe[i.charCodeAt(m+3)],o[d++]=e>>16&255,o[d++]=e>>8&255,o[d++]=e&255;return s===2&&(e=Pe[i.charCodeAt(m)]<<2|Pe[i.charCodeAt(m+1)]>>4,o[d++]=e&255),s===1&&(e=Pe[i.charCodeAt(m)]<<10|Pe[i.charCodeAt(m+1)]<<4|Pe[i.charCodeAt(m+2)]>>2,o[d++]=e>>8&255,o[d++]=e&255),o}function zp(i){return Oe[i>>18&63]+Oe[i>>12&63]+Oe[i>>6&63]+Oe[i&63]}function qp(i,e,t){for(var r,s=[],o=e;o<t;o+=3)r=(i[o]<<16&16711680)+(i[o+1]<<8&65280)+(i[o+2]&255),s.push(zp(r));return s.join("")}function $p(i){for(var e,t=i.length,r=t%3,s=[],o=16383,d=0,c=t-r;d<c;d+=o)s.push(qp(i,d,d+o>c?c:d+o));return r===1?(e=i[t-1],s.push(Oe[e>>2]+Oe[e<<4&63]+"==")):r===2&&(e=(i[t-2]<<8)+i[t-1],s.push(Oe[e>>10]+Oe[e>>4&63]+Oe[e<<2&63]+"=")),s.join("")}});function p(i,e){if(i==null)throw Error(e??"Expected nonnullish value.")}function Ct(i,e){if(!i)throw Error(e)}var ee;(function(i){i.COMMENT="t1_",i.ACCOUNT="t2_",i.LINK="t3_",i.MESSAGE="t4_",i.SUBREDDIT="t5_",i.AWARD="t6_"})(ee||(ee={}));function Ve(i){return i.startsWith(ee.COMMENT)}function Bs(i){return i.startsWith(ee.ACCOUNT)}function St(i){return i.startsWith(ee.LINK)}function id(i){return i.startsWith(ee.MESSAGE)}function rd(i){return i.startsWith(ee.SUBREDDIT)}function nd(i){return i.startsWith(ee.AWARD)}function Bc(i){Ct(Ve(i),`Expected comment id to start with ${ee.COMMENT}, got ${i}}`)}function Mc(i){Ct(Bs(i),`Expected account id to start with ${ee.ACCOUNT}, got ${i}}`)}function Uc(i){Ct(St(i),`Expected link id to start with ${ee.LINK}, got ${i}}`)}function Dc(i){Ct(id(i),`Expected message id to start with ${ee.MESSAGE}, got ${i}}`)}function Nc(i){Ct(rd(i),`Expected subreddit id to start with ${ee.SUBREDDIT}, got ${i}}`)}function Lc(i){Ct(nd(i),`Expected award id to start with ${ee.AWARD}, got ${i}}`)}function Yt(i){return Bc(i),i}function te(i){return Mc(i),i}function de(i){return Uc(i),i}function _c(i){return Dc(i),i}function $(i){return Nc(i),i}function Hc(i){return Lc(i),i}function he(i){if(Ve(i))return Yt(i);if(Bs(i))return te(i);if(St(i))return de(i);if(id(i))return _c(i);if(rd(i))return $(i);if(nd(i))return Hc(i);throw new Error(`Expected thing id to start with ${Object.values(ee).join(", ")} got ${i}}`)}function Do(i){return Ve(i)}import*as k from"@devvit/protos";var Ms=class{constructor(e){}};var No=(t=>(t.Installation="installation",t.App="app",t))(No||{});function Pt(i,e=new Set){for(let t of i){if(t.type==="group"){Pt(t.fields,e);continue}let r=t.name;if(e.has(r))throw new Error(`Duplicate field name: ${r}`);e.add(r)}jc(i)}function jc(i){for(let e of i)if(e.type==="string"&&e.isSecret&&e.scope!=="app")throw`Invalid setting: only app settings can be secrets. Add "scope: SettingScope.App" to field "${e.name}"`}var Ge=Object.freeze({INTERVAL:0,FORM:1,STATE:2,CHANNEL:3,WEB_VIEW:4});var Ag=["3rd-party","activity","add-emoji","add","add-media","add-to-feed","admin","ads","ai","align-center","align-left","align-right","all","ama","appearance","approve","archived","aspect-ratio","aspect-rectangle","attach","audience","audio","author","automod","avatar-style","award","back","backup","ban","best","block","blockchain","bold","boost","bot","bounce","brand-awareness","browse","browser","cake","calendar","camera","campaign","caret-down","caret-left","caret-right","caret-up","chat","chat-group","chat-new","chat-private","checkbox-dismiss","checkbox","checkmark","chrome","clear","client-list","close","closed-captioning","code-block","code-inline","coins-color-old","coins","collapse-left","collapse-right","collectible-expressions","collection","comment","comments","communities","community","confidence","contest","controversial","conversion","copy-clipboard","crop","crosspost","crowd-control","custom-feed","customize","dashboard","day","delete-column","delete","delete-row","devvit","discover","dismiss-all","distinguish","down-arrow","down","download","downvote","downvotes","drag","drugs","duplicate","edit","effect","embed","emoji","end-live-chat","error","expand-left","expand-right","external","feed-video","filter","format","forward","funnel","gif-post","gold","hashtag","heart","help","hide","history","home","hot","ignore-reports","image-post","inbox","info","insert-column-left","insert-column-right","insert-row-above","insert-row-below","internet","invite","italic","join","joined","jump-down","jump-up","karma","keyboard","kick","language","leave","left","link","link-post","list-bulleted","list-numbered","live-chat","live","load","location","lock","logout","loop","macro","mark-read","marketplace","mask","media-gallery","meme","menu","message","mic","mic-mute","mod","mod-mail","mod-mode","mod-mute","mod-overflow","mod-queue","mod-unmute","music","mute","new","night","no-internet","notification","notification-frequent","notification-off","nsfw","nsfw-language","nsfw-violence","official","original","overflow-caret","overflow-horizontal","overflow-vertical","pause","payment","peace","pending-posts","phone","pin","play","poll-post","popular","posts","powerup","predictions","premium","privacy","profile","qa","qr-code","quarantined","quote","r-slash","radar","radio-button","raise-hand","random","ratings-everyone","ratings-mature","ratings-nsfw","ratings-violence","recovery-phrase","refresh","removal-reasons","remove","reply","report","reverse","rich-text","right","rising","rotate","rotate-image","rpan","rules","safari","save","save-view","saved","saved-response","search","self","send","settings","severity","share","share-new","show","side-menu","skipback10","skipforward10","sort-az","sort","sort-price","sort-za","spam","spoiler","sponsored","spreadsheet","star","statistics","status-live","sticker","strikethrough","subtract","superscript","swap-camera","swipe-back","swipe-down","swipe","swipe-up","table","tag","tap","text","text-post","text-size","toggle","tools","top","topic-activism","topic-addictionsupport","topic-advice","topic-animals","topic-anime","topic-art","topic-beauty","topic-business","topic-careers","topic-cars","topic-celebrity","topic-craftsdiy","topic-crypto","topic-culture","topic-diy","topic-entertainment","topic-ethics","topic-family","topic-fashion","topic","topic-fitness","topic-food","topic-funny","topic-gender","topic-health","topic-help","topic-history","topic-hobbies","topic-homegarden","topic-internet","topic-law","topic-learning","topic-lifestyle","topic-marketplace","topic-mature","topic-mensfashion","topic-menshealth","topic-meta","topic-military","topic-movies","topic-music","topic-news","topic-other","topic-outdoors","topic-pets","topic-photography","topic-places","topic-podcasts","topic-politics","topic-programming","topic-reading","topic-religion","topic-science","topic-sexorientation","topic-sports","topic-style","topic-tabletop","topic-technology","topic-television","topic-traumasupport","topic-travel","topic-videogaming","topic-womensfashion","topic-womenshealth","translate","translation-off","trim","u-slash","unban","undo","unheart","unlock","unmod","unpin","unstar","unverified","up-arrow","up","upload","upvote","upvotes","user","user-note","users","vault","verified","video-camera","video-feed","video-post","video-thread","video-transcription","view-card","view-classic","view-compact","view-grid","view-sort","views","volume","wallet","warning","webhook","whale","wiki-ban","wiki","wiki-unban","world","coins-color","powerup-color","powerup-fill-color","share-android","share-ios","video-live-1","video-live-fill-1","video-live","volume-mute","binoculars","caret-updown","planet","telescope"];import{AppSettingsDefinition as rm,GetFieldsResponse as nm}from"@devvit/protos";import{FormFieldType as fe}from"@devvit/protos";function Ue(i){return i.map(e=>{switch(e.type){case"string":return Wc(e);case"image":return Vc(e);case"paragraph":return Gc(e);case"number":return Jc(e);case"select":return zc(e);case"boolean":return qc(e);case"group":return $c(e);default:throw new Error("Unknown field type.")}})}function Wc(i){return{defaultValue:{fieldType:fe.STRING,stringValue:i.defaultValue},disabled:i.disabled,fieldConfig:{stringConfig:{placeholder:i.placeholder}},fieldId:i.name,fieldType:fe.STRING,helpText:i.helpText,label:i.label,required:i.required,isSecret:i.isSecret}}function Vc(i){return{disabled:i.disabled,fieldId:i.name,fieldType:fe.IMAGE,helpText:i.helpText,label:i.label,required:i.required}}function Gc(i){return{defaultValue:{fieldType:fe.PARAGRAPH,stringValue:i.defaultValue},disabled:i.disabled,fieldConfig:{paragraphConfig:{lineHeight:i.lineHeight,placeholder:i.placeholder}},fieldId:i.name,fieldType:fe.PARAGRAPH,helpText:i.helpText,label:i.label,required:i.required}}function Jc(i){return{defaultValue:{fieldType:fe.NUMBER,numberValue:i.defaultValue},disabled:i.disabled,fieldConfig:{numberConfig:{}},fieldId:i.name,fieldType:fe.NUMBER,helpText:i.helpText,label:i.label,required:i.required}}function zc(i){return{defaultValue:{fieldType:fe.SELECTION,selectionValue:{values:i.defaultValue??[]}},disabled:i.disabled,fieldConfig:{selectionConfig:{choices:i.options,multiSelect:i.multiSelect}},fieldId:i.name,fieldType:fe.SELECTION,helpText:i.helpText,label:i.label,required:i.required}}function qc(i){return{defaultValue:{fieldType:fe.BOOLEAN,boolValue:i.defaultValue},disabled:i.disabled,fieldId:i.name,fieldType:fe.BOOLEAN,helpText:i.helpText,label:i.label}}function $c(i){return{fieldId:"",fieldType:fe.GROUP,fieldConfig:{groupConfig:{fields:Ue(i.fields)}},label:i.label,helpText:i.helpText}}function R(i,e){u.prototype[i]=e}import{ValidateFormResponse as im}from"@devvit/protos";import{RealtimeSubscriptionStatus as od}from"@devvit/protos";var P=Object.freeze({Actor:"devvit-actor",App:"devvit-app",AppUser:"devvit-app-user",AppViewerAuthToken:"devvit-app-viewer-authorization",Caller:"devvit-caller",CallerPortID:"devvit-caller-port-id",Canary:"devvit-canary",Debug:"devvit-debug",GQLHost:"devvit-gql-host",Installation:"devvit-installation",ModPermissions:"devvit-mod-permissions",Post:"devvit-post",PostAuthor:"devvit-post-author",R2Auth:"devvit-sec-authorization",R2Host:"devvit-r2-host",RemoteHostname:"devvit-remote-hostname",SettingsUri:"devvit-sec-settings-uri",StreamID:"devvit-stream-id",Subreddit:"devvit-subreddit",SubredditName:"devvit-subreddit-name",TraceID:"devvit-trace-id",User:"devvit-user",Username:"devvit-user-name",UserAgent:"devvit-user-agent",Version:"devvit-version",Language:"devvit-accept-language",Timezone:"devvit-accept-timezone",Traceparent:"traceparent",AppDependencies:"devvit-app-dependencies"}),sd;(function(i){i.Blocks="blocks",i.EmitSnapshots="emitSnapshots",i.EmitState="emitState",i.Realtime="realtime",i.Runtime="runtime",i.Surface="surface",i.UseAsync="useAsync",i.Payments="payments",i.Bootstrap="bootstrap",i.WebView="webView"})(sd||(sd={}));function ad(i){function e(t){let s=i.currentHookIndex,o=i.getCurrentComponentState(),d=i.getPreviousComponentState(),c=i.metadata[P.App]?.values[0];p(c,"useChannel - app is missing from Context");let m=i.metadata[P.Installation]?.values[0];p(m,"useChannel - installation is missing from Context");async function y(B){let Y=o[s].channel;if(o[s].active)if(o[s].connected)await i.realtime.send(Y,B);else throw Error(`Failed to send to channel '${Y}'; it is active but not yet connected`);else throw Error(`Cannot send a message over inactive channel: ${Y}`)}function v(){if(!o[s].active){let B=o[s].channel;o[s].active=!0,i.addRealtimeChannel(B)}}function f(){if(o[s].active){let B=o[s].channel;o[s].active=!1,i.removeRealtimeChannel(B)}}function S(B){return async()=>{let Y;switch(B.status){case od.REALTIME_SUBSCRIBED:o[s].connected=!0,Y=t.onSubscribed?.();break;case od.REALTIME_UNSUBSCRIBED:o[s].connected=!1,Y=t.onUnsubscribed?.();break;default:Y=t.onMessage(B.event?.data?.msg);break}await Y}}let b={channel:`${c}:${m}:${t.name}`,active:!1,connected:!1,preventCallback:!1,type:Ge.CHANNEL};s in o?b=o[s]:s in d&&(b=d[s]);let O=i.realtimeEvent;i.isInitialRender?b.active=!1:O&&b.active&&O.event.channel===b.channel&&(b.preventCallback||i.runHook(S(O)),i.rerenderIn(0)),o[s]=b,i.currentHookIndex++;let L=0;return b.active&&b.connected?L=2:b.active&&!b.connected?L=1:!b.active&&b.connected?L=3:!b.active&&!b.connected&&(L=4),{subscribe:v,unsubscribe:f,send:y,status:L}}return e}import{FormFieldType as ei}from"@devvit/protos";function Lo(i){switch(i.fieldType){case ei.STRING:return i.stringValue;case ei.IMAGE:return i.stringValue;case ei.PARAGRAPH:return i.stringValue;case ei.NUMBER:return i.numberValue;case ei.BOOLEAN:return i.boolValue;case ei.SELECTION:return i.selectionValue?.values??[];default:return}}function Je(i){return Object.keys(i).reduce((e,t)=>{let r=Lo(i[t]);return r!==void 0&&(e[t]=r),e},{})}function dd(i){function e(t,r){let s=i.currentHookIndex,o=i.getCurrentComponentKey(),d=i.getCurrentComponentState(),c=i.getPreviousComponentState(),m=`form.hook.${o}.${s}`,y={formKey:m,preventSubmit:!1,type:Ge.FORM};s in d?y=d[s]:s in c&&(y=c[s]),d[s]=y,i.forms.set(m,t);let v=i.formSubmittedEvent;return v&&!y.preventSubmit&&v.formId===m&&i.runHook(async()=>{let f=r(Je(v.results));f&&f instanceof Promise&&await f,i.rerenderIn(0)}),d[s].preventSubmit=!1,i.currentHookIndex++,m}return e}function ld(i){function e(t,r){let s=i.currentHookIndex,o=i.getCurrentComponentState(),d=i.getPreviousComponentState(),c=100,m=Math.max(c,r),y={lastRun:void 0,running:!1,preventCallback:!1,type:Ge.INTERVAL};s in o?y=o[s]:s in d&&(y=d[s]);function v(){r<c&&console.error(`useInterval delay must be at least ${c}ms. Your interval of ${r}ms was automatically extended.`);for(let[S,b]of Object.entries(o))if(S!==s.toString()&&b?.type===Ge.INTERVAL&&b?.running)throw new Error("Only one useInterval hook may be running at a time");o[s]={running:!0,lastRun:o[s]?.lastRun??Date.now(),preventCallback:!1,type:Ge.INTERVAL},i.rerenderIn(m)}function f(){o[s].running=!1,o[s].lastRun=void 0,o[s].preventCallback=!1}return i.isEffectRender&&y.running&&(y.preventCallback||(y.lastRun===void 0||y.lastRun+m<Date.now())&&i.runHook(async()=>{let S=t();S&&S instanceof Promise&&await S,y.lastRun=Date.now()}),i.rerenderIn(m)),y.preventCallback=!1,o[s]=y,i.currentHookIndex++,{start:v,stop:f}}return e}function ud(i){function e(t){let r=i.currentHookIndex,s=i.getCurrentComponentState(),o=i.getPreviousComponentState();if(r in s)return i.currentHookIndex++,[s[r],d];if(i.isInitialRender||!(r in o)){let c=t instanceof Function?t():t;if(c instanceof Promise)throw(async()=>{s[r]=await c,i.currentHookIndex=0})();s[r]=c}else s[r]=o[r];function d(c){if(i.isRendering)throw new Error("Cannot call setState while rendering.");s[r]=c instanceof Function?c(s[r]):c}return i.currentHookIndex++,[s[r],d]}return e}var Wo={now(){return new Date}};function cd(i){return`__autocache__${i}`}function md(i){return`__lock__${i}`}var Zc=300,Xc=1e3,Us=5e3,_o=3,pd=.1,gd=1e3,Qc=3e4;function hd(i){if(i.error)throw new Error(i.error);return i.value}var ze,qe,be,ti,J,fd,bd,yd,Ho,vd,kd,jo,Cd,Ds=class{constructor(e,t,r=Wo){l(this,J);l(this,ze);l(this,qe,{});l(this,be);l(this,ti);a(this,ze,e),a(this,ti,t),a(this,be,r)}async cache(e,t){a(this,qe,n(this,ti).__cache=n(this,ti).__cache??{}),h(this,J,Cd).call(this,t);let r=h(this,J,fd).call(this,t.key);if(r!==void 0)return r;let s=await h(this,J,jo).call(this,t.key),o=await h(this,J,bd).call(this,t,s,e);return hd(o)}};ze=new WeakMap,qe=new WeakMap,be=new WeakMap,ti=new WeakMap,J=new WeakSet,fd=function(e){let t=n(this,qe)[e];if(t){let r=n(this,be).now().getTime(),s=t?.error&&t?.errorTime&&t.errorCount<_o&&Math.random()<pd&&t.errorTime+gd<r;if(t?.expires&&t.expires<r&&t.checkedAt+gd<r||s){delete n(this,qe)[e];return}else return hd(t)}},bd=async function(e,t,r){let s=t?.expires,o=s?h(this,J,kd).call(this,s):1;return!t||t?.error&&t.errorCount<_o&&pd>Math.random()||o>Math.random()?h(this,J,yd).call(this,e,t,r):t},yd=async function(e,t,r){let s=md(e.key),o=n(this,be).now().getTime(),d=new Date(o+e.ttl/2);if(await n(this,ze).set(s,"1",{expiration:d,nx:!0}))return h(this,J,vd).call(this,e.key,t,r,e.ttl);if(t)return t;{let m=n(this,be).now();return h(this,J,Ho).call(this,m,e.key,e.ttl)}},Ho=async function(e,t,r){let s=Math.min(r,Xc),o=await h(this,J,jo).call(this,t);if(o)return o;if(n(this,be).now().getTime()-e.getTime()>=s)throw new Error(`Cache request timed out trying to get data at key: ${t}`);return await new Promise(d=>setTimeout(d,Zc)),h(this,J,Ho).call(this,e,t,r)},vd=async function(e,t,r,s){let o=n(this,be).now().getTime()+s;t=t??{value:null,expires:o,errorCount:0,error:null,errorTime:null,checkedAt:0};try{t.value=await r(),t.error=null,t.errorCount=0,t.errorTime=null}catch(d){t.value=null,t.error=d.message??"Unknown error",t.errorTime=n(this,be).now().getTime(),t.errorCount++}return n(this,qe)[e]=t,await n(this,ze).set(cd(e),JSON.stringify(t),{expiration:new Date(o+Qc)}),t.error&&t.errorCount<_o&&await n(this,ze).del(md(e)),t},kd=function(e){let t=n(this,be).now().getTime(),r=e-t;return r<0?1:r<1e3?.1:r<2e3?.01:r<3e3?.001:0},jo=async function(e){let t=await n(this,ze).get(cd(e));if(t){let r=JSON.parse(t);return r.checkedAt=n(this,be).now().getTime(),n(this,qe)[e]=r,r}},Cd=function(e){e.ttl<Us&&(console.warn(`Cache TTL cannot be less than ${Us} milliseconds! Updating ttl value of ${e.ttl} to ${Us}.`),e.ttl=Us)};function Sd(i,e,t=Wo){let r=new Ds(i,e,t);return r.cache.bind(r)}function Pd(i){new URL(i.slice(0,i.indexOf(",")))}var ii,ri,si,wd,Fd,ni=class{constructor(){l(this,si);l(this,ii,{});l(this,ri,{});a(this,ii,u.assets),a(this,ri,u.webViewAssets)}getURL(e,t){return typeof e=="string"?h(this,si,wd).call(this,e,t??{webView:!1}):h(this,si,Fd).call(this,e,t??{webView:!1})}};ii=new WeakMap,ri=new WeakMap,si=new WeakSet,wd=function(e,t){let r=t.webView?n(this,ri)[e]:n(this,ii)[e];if(r)return r;try{return Pd(e),e}catch{return""}},Fd=function(e,t){let r={},s=[],o=t.webView?n(this,ri):n(this,ii);if(o)for(let d of e)if(o[d])r[d]=o[d];else try{Pd(d),r[d]=d}catch{s.push(d)}else s=e;if(s.length>0)throw new Error(`The following assets were missing from the assets list: ${s.join(", ")}`);return r};var $e,oi=class{constructor(e){l(this,$e);a(this,$e,e)}async get(e){let{messages:t}=await u.kvStorePlugin.Get({keys:[e]},n(this,$e));try{if(t[e])return JSON.parse(t[e])}catch{return}}async put(e,t){let r={};r[e]=JSON.stringify(t),await u.kvStorePlugin.Put({messages:r},n(this,$e))}async delete(e){await u.kvStorePlugin.Del({keys:[e]},n(this,$e))}async list(){let{keys:e}=await u.kvStorePlugin.List({filter:"*"},n(this,$e));return e}};$e=new WeakMap;var Ar,ai=class{constructor(e){l(this,Ar);a(this,Ar,e)}async upload(e){let t=await u.mediaPlugin.Upload(e,n(this,Ar));if(!t.mediaId)throw new Error("unable to get mediaId via uploads");return Promise.resolve({mediaId:t.mediaId,mediaUrl:t.mediaUrl})}};Ar=new WeakMap;var Tr,di=class{constructor(e){l(this,Tr);a(this,Tr,e)}async add(e){await u.modLogPlugin.Add(e,n(this,Tr))}};Tr=new WeakMap;var Rr,li=class{constructor(e){l(this,Rr);a(this,Rr,e)}async send(e,t){await u.realtimePlugin.Send({channel:e,data:{msg:t}},n(this,Rr))}};Rr=new WeakMap;var g,Or,Br,Mr,ui=class{constructor(e){l(this,g);l(this,Or);l(this,Br);l(this,Mr);a(this,g,e),a(this,Or,new Ls(e))}get modMail(){return n(this,Or)}getSubredditById(e){return le.getById(he(e),n(this,g))}getSubredditInfoById(e){return Ed(e,n(this,g))}getSubredditByName(e){return le.getByName(e,n(this,g))}getSubredditInfoByName(e){return Ad(e,n(this,g))}addSubredditRemovalReason(e,t){return le.addRemovalReason(e,t.title,t.message,n(this,g))}getSubredditRemovalReasons(e){return le.getRemovalReasons(e,n(this,g))}async getCurrentSubredditName(){let e=n(this,g)?.[P.SubredditName]?.values[0];if(e)return e;let t=n(this,g)?.[P.Subreddit]?.values[0],r=await Vo($(t),n(this,g));if(!r)throw new Error("Couldn't get current subreddit's name");return r}async getCurrentSubreddit(){let e=await le.getFromMetadata(n(this,g));if(!e)throw new Error("Couldn't get current subreddit");return e}getPostById(e){return V.getById(he(e),n(this,g))}submitPost(e){return V.submit(e,n(this,g))}crosspost(e){return V.crosspost(e,n(this,g))}getUserById(e){return C.getById(he(e),n(this,g))}getUserByUsername(e){return C.getByUsername(e,n(this,g))}async getCurrentUsername(){return n(this,Mr)??a(this,Mr,xd(n(this,g))),n(this,Mr)}async getCurrentUser(){return n(this,Br)??a(this,Br,this.getCurrentUsername().then(e=>e?C.getByUsername(e,n(this,g)):void 0)),n(this,Br)}getAppUser(){return C.getFromMetadata(P.AppUser,n(this,g))}getSnoovatarUrl(e){return C.getSnoovatarUrl(e,n(this,g))}getCommentById(e){return X.getById(he(e),n(this,g))}getComments(e){return X.getComments(e,n(this,g))}getCommentsByUser(e){return X.getCommentsByUser(e,n(this,g))}submitComment(e){return X.submit({...e,id:he(e.id)},n(this,g))}getControversialPosts(e){return V.getControversialPosts(e,n(this,g))}getTopPosts(e){return V.getTopPosts(e,n(this,g))}getHotPosts(e){return V.getHotPosts(e,n(this,g))}getNewPosts(e){return V.getNewPosts(e,n(this,g))}getRisingPosts(e){return V.getRisingPosts(e,n(this,g))}getPostsByUser(e){return V.getPostsByUser(e,n(this,g))}getCommentsAndPostsByUser(e){return C.getOverview(e,n(this,g))}getModerationLog(e){return Ns(e,n(this,g))}getApprovedUsers(e){return C.getSubredditUsersByType({type:"contributors",...e},n(this,g))}approveUser(e,t){return C.createRelationship({username:e,subredditName:t,type:"contributor"},n(this,g))}removeUser(e,t){return C.removeRelationship({username:e,subredditName:t,type:"contributor"},n(this,g))}getWikiContributors(e){return C.getSubredditUsersByType({type:"wikicontributors",...e},n(this,g))}addWikiContributor(e,t){return C.createRelationship({username:e,subredditName:t,type:"wikicontributor"},n(this,g))}removeWikiContributor(e,t){return C.removeRelationship({username:e,subredditName:t,type:"wikicontributor"},n(this,g))}getBannedUsers(e){return C.getSubredditUsersByType({type:"banned",...e},n(this,g))}banUser(e){return C.createRelationship({username:e.username,subredditName:e.subredditName,type:"banned",banReason:e.reason,banMessage:e.message,note:e.note,duration:e.duration,banContext:e.context},n(this,g))}unbanUser(e,t){return C.removeRelationship({username:e,subredditName:t,type:"banned"},n(this,g))}getBannedWikiContributors(e){return C.getSubredditUsersByType({type:"wikibanned",...e},n(this,g))}banWikiContributor(e){return C.createRelationship({...e,type:"wikibanned"},n(this,g))}unbanWikiContributor(e,t){return C.removeRelationship({username:e,subredditName:t,type:"wikibanned"},n(this,g))}getModerators(e){return C.getSubredditUsersByType({type:"moderators",...e},n(this,g))}inviteModerator(e){return C.createRelationship({type:"moderator_invite",subredditName:e.subredditName,username:e.username,permissions:e.permissions??[]},n(this,g))}revokeModeratorInvite(e,t){return C.removeRelationship({username:e,subredditName:t,type:"moderator_invite"},n(this,g))}removeModerator(e,t){return C.removeRelationship({type:"moderator",subredditName:t,username:e},n(this,g))}setModeratorPermissions(e,t,r){return C.setModeratorPermissions(e,t,r,n(this,g))}getMutedUsers(e){return C.getSubredditUsersByType({type:"muted",...e},n(this,g))}muteUser(e){return C.createRelationship({...e,type:"muted"},n(this,g))}unmuteUser(e,t){return C.removeRelationship({username:e,subredditName:t,type:"muted"},n(this,g))}getModNotes(e){return ye.get(e,n(this,g))}deleteModNote(e){return ye.delete(e,n(this,g))}addModNote(e){let t={...e,redditId:e.redditId?he(e.redditId):void 0};return ye.add(t,n(this,g))}addRemovalNote(e){return ye.addRemovalNote(e,n(this,g))}async sendPrivateMessage(e){return wt.send(e,n(this,g))}async sendPrivateMessageAsSubreddit(e){return wt.sendAsSubreddit(e,n(this,g))}async approve(e){if(Ve(e))return X.approve(e,n(this,g));if(St(e))return V.approve(e,n(this,g));throw new Error("id must start with either t1_ or t3_")}async remove(e,t){if(Ve(e))return X.remove(e,t,n(this,g));if(St(e))return V.remove(e,t,n(this,g));throw new Error("id must start with either t1_ or t3_")}async getPostFlairTemplates(e){return ne.getPostFlairTemplates(e,n(this,g))}async getUserFlairTemplates(e){return ne.getUserFlairTemplates(e,n(this,g))}async createPostFlairTemplate(e){return ne.createPostFlairTemplate(e,n(this,g))}async createUserFlairTemplate(e){return ne.createUserFlairTemplate(e,n(this,g))}async editFlairTemplate(e){return ne.editFlairTemplate(e,n(this,g))}async deleteFlairTemplate(e,t){return ne.deleteFlairTemplate(e,t,n(this,g))}async setUserFlair(e){return ve.setUserFlair(e,n(this,g))}async removeUserFlair(e,t){return ve.removeUserFlair(e,t,n(this,g))}async setPostFlair(e){return ve.setPostFlair(e,n(this,g))}async removePostFlair(e,t){return ve.removePostFlair(e,de(t),n(this,g))}async getWidgets(e){return ie.getWidgets(e,n(this,g))}async deleteWidget(e,t){return ie.delete(e,t,n(this,g))}async addWidget(e){return ie.add(e,n(this,g))}async reorderWidgets(e,t){return ie.reorder(e,t,n(this,g))}async getWikiPage(e,t){return ue.getPage(e,t,n(this,g))}async getWikiPages(e){return ue.getPages(e,n(this,g))}async createWikiPage(e){return ue.createPage(e,n(this,g))}async updateWikiPage(e){return ue.updatePage(e,n(this,g))}getWikiPageRevisions(e){return ue.getPageRevisions(e,n(this,g))}async revertWikiPage(e,t,r){return ue.revertPage(e,t,r,n(this,g))}async getWikiPageSettings(e,t){return ue.getPageSettings(e,t,n(this,g))}async updateWikiPageSettings(e){return ue.updatePageSettings(e,n(this,g))}async addEditorToWikiPage(e,t,r){return ue.addEditor(e,t,r,n(this,g))}async removeEditorFromWikiPage(e,t,r){return ue.removeEditor(e,t,r,n(this,g))}getMessages(e){return wt.getMessages(e,n(this,g))}markAllMessagesAsRead(){return wt.markAllAsRead(n(this,g))}report(e,t){return u.redditAPIPlugins.LinksAndComments.Report({reason:t.reason,thingId:e.id,srName:e.subredditName,usernames:e.authorName},n(this,g))}getModQueue(e){return le.aboutLocation({...e,location:"modqueue"},n(this,g))}getReports(e){return le.aboutLocation({...e,location:"reports"},n(this,g))}getSpam(e){return le.aboutLocation({...e,location:"spam"},n(this,g))}getUnmoderated(e){return le.aboutLocation({...e,location:"unmoderated"},n(this,g))}getEdited(e){return le.aboutLocation({...e,location:"edited"},n(this,g))}getVaultByAddress(e){return Od(e,n(this,g))}getVaultByUserId(e){return Bd(he(e),n(this,g))}getSubredditLeaderboard(e){return Td(e,n(this,g))}getSubredditStyles(e){return Rd(e,n(this,g))}async subscribeToCurrentSubreddit(){let e=await this.getCurrentSubreddit();await u.redditAPIPlugins.Subreddits.Subscribe({action:"sub",actionSource:"",srName:e.name,sr:"",skipInitialDefaults:!0},n(this,g))}async unsubscribeFromCurrentSubreddit(){let e=await this.getCurrentSubreddit();await u.redditAPIPlugins.Subreddits.Subscribe({action:"unsub",actionSource:"",srName:e.name,sr:"",skipInitialDefaults:!1},n(this,g))}};g=new WeakMap,Or=new WeakMap,Br=new WeakMap,Mr=new WeakMap;import{BitfieldOverflowBehavior as Go,RedisKeyScope as Jo}from"@devvit/protos";function _s(i){return i&&typeof i=="object"&&"message"in i&&i.message!==void 0&&typeof i.message=="string"?i.message.includes("redis: nil"):!1}var x,I,E,zo=class{constructor(e,t,r){l(this,x);l(this,I);l(this,E);a(this,x,e),a(this,I,t),a(this,E,r)}async get(e){return await n(this,x).Get({key:e,transactionId:n(this,I)},n(this,E)),this}async multi(){await n(this,x).Multi(n(this,I),n(this,E))}async set(e,t,r){let s;return r?.expiration&&(s=Math.floor((r.expiration.getTime()-Date.now())/1e3),s<1&&(s=1)),await n(this,x).Set({key:e,value:t,nx:r?.nx===!0,xx:r?.xx===!0,expiration:s||0,transactionId:n(this,I)},n(this,E)),this}async del(...e){return await n(this,x).Del({keys:e,transactionId:n(this,I)},n(this,E)),this}async type(e){return await n(this,x).Type({key:e,transactionId:n(this,I)},n(this,E)),this}async exec(){let e=await n(this,x).Exec(n(this,I),n(this,E)),t=[];for(let r of e.response)r.members?t.push(r.members):r.nil!==void 0?t.push(null):r.num!==void 0?t.push(r.num):r.values!==void 0?t.push(r.values.values):r.str!==void 0?t.push(r.str):r.dbl!==void 0&&t.push(r.dbl);return t}async discard(){await n(this,x).Discard(n(this,I),n(this,E))}async watch(...e){return await n(this,x).Watch({keys:e,transactionId:n(this,I)},n(this,E)),this}async unwatch(){return await n(this,x).Unwatch(n(this,I),n(this,E)),this}async getRange(e,t,r){return await n(this,x).GetRange({key:e,start:t,end:r,transactionId:n(this,I)},n(this,E)),this}async setRange(e,t,r){return await n(this,x).SetRange({key:e,offset:t,value:r,transactionId:n(this,I)},n(this,E)),this}async strlen(e){return this.strLen(e)}async strLen(e){return await n(this,x).Strlen({key:e,transactionId:n(this,I)},n(this,E)),this}async mget(e){return this.mGet(e)}async mGet(e){return await n(this,x).MGet({keys:e,transactionId:n(this,I)},n(this,E)),this}async mset(e){return this.mSet(e)}async mSet(e){let t=Object.entries(e).map(([r,s])=>({key:r,value:s}));return await n(this,x).MSet({kv:t,transactionId:n(this,I)},n(this,E)),this}async incrBy(e,t){return await n(this,x).IncrBy({key:e,value:t,transactionId:n(this,I)},n(this,E)),this}async expire(e,t){return await n(this,x).Expire({key:e,seconds:t,transactionId:n(this,I)},n(this,E)),this}async expireTime(e){return await n(this,x).ExpireTime({key:e,transactionId:n(this,I)},n(this,E)),this}async zAdd(e,...t){return await n(this,x).ZAdd({key:e,members:t,transactionId:n(this,I)},n(this,E)),this}async zScore(e,t){return await n(this,x).ZScore({key:{key:e,transactionId:n(this,I)},member:t},n(this,E)),this}async zRank(e,t){return await n(this,x).ZRank({key:{key:e,transactionId:n(this,I)},member:t},n(this,E)),this}async zIncrBy(e,t,r){return await n(this,x).ZIncrBy({key:e,member:t,value:r,transactionId:n(this,I)},n(this,E)),this}async zScan(e,t,r,s){let o={key:e,cursor:t,pattern:r,count:s,transactionId:n(this,I)};return await n(this,x).ZScan(o,n(this,E)),this}async zCard(e){return await n(this,x).ZCard({key:e,transactionId:n(this,I)},n(this,E)),this}async zRange(e,t,r,s){let o={rev:!1,byLex:!1,byScore:!1,offset:0,count:1e3};return s?.reverse&&(o.rev=s.reverse),s?.by==="lex"?o.byLex=!0:s?.by==="score"&&(o.byScore=!0),await n(this,x).ZRange({key:{key:e,transactionId:n(this,I)},start:t+"",stop:r+"",...o},n(this,E)),this}async zRem(e,t){return await n(this,x).ZRem({key:{key:e,transactionId:n(this,I)},members:t},n(this,E)),this}async zRemRangeByLex(e,t,r){return await n(this,x).ZRemRangeByLex({key:{key:e,transactionId:n(this,I)},min:t,max:r},n(this,E)),this}async zRemRangeByRank(e,t,r){return await n(this,x).ZRemRangeByRank({key:{key:e,transactionId:n(this,I)},start:t,stop:r},n(this,E)),this}async zRemRangeByScore(e,t,r){return await n(this,x).ZRemRangeByScore({key:{key:e,transactionId:n(this,I)},min:t,max:r},n(this,E)),this}async hgetall(e){return this.hGetAll(e)}async hGetAll(e){return await n(this,x).HGetAll({key:e,transactionId:n(this,I)},n(this,E)),this}async hget(e,t){return this.hGet(e,t)}async hGet(e,t){return await n(this,x).HGet({key:e,field:t,transactionId:n(this,I)},n(this,E)),this}async hMGet(e,t){return await n(this,x).HMGet({key:e,fields:t,transactionId:n(this,I)},n(this,E)),this}async hset(e,t){return this.hSet(e,t)}async hSet(e,t){let r=Object.entries(t).map(([s,o])=>({field:s,value:o}));return await n(this,x).HSet({key:e,fv:r,transactionId:n(this,I)},n(this,E)),this}async hincrby(e,t,r){return this.hIncrBy(e,t,r)}async hIncrBy(e,t,r){return await n(this,x).HIncrBy({key:e,field:t,value:r,transactionId:n(this,I)},n(this,E)),this}async hdel(e,t){return this.hDel(e,t)}async hDel(e,t){return await n(this,x).HDel({key:e,fields:t,transactionId:n(this,I)},n(this,E)),this}async hscan(e,t,r,s){return this.hScan(e,t,r,s)}async hScan(e,t,r,s){let o={key:e,cursor:t,pattern:r,count:s,transactionId:n(this,I)};return await n(this,x).HScan(o,n(this,E)),this}async hkeys(e){return this.hKeys(e)}async hKeys(e){return await n(this,x).HKeys({key:e,transactionId:n(this,I)},n(this,E)),this}async hlen(e){return this.hLen(e)}async hLen(e){return await n(this,x).HLen({key:e,transactionId:n(this,I)},n(this,E)),this}};x=new WeakMap,I=new WeakMap,E=new WeakMap;var T,ci,qo=class qo{constructor(e,t=void 0,r=Jo.INSTALLATION){l(this,T);l(this,ci);a(this,T,e),a(this,ci,t),this.scope=r,this.global=r===Jo.INSTALLATION?new qo(n(this,T),n(this,ci),Jo.GLOBAL):this}get storage(){return n(this,ci)||u.redisPlugin}async watch(...e){let t=await this.storage.Watch({keys:e},n(this,T));return new zo(this.storage,t,n(this,T))}async get(e){try{let t=await this.storage.Get({key:e,scope:this.scope},{...n(this,T),"throw-redis-nil":{values:["true"]}});return t!==null?t.value??void 0:t}catch(t){if(_s(t))return;throw t}}async set(e,t,r){let s;return r?.expiration&&(s=Math.floor((r.expiration.getTime()-Date.now())/1e3),s<1&&(s=1)),(await this.storage.Set({key:e,value:t,nx:r?.nx===!0&&!r.xx,xx:r?.xx===!0&&!r.nx,expiration:s||0,scope:this.scope},n(this,T))).value}async del(...e){await this.storage.Del({keys:e,scope:this.scope},n(this,T))}async incrBy(e,t){return(await this.storage.IncrBy({key:e,value:t,scope:this.scope},n(this,T))).value}async getRange(e,t,r){let s=await this.storage.GetRange({key:e,start:t,end:r,scope:this.scope},n(this,T));return s!==null?s.value:s}async setRange(e,t,r){return(await this.storage.SetRange({key:e,offset:t,value:r,scope:this.scope},n(this,T))).value}async strlen(e){return this.strLen(e)}async strLen(e){return(await this.storage.Strlen({key:e,scope:this.scope},n(this,T))).value}async expire(e,t){await this.storage.Expire({key:e,seconds:t,scope:this.scope},n(this,T))}async expireTime(e){return(await this.storage.ExpireTime({key:e,scope:this.scope},n(this,T))).value}async zAdd(e,...t){return(await this.storage.ZAdd({key:e,members:t,scope:this.scope},n(this,T))).value}async zRange(e,t,r,s){let o={rev:!1,byLex:!1,byScore:!1,offset:0,count:1e3};return s?.reverse&&(o.rev=s.reverse),s?.by==="lex"?o.byLex=!0:s?.by==="score"?o.byScore=!0:(o.offset=0,o.count=0),(await this.storage.ZRange({key:{key:e},start:t+"",stop:r+"",...o,scope:this.scope},n(this,T))).members}async zRem(e,t){return(await this.storage.ZRem({key:{key:e},members:t,scope:this.scope},n(this,T))).value}async zRemRangeByLex(e,t,r){return(await this.storage.ZRemRangeByLex({key:{key:e},min:t,max:r,scope:this.scope},n(this,T))).value}async zRemRangeByRank(e,t,r){return(await this.storage.ZRemRangeByRank({key:{key:e},start:t,stop:r,scope:this.scope},n(this,T))).value}async zRemRangeByScore(e,t,r){return(await this.storage.ZRemRangeByScore({key:{key:e},min:t,max:r,scope:this.scope},n(this,T))).value}async zScore(e,t){try{let r=await this.storage.ZScore({key:{key:e},member:t,scope:this.scope},{...n(this,T),"throw-redis-nil":{values:["true"]}});return r!==null?r.value:r}catch(r){if(_s(r))return;throw r}}async zRank(e,t){try{let r=await this.storage.ZRank({key:{key:e},member:t,scope:this.scope},{...n(this,T),"throw-redis-nil":{values:["true"]}});return r!==null?r.value:r}catch(r){if(_s(r))return;throw r}}async zIncrBy(e,t,r){let s=await this.storage.ZIncrBy({key:e,member:t,value:r,scope:this.scope},n(this,T));return s!==null?s.value:s}async mget(e){return this.mGet(e)}async mGet(e){let t=await this.storage.MGet({keys:e,scope:this.scope},n(this,T));return t!==null?t.values.map(r=>r||null):t}async mset(e){return this.mSet(e)}async mSet(e){let t=Object.entries(e).map(([r,s])=>({key:r,value:s}));await this.storage.MSet({kv:t,scope:this.scope},n(this,T))}async zCard(e){let t=await this.storage.ZCard({key:e,scope:this.scope},n(this,T));return t!==null?t.value:t}async zScan(e,t,r,s){let o={key:e,cursor:t,pattern:r,count:s,scope:this.scope};return await this.storage.ZScan(o,n(this,T))}async type(e){let t=await this.storage.Type({key:e,scope:this.scope},n(this,T));return t!==null?t.value:t}async hget(e,t){return this.hGet(e,t)}async hGet(e,t){try{let r=await this.storage.HGet({key:e,field:t,scope:this.scope},{...n(this,T),"throw-redis-nil":{values:["true"]}});return r!==null?r.value??void 0:r}catch(r){if(_s(r))return;throw r}}async hMGet(e,t){let r=await this.storage.HMGet({key:e,fields:t,scope:this.scope},n(this,T));return r!==null?r.values.map(s=>s||null):r}async hset(e,t){return this.hSet(e,t)}async hSet(e,t){let r=Object.entries(t).map(([o,d])=>({field:o,value:d}));return(await this.storage.HSet({key:e,fv:r,scope:this.scope},n(this,T))).value}async hgetall(e){return this.hGetAll(e)}async hGetAll(e){let t=await this.storage.HGetAll({key:e,scope:this.scope},n(this,T));return t!==null?t.fieldValues:t}async hdel(e,t){return this.hDel(e,t)}async hDel(e,t){return(await this.storage.HDel({key:e,fields:t,scope:this.scope},n(this,T))).value}async hscan(e,t,r,s){return this.hScan(e,t,r,s)}async hScan(e,t,r,s){let o={key:e,cursor:t,pattern:r,count:s,scope:this.scope};return await this.storage.HScan(o,n(this,T))}async hkeys(e){return this.hKeys(e)}async hKeys(e){let t=await this.storage.HKeys({key:e,scope:this.scope},n(this,T));return t!==null?t.keys:t}async hincrby(e,t,r){return this.hIncrBy(e,t,r)}async hIncrBy(e,t,r){return(await this.storage.HIncrBy({key:e,field:t,value:r,scope:this.scope},n(this,T))).value}async hlen(e){return this.hLen(e)}async hLen(e){return(await this.storage.HLen({key:e,scope:this.scope})).value}async bitfield(e,...t){let r=[];for(let o=0;o<t.length;){let d=t[o],c={};switch(d){case"get":{if(o+2>=t.length)throw Error("bitfield command parse failed; not enough arguments for 'get' command");c.get={encoding:t[o+1],offset:t[o+2].toString()},o+=3;break}case"set":{if(o+3>=t.length)throw Error("bitfield command parse failed; not enough arguments for 'set' command");c.set={encoding:t[o+1],offset:t[o+2].toString(),value:t[o+3].toString()},o+=4;break}case"incrBy":{if(o+3>=t.length)throw Error("bitfield command parse failed; not enough arguments for 'incrBy' command");c.incrBy={encoding:t[o+1],offset:t[o+2].toString(),increment:t[o+3].toString()},o+=4;break}case"overflow":{if(o+1>=t.length)throw Error("bitfield command parse failed; not enough arguments for 'overflow' command");let m=t[o+1].toString();c.overflow={behavior:Yc(m)},o+=2;break}default:throw Error(`bitfield command parse failed; ${d} unrecognized (must be 'get', 'set', 'incrBy', or 'overflow')`)}r.push(c)}return(await this.storage.Bitfield({key:e,commands:r})).results}};T=new WeakMap,ci=new WeakMap;var mi=qo;function Yc(i){let e=i.toLowerCase();switch(e){case"wrap":return Go.BITFIELD_OVERFLOW_BEHAVIOR_WRAP;case"sat":return Go.BITFIELD_OVERFLOW_BEHAVIOR_SAT;case"fail":return Go.BITFIELD_OVERFLOW_BEHAVIOR_FAIL;default:throw Error(`unknown bitfield overflow behavior: ${e}`)}}var Ft,pi=class{constructor(e){l(this,Ft);a(this,Ft,e)}async runJob(e){return(await u.schedulerPlugin.Schedule({action:{type:e.name,data:e.data},cron:"cron"in e?e.cron:void 0,when:"runAt"in e?e.runAt:void 0},n(this,Ft))).id}async cancelJob(e){await u.schedulerPlugin.Cancel({id:e},n(this,Ft))}async listJobs(){return(await u.schedulerPlugin.List({after:new Date(0),before:new Date(Date.now()+31536e7)},n(this,Ft))).actions.map(t=>(p(t.request?.action,"Scheduled job is malformed"),"when"in t.request&&t.request.when!=null?{id:t.id,name:t.request.action.type,runAt:t.request.when,data:t.request.action.data}:{id:t.id,name:t.request.action.type,cron:t.request.cron??"",data:t.request.action}))}};Ft=new WeakMap;var Ur,gi=class{constructor(e){l(this,Ur);a(this,Ur,e)}async get(e){return(await this.getAll())[e]}async getAll(){let t=await u.settingsPlugin.GetSettings({},n(this,Ur));if(!t.installationSettings)throw new Error("Could not get installation settings");if(!t.appSettings)throw new Error("Could not get app settings");return{...Md(t.installationSettings.settings,u.installationSettings),...Md(t.appSettings.settings,u.appSettings)}}};Ur=new WeakMap;function Md(i,e){let t=Object.keys(i).reduce((r,s)=>(r[s]=Lo(i[s]),r),{});return e&&Ud(t,e),t}function Ud(i,e){for(let t of e)t.type==="group"?Ud(i,t.fields):!(t.name in i)&&"defaultValue"in t&&(i[t.name]=t.defaultValue)}import{EffectType as Hs,ToastAppearance as Dd}from"@devvit/protos";var Ke,hi,Dr,Ws,js=class{constructor(e){l(this,Ke,[]);l(this,hi);l(this,Dr);l(this,Ws,(e,t)=>{let r=t!==void 0?e:"",s=t!==void 0?t:e;n(this,Ke).push({type:Hs.EFFECT_WEB_VIEW,webView:{postMessage:{webViewId:r,app:{message:s}}}})});a(this,hi,e),a(this,Dr,{postMessage:n(this,Ws)})}get webView(){return n(this,Dr)}showForm(e,t){let r=u.formDefinitions.get(e);if(!r&&n(this,hi)){let d=n(this,hi).forms.get(e);d&&(r={form:d,onSubmit:()=>{}})}if(!r)throw new Error("Form does not exist. Make sure you have added it using Devvit.createForm at the root of your app.");let s=r.form instanceof Function?r.form(t??{}):r.form,o={fields:[],id:e,title:s.title,acceptLabel:s.acceptLabel,cancelLabel:s.cancelLabel,shortDescription:s.description};Pt(s.fields),o.fields=Ue(s.fields),n(this,Ke).push({type:Hs.EFFECT_SHOW_FORM,showForm:{form:o}})}showToast(e){let t;e instanceof Object?t={text:e.text,appearance:e.appearance==="success"?Dd.SUCCESS:Dd.NEUTRAL}:t={text:e},n(this,Ke).push({type:Hs.EFFECT_SHOW_TOAST,showToast:{toast:t}})}navigateTo(e){let t;typeof e=="string"?t=new URL(e).toString():t=new URL(e.permalink,"https://www.reddit.com").toString(),n(this,Ke).push({type:Hs.EFFECT_NAVIGATE_TO_URL,navigateToUrl:{url:t}})}get __effects(){return n(this,Ke)}};Ke=new WeakMap,hi=new WeakMap,Dr=new WeakMap,Ws=new WeakMap;function ke({metadata:i,ui:e,hooks:t,reconciler:r}){let s=new di(i),o=new oi(i),d=new mi(i),c=Sd(d,r?r.state:{}),m=new ui(i),y=new pi(i),v=new gi(i),f=e?new js(r):void 0,S=new ai(i),b=new ni,O=new li(i),L=t&&r?ud(r):void 0,B=t&&r?ld(r):void 0,Y=t&&r?dd(r):void 0,Xt=t&&r?ad(r):void 0;return{modLog:s,kvStore:o,redis:d,reddit:m,scheduler:y,settings:v,media:S,assets:b,realtime:O,get useForm(){return Y??(()=>{throw new Error("useForm() is unavailable")})},get cache(){return c??(()=>{throw new Error("cache() is unavailable")})},get useState(){return L??(()=>{throw new Error("useState() is unavailable")})},get useInterval(){return B??(()=>{throw new Error("useInterval() is unavailable")})},get useChannel(){return Xt??(()=>{throw new Error("useChannel() is unavailable")})},get ui(){if(!f)throw new Error("ui client is not available");return f}}}var Nd={name:"@devvit/public-api",version:"0.11.8-dev",license:"BSD-3-Clause",repository:{type:"git",url:"https://developers.reddit.com/"},type:"module",exports:{".":"./dist/index.js","./package.json":"./package.json","./*":"./dist/*"},main:"./dist/index.js",files:["dist/**"],scripts:{build:"yarn build:icon-types && yarn build:semantic-colors && tsc && cp -af devvit.tsconfig.json dist/ && yarn build:types && yarn build:min && yarn build:unmin","build:icon-types":"make-icons src/types/icons.ts","build:min":"esbuild --bundle --sourcemap=linked --target=es2020 --format=esm --metafile=dist/meta.min.json --outfile=dist/public-api.min.js --external:@devvit/protos --minify src/index.ts","build:semantic-colors":"node scripts/make-semantic-colors.js","build:types":"api-extractor run && sed -ne '/declare global {/,$ p' src/devvit/Devvit.ts >> dist/public-api.d.ts","build:unmin":"esbuild --bundle --sourcemap=inline --target=es2020 --format=iife --metafile=dist/meta.json --outfile=dist/public-api.iife.js --global-name=devvitPublicAPI src/index.ts",clean:"rm -rf .turbo api-extractor coverage dist src/devvit/internals/semanticColors.ts src/types/icons.ts || :",clobber:"yarn clean && rm -rf node_modules",dev:"tsc -w","dev:build":"chokidar ./src ../shared-types/dist --command 'yarn build' --ignore './src/types/icons.ts' --ignore './src/devvit/internals/semanticColors.ts'",lint:"redlint .","lint:fix":"yarn lint --fix",prepublishOnly:"publish-package-json",test:"yarn test:unit && yarn test:types && yarn test:size","test:size":"filesize","test:types":"tsc --noEmit","test:unit":"vitest run","test:unit-with-coverage":"vitest run --coverage"},types:"./dist/index.d.ts",dependencies:{"@devvit/protos":"0.11.8-dev","@devvit/shared-types":"0.11.8-dev","base64-js":"1.5.1","clone-deep":"4.0.1",moderndash:"4.0.0"},devDependencies:{"@ampproject/filesize":"4.3.0","@devvit/repo-tools":"0.11.8-dev","@devvit/tsconfig":"0.11.8-dev","@microsoft/api-extractor":"7.41.0","@reddit/faceplate-ui":"18.0.1","@types/clone-deep":"4.0.1","@vitest/coverage-c8":"0.32.0","chokidar-cli":"3.0.0",esbuild:"0.23.0",eslint:"9.11.1",typescript:"5.3.2",vitest:"1.6.0"},publishConfig:{directory:"dist"},filesize:{"dist/public-api.min.js":{gzip:"60 KB",none:"212 KB"}},source:"./src/index.ts"};function se(i,e,t){let r=i[P.Subreddit]?.values[0];p(r,"subreddit is missing from Context");let s=i[P.SubredditName]?.values[0],o=i[P.AppUser]?.values[0],d=i[P.App]?.values[0],c=i[P.Version]?.values[0],m=i[P.User]?.values[0],y=tm(i);return{get appAccountId(){return p(o,"appAccountId is missing from Context"),o},subredditId:r,subredditName:s,userId:m,postId:e,commentId:t,appName:d,appVersion:c,debug:y,toJSON(){return{appAccountId:o,appName:d,appVersion:c,subredditId:r,subredditName:s,userId:m,postId:e,commentId:t,debug:y}}}}function tm(i){let e={blocks:void 0,emitSnapshots:void 0,emitState:void 0,realtime:void 0,runtime:void 0,surface:void 0,useAsync:void 0,payments:void 0,bootstrap:void 0,webView:void 0},t={};for(let s in e)t[s.toLowerCase()]=s;let r={};for(let s of(i[P.Debug]?.values??[]).join().split(",")){let[o,d]=s.split("=");o&&(o=o.trim(),d=d?.trim(),o.toLowerCase()in t&&(o=t[o.toLowerCase()]),r[o]??(r[o]=d||"true"))}return i[P.Debug]&&console.info(`[api] @devvit/public-api v${Nd.version} ${Object.entries(r).map(([s,o])=>`${s}=${o}`).join(" ")}`),{...r,metadata:i}}function Ld(i){return i.flatMap(e=>e.type==="group"?Ld(e.fields):e)}async function Vs(i,e,t){if(!e)throw new Error("Settings were not defined.");let r={success:!0,errors:{}},s=Je(i.fieldValues),o=Ld(e);return await Promise.all(o.map(async d=>{let c=d.name;if(c&&d.onValidate){let m=s[c],y=d.onValidate,v=Object.assign(ke({metadata:t}),se(t)),f=await y({value:m,isEditing:i.editing},v);f&&(r.success=!1,r.errors[c]=f)}})),im.fromJSON(r)}async function sm(){if(!u.appSettings)throw new Error("App settings were not defined.");return nm.fromJSON({fields:{fields:Ue(u.appSettings)}})}async function om(i,e){return Vs(i,u.appSettings,e)}function _d(i){i.provides(rm),R("GetAppSettingsFields",sm),R("ValidateAppForm",om)}import{CustomPostDefinition as pm,RenderPostResponse as gm}from"@devvit/protos";import{BlockRenderEventType as aa,EffectType as el}from"@devvit/protos";function fi(i){return i.__effects}function Hd(){let i=new Set;return e=>{let t=e,r=1;for(;i.has(t);)t=`${e}.${r++}`;return i.add(t),t}}import{BlockActionType as oa,BlockAvatarBackground as Zd,BlockAvatarFacing as Xd,BlockAvatarSize as Ze,BlockBorderWidth as qs,BlockButtonAppearance as Xe,BlockButtonSize as Qo,BlockGap as $s,BlockHorizontalAlignment as Yo,BlockIconSize as Ks,BlockImageResizeMode as Nr,BlockPadding as Lr,BlockRadius as _r,BlockSpacerShape as ea,BlockSpacerSize as Zs,BlockStackDirection as ta,BlockTextOutline as ia,BlockTextOverflow as ra,BlockTextSize as yi,BlockTextStyle as na,BlockTextWeight as Qd,BlockType as Ae,BlockVerticalAlignment as sa}from"@devvit/protos";var $o={"alienblue-100":"#DCE2FB","alienblue-200":"#B8C5FC","alienblue-25":"#F7F8FD","alienblue-300":"#90A9FD","alienblue-400":"#648EFC","alienblue-50":"#EEF0FB","alienblue-500":"#1870F4","alienblue-600":"#115BCA","alienblue-700":"#0A449B","alienblue-75":"#E6E9FB","alienblue-800":"#0A2F6C","alienblue-900":"#0A1A3F","alienblue-950":"#07102B","berrypurple-100":"#F3DAFB","berrypurple-200":"#EAB3FD","berrypurple-25":"#FBF6FD","berrypurple-300":"#DE8BFF","berrypurple-400":"#CF5FFF","berrypurple-50":"#F8EDFC","berrypurple-500":"#BC0EFF","berrypurple-600":"#9B00D4","berrypurple-700":"#7600A3","berrypurple-75":"#F6E4FB","berrypurple-800":"#520472","berrypurple-900":"#300643","berrypurple-950":"#20042A",black:"#000000","black-opacity-0":"#00000000","black-opacity-10":"#00000019","black-opacity-15":"#00000026","black-opacity-20":"#00000033","black-opacity-25":"#0000003F","black-opacity-33":"#00000054","black-opacity-5":"#0000000C","black-opacity-50":"#0000007F","black-opacity-60":"#00000099","black-opacity-67":"#000000AA","black-opacity-80":"#000000CC","black-opacity-90":"#000000E5","brown-100":"#F1DFCF","brown-200":"#E9BE95","brown-25":"#FBF7F4","brown-300":"#DC9D5D","brown-400":"#BA854E","brown-50":"#F7EFE9","brown-500":"#9A6D3F","brown-600":"#7B5631","brown-700":"#5D4023","brown-75":"#F4E7DC","brown-800":"#3F2C19","brown-900":"#221A11","brown-950":"#15100A","coolgray-100":"#DBE4E9","coolgray-150":"#C9D7DE","coolgray-200":"#B7CAD4","coolgray-25":"#F6F8F9","coolgray-250":"#A4BDCA","coolgray-300":"#97AFBC","coolgray-350":"#8BA2AD","coolgray-400":"#7F949F","coolgray-450":"#748791","coolgray-50":"#EEF1F3","coolgray-500":"#667780","coolgray-525":"#576F76","coolgray-550":"#5C6C74","coolgray-600":"#536168","coolgray-650":"#48545B","coolgray-700":"#3D494E","coolgray-75":"#E5EBEE","coolgray-750":"#333D42","coolgray-800":"#2A3236","coolgray-850":"#21272A","coolgray-900":"#181C1F","coolgray-950":"#0E1113","global-black":{light:"#000000",dark:"#000000"},"global-brand-orangered":{light:"#FF4500",dark:"#FF4500"},"global-white":{light:"#FFFFFF",dark:"#FFFFFF"},"kiwigreen-100":"#A8F5A0","kiwigreen-200":"#58E15B","kiwigreen-25":"#EBFDE7","kiwigreen-300":"#00C61C","kiwigreen-400":"#01A816","kiwigreen-50":"#DDF8D7","kiwigreen-500":"#008A10","kiwigreen-600":"#016E0B","kiwigreen-700":"#005306","kiwigreen-75":"#CAF5C2","kiwigreen-800":"#033902","kiwigreen-900":"#0D2005","kiwigreen-950":"#081404","lightblue-100":"#CAE7FB","lightblue-200":"#87D0FD","lightblue-25":"#F3F9FD","lightblue-300":"#02B9FB","lightblue-400":"#029DD5","lightblue-50":"#E6F3FC","lightblue-500":"#007FAE","lightblue-600":"#01668D","lightblue-700":"#014D6B","lightblue-75":"#D9EDFB","lightblue-800":"#03354B","lightblue-900":"#051E2B","lightblue-950":"#04131A","lime-100":"#B7F28E","lime-200":"#90DA58","lime-25":"#EEFDDC","lime-300":"#6DBF01","lime-400":"#5BA200","lime-50":"#E0F8C8","lime-500":"#4A8500","lime-600":"#3A6A00","lime-700":"#2A5000","lime-75":"#CEF5AD","lime-800":"#1E3702","lime-900":"#151E05","lime-950":"#0D1304","mintgreen-100":"#9BF5D9","mintgreen-200":"#00E2B7","mintgreen-25":"#E7FDF5","mintgreen-300":"#00C29D","mintgreen-400":"#01A484","mintgreen-50":"#D7F8EC","mintgreen-500":"#01876D","mintgreen-600":"#006C56","mintgreen-700":"#015140","mintgreen-75":"#C0F5E3","mintgreen-800":"#00382B","mintgreen-900":"#032019","mintgreen-950":"#03140F","orangered-100":"#FCDBCF","orangered-200":"#FDB498","orangered-25":"#FDF6F4","orangered-300":"#FF895D","orangered-400":"#FF4500","orangered-50":"#FCEEE8","orangered-500":"#D93900","orangered-600":"#AE2C00","orangered-700":"#842100","orangered-75":"#FBE5DC","orangered-800":"#591B02","orangered-900":"#2F1405","orangered-950":"#1C0D04","periwinkle-100":"#E6DFFB","periwinkle-200":"#CDBEFD","periwinkle-25":"#F9F7FD","periwinkle-300":"#B29FFF","periwinkle-400":"#9580FF","periwinkle-50":"#F2EFFC","periwinkle-500":"#6A5CFF","periwinkle-600":"#523DFF","periwinkle-700":"#4001EA","periwinkle-75":"#ECE7FB","periwinkle-800":"#250AA6","periwinkle-900":"#160E5B","periwinkle-950":"#0C083F","poopbrown-100":"#FEEEDD","poopbrown-200":"#F6DDC3","poopbrown-300":"#EECCAA","poopbrown-400":"#CAA075","poopbrown-50":"#FEF7EE","poopbrown-500":"#9A6D3F","poopbrown-600":"#6E4924","poopbrown-700":"#54371A","poopbrown-800":"#3B2510","poopbrown-900":"#29190A","poopbrown-950":"#110B04","puregray-100":"#F2F2F2","puregray-150":"#EBEBEB","puregray-200":"#E4E4E4","puregray-250":"#DDDDDD","puregray-300":"#D6D6D6","puregray-350":"#C3C3C3","puregray-400":"#ACACAC","puregray-450":"#919191","puregray-50":"#F8F8F8","puregray-500":"#767676","puregray-550":"#5C5C5C","puregray-600":"#434343","puregray-650":"#393939","puregray-700":"#303030","puregray-750":"#272727","puregray-800":"#1E1E1E","puregray-850":"#181818","puregray-900":"#131313","puregray-950":"#080808","red-100":"#FBDBD4","red-200":"#FDB3A4","red-25":"#FDF6F5","red-300":"#FF8773","red-400":"#FF4F40","red-50":"#FCEEEA","red-500":"#EB001F","red-600":"#BC0117","red-700":"#90000F","red-75":"#FBE4DF","red-800":"#650405","red-900":"#340F05","red-950":"#1F0B04","sakurapink-100":"#FBD9EB","sakurapink-200":"#FDAEDA","sakurapink-25":"#FDF6F9","sakurapink-300":"#FF7ECA","sakurapink-400":"#FF38BB","sakurapink-50":"#FCEDF4","sakurapink-500":"#DE019F","sakurapink-600":"#B2007F","sakurapink-700":"#880060","sakurapink-75":"#FBE3EF","sakurapink-800":"#5F0443","sakurapink-900":"#380626","sakurapink-950":"#250419",transparent:"transparent",white:"#ffffff","white-opacity-0":"#FFFFFF00","white-opacity-10":"#FFFFFF19","white-opacity-15":"#FFFFFF26","white-opacity-20":"#FFFFFF33","white-opacity-25":"#FFFFFF3F","white-opacity-5":"#FFFFFF0C","white-opacity-50":"#FFFFFF7F","yellow-100":"#FFE284","yellow-200":"#FFBF0B","yellow-25":"#FFF9E0","yellow-300":"#D8A100","yellow-400":"#B78800","yellow-50":"#FFF3C0","yellow-500":"#977000","yellow-600":"#785800","yellow-700":"#5B4200","yellow-75":"#FFEAA2","yellow-800":"#3F2D00","yellow-900":"#231A03","yellow-950":"#161003","yelloworange-100":"#FCDCC8","yelloworange-200":"#FDB586","yelloworange-25":"#FDF7F3","yelloworange-300":"#FF8A35","yelloworange-400":"#E46C00","yelloworange-50":"#FCEEE6","yelloworange-500":"#BD5800","yelloworange-600":"#974500","yelloworange-700":"#733300","yelloworange-75":"#FBE5D7","yelloworange-800":"#4E2402","yelloworange-900":"#2A1705","yelloworange-950":"#1A0E04","action-downvote":{light:"#6A5CFF",dark:"#6A5CFF"},"action-upvote":{light:"#D93900",dark:"#D93900"},"ai-background-weaker":{light:"#E7FDF5",dark:"#00382B"},"ai-plain":{light:"#006C56",dark:"#01A484"},"ai-plain-hover":{light:"#015140",dark:"#00C29D"},"alert-caution":{light:"#977000",dark:"#977000"},"avatar-gradient":{light:"",dark:""},"brand-background":{light:"#D93900",dark:"#D93900"},"brand-background-hover":{light:"#AE2C00",dark:"#AE2C00"},"brand-gradient-active":{light:"",dark:""},"brand-gradient-active-highlight":{light:"",dark:""},"brand-gradient-default":{light:"",dark:""},"brand-gradient-default-highlight":{light:"",dark:""},"brand-gradient-hover":{light:"",dark:""},"brand-gradient-hover-highlight":{light:"",dark:""},"brand-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"category-live":{light:"#D93900",dark:"#D93900"},"category-nsfw":{light:"#DE019F",dark:"#DE019F"},"category-spoiler":{light:"#131313",dark:"#F2F2F2"},"caution-background":{light:"#FFBF0B",dark:"#D8A100"},"caution-background-hover":{light:"#D8A100",dark:"#FFBF0B"},"caution-onBackground":{light:"#000000",dark:"#000000"},"caution-plain":{light:"#785800",dark:"#FFBF0B"},"caution-plain-hover":{light:"#5B4200",dark:"#FFE284"},"danger-background":{light:"#EB001F",dark:"#BC0117"},"danger-background-disabled":{light:"#FDB3A4",dark:"#340F05"},"danger-background-hover":{light:"#BC0117",dark:"#EB001F"},"danger-background-weaker":{light:"#FBDBD4",dark:"#650405"},"danger-content":{light:"#BC0117",dark:"#FF4F40"},"danger-content-default":{light:"#ffffff",dark:"#ffffff"},"danger-content-hover":{light:"#90000F",dark:"#FF8773"},"danger-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"danger-plain":{light:"#BC0117",dark:"#FF8773"},"danger-plain-hover":{light:"#90000F",dark:"#FDB3A4"},"downvote-background":{light:"#6A5CFF",dark:"#6A5CFF"},"downvote-background-disabled":{light:"#6a5cff4d",dark:"#6a5cff4d"},"downvote-background-hover":{light:"#523DFF",dark:"#523DFF"},"downvote-content":{light:"#523DFF",dark:"#9580FF"},"downvote-content-weak":{light:"#6A5CFF",dark:"#6A5CFF"},"downvote-disabled":{light:"#523DFF4c",dark:"#9580FF4c"},"downvote-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"downvote-onStrongScrim":{light:"#B29FFF",dark:"#B29FFF"},"downvote-onStrongScrim-disabled":{light:"#b29fff4d",dark:"#b29fff4d"},"downvote-onStrongScrim-weaker":{light:"#9580FF",dark:"#9580FF"},"downvote-plain":{light:"#523DFF",dark:"#9580FF"},"downvote-plain-disabled":{light:"#523dff4d",dark:"#9580ff4d"},"downvote-plain-weaker":{light:"#6A5CFF",dark:"#6A5CFF"},"elevation-large1":{light:"#0000003F",dark:"#0000007F"},"elevation-large2":{light:"#00000026",dark:"#00000033"},"elevation-medium1":{light:"#0000003F",dark:"#0000007F"},"elevation-medium2":{light:"#00000019",dark:"#00000033"},"elevation-small":{light:"#00000026",dark:"#00000054"},"elevation-xsmall":{light:"#0000003F",dark:"#000000AA"},favorite:{light:"#977000",dark:"#B78800"},"global-admin":{light:"#D93900",dark:"#D93900"},"global-alienblue":{light:"#1870F4",dark:"#1870F4"},"global-darkblue":{light:"#2A3236",dark:"#2A3236"},"global-focus":{light:"#029DD5",dark:"#007FAE"},"global-gold":{light:"#B78800",dark:"#D8A100"},"global-moderator":{light:"#008A10",dark:"#008A10"},"global-nsfw":{light:"#DE019F",dark:"#DE019F"},"global-offline":{light:"#667780",dark:"#667780"},"global-online":{light:"#00C61C",dark:"#00C61C"},"global-orangered":{light:"#FF4500",dark:"#FF4500"},"global-stars":{light:"#977000",dark:"#D8A100"},"gradient-media":{light:"",dark:""},"gradient-media-strong":{light:"",dark:""},"identity-admin":{light:"#D93900",dark:"#D93900"},"identity-coins":{light:"#B78800",dark:"#B78800"},"identity-moderator":{light:"#008A10",dark:"#008A10"},"identity-self":{light:"#01876D",dark:"#01876D"},"interactive-background-disabled":{light:"#0000000C",dark:"#FFFFFF0C"},"interactive-content-disabled":{light:"#0000003F",dark:"#FFFFFF3F"},"interactive-focused":{light:"#007FAE",dark:"#007FAE"},"interactive-pressed":{light:"#00000026",dark:"#FFFFFF26"},"inverted-interactive-background-disabled":{light:"#FFFFFF0C",dark:"#0000000C"},"inverted-interactive-content-disabled":{light:"#FFFFFF3F",dark:"#0000003F"},"inverted-interactive-pressed":{light:"#FFFFFF26",dark:"#00000026"},"inverted-neutral-background":{light:"#0E1113",dark:"#FFFFFF"},"inverted-neutral-background-hover":{light:"#181C1F",dark:"#F6F8F9"},"inverted-neutral-border":{light:"#FFFFFF33",dark:"#00000033"},"inverted-neutral-content":{light:"#B7CAD4",dark:"#333D42"},"inverted-neutral-content-strong":{light:"#EEF1F3",dark:"#181C1F"},"inverted-secondary-background":{light:"#2A3236",dark:"#E5EBEE"},"inverted-secondary-background-hover":{light:"#333D42",dark:"#DBE4E9"},"inverted-secondary-background-selected":{light:"#3D494E",dark:"#C9D7DE"},"inverted-secondary-onBackground":{light:"#FFFFFF",dark:"#000000"},"inverted-secondary-plain":{light:"#DBE4E9",dark:"#181C1F"},"inverted-secondary-plain-hover":{light:"#FFFFFF",dark:"#000000"},"media-background":{light:"#00000099",dark:"#00000099"},"media-background-hover":{light:"#000000cc",dark:"#000000cc"},"media-background-selected":{light:"#000000cc",dark:"#000000cc"},"media-border-selected":{light:"#FFFFFF",dark:"#FFFFFF"},"media-border-weak":{light:"#FFFFFF19",dark:"#FFFFFF19"},"media-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"media-onBackground-disabled":{light:"#FFFFFF3F",dark:"#FFFFFF3F"},"media-onBackground-weak":{light:"#E5EBEE",dark:"#E5EBEE"},"media-onbackground":{light:"#ffffff",dark:"#ffffff"},"media-onbackground-disabled":{light:"#ffffff3f",dark:"#ffffff3f"},"media-onbackground-weak":{light:"#B7CAD4",dark:"#B7CAD4"},"neutral-background":{light:"#FFFFFF",dark:"#0E1113"},"neutral-background-container":{light:"#F6F8F9",dark:"#181C1F"},"neutral-background-container-hover":{light:"#EEF1F3",dark:"#21272A"},"neutral-background-container-strong":{light:"#EEF1F3",dark:"#21272A"},"neutral-background-container-strong-hover":{light:"#E5EBEE",dark:"#2A3236"},"neutral-background-gilded":{light:"#FFF9E0",dark:"#181C1F"},"neutral-background-gilded-hover":{light:"#FFF3C0",dark:"#21272A"},"neutral-background-hover":{light:"#F6F8F9",dark:"#181C1F"},"neutral-background-medium":{light:"#F8F8F8",dark:"#131313"},"neutral-background-pinned":{light:"#FFFFFF",dark:"#0E1113"},"neutral-background-selected":{light:"#E5EBEE",dark:"#2A3236"},"neutral-background-strong":{light:"#FFFFFF",dark:"#181C1F"},"neutral-background-strong-hover":{light:"#F6F8F9",dark:"#21272A"},"neutral-background-weak":{light:"#F6F8F9",dark:"#000000"},"neutral-background-weak-hover":{light:"#EEF1F3",dark:"#0E1113"},"neutral-border":{light:"#00000033",dark:"#FFFFFF33"},"neutral-border-medium":{light:"#0000007F",dark:"#FFFFFF7F"},"neutral-border-strong":{light:"#181C1F",dark:"#F6F8F9"},"neutral-border-weak":{light:"#00000019",dark:"#FFFFFF19"},"neutral-content":{light:"#333D42",dark:"#B7CAD4"},"neutral-content-disabled":{light:"#D6D6D6",dark:"#303030"},"neutral-content-strong":{light:"#181C1F",dark:"#EEF1F3"},"neutral-content-weak":{light:"#5C6C74",dark:"#8BA2AD"},offline:{light:"#767676",dark:"#767676"},online:{light:"#01A816",dark:"#01A816"},"opacity-08":{light:"#13131314",dark:"#13131314"},"opacity-50":{light:"#0000007f",dark:"#F2F2F27f"},"opacity-highlight":{light:"",dark:""},pizzaRed:{light:"#ef5350",dark:"#c62828"},primary:{light:"#115BCA",dark:"#648EFC"},"primary-background":{light:"#0A449B",dark:"#115BCA"},"primary-background-hover":{light:"#0A2F6C",dark:"#1870F4"},"primary-background-selected":{light:"#0A1A3F",dark:"#648EFC"},"primary-border":{light:"#0A449B",dark:"#648EFC"},"primary-border-hover":{light:"#0A2F6C",dark:"#90A9FD"},"primary-hover":{light:"#0A449B",dark:"#90A9FD"},"primary-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"primary-onBackground-selected":{light:"#FFFFFF",dark:"#000000"},"primary-plain":{light:"#0A449B",dark:"#648EFC"},"primary-plain-hover":{light:"#0A2F6C",dark:"#90A9FD"},"primary-plain-visited":{light:"#7600A3",dark:"#CF5FFF"},"primary-visited":{light:"#9B00D4",dark:"#CF5FFF"},scrim:{light:"#00000099",dark:"#00000099"},"scrim-background":{light:"#00000099",dark:"#00000099"},"scrim-background-strong":{light:"#000000CC",dark:"#000000CC"},"scrim-gradient":{light:"",dark:""},"scrim-strong":{light:"#000000cc",dark:"#000000cc"},secondary:{light:"#21272A",dark:"#DBE4E9"},"secondary-background":{light:"#E5EBEE",dark:"#2A3236"},"secondary-background-hover":{light:"#DBE4E9",dark:"#333D42"},"secondary-background-selected":{light:"#C9D7DE",dark:"#3D494E"},"secondary-hover":{light:"#000000",dark:"#ffffff"},"secondary-onBackground":{light:"#000000",dark:"#FFFFFF"},"secondary-plain":{light:"#181C1F",dark:"#DBE4E9"},"secondary-plain-hover":{light:"#000000",dark:"#FFFFFF"},"secondary-plain-weak":{light:"#5C6C74",dark:"#8BA2AD"},"secondary-weak":{light:"#576F76",dark:"#748791"},"success-background":{light:"#008A10",dark:"#016E0B"},"success-background-hover":{light:"#016E0B",dark:"#008A10"},"success-content":{light:"#016E0B",dark:"#01A816"},"success-hover":{light:"#005306",dark:"#00C61C"},"success-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"success-plain":{light:"#016E0B",dark:"#00C61C"},"success-plain-hover":{light:"#005306",dark:"#58E15B"},"tone-1":{light:"#131313",dark:"#F2F2F2"},"tone-2":{light:"#434343",dark:"#ACACAC"},"tone-3":{light:"#ACACAC",dark:"#434343"},"tone-4":{light:"#E4E4E4",dark:"#303030"},"tone-5":{light:"#F2F2F2",dark:"#1E1E1E"},"tone-6":{light:"#F8F8F8",dark:"#131313"},"tone-7":{light:"#ffffff",dark:"#080808"},"transparent-background-hover":{light:"#74879119",dark:"#66778019"},"ui-canvas":{light:"#F2F2F2",dark:"#080808"},"ui-modalbackground":{light:"#FFFFFF",dark:"#181C1F"},"upvote-background":{light:"#D93900",dark:"#D93900"},"upvote-background-disabled":{light:"#d939004d",dark:"#d939004d"},"upvote-background-hover":{light:"#AE2C00",dark:"#AE2C00"},"upvote-content":{light:"#AE2C00",dark:"#FF4500"},"upvote-content-weak":{light:"#FF4500",dark:"#FF4500"},"upvote-disabled":{light:"#AE2C004c",dark:"#FF45004c"},"upvote-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"upvote-onStrongScrim":{light:"#FF895D",dark:"#FF895D"},"upvote-onStrongScrim-disabled":{light:"#ff895d4d",dark:"#ff895d4d"},"upvote-onStrongScrim-weaker":{light:"#FF4500",dark:"#FF4500"},"upvote-plain":{light:"#AE2C00",dark:"#FF895D"},"upvote-plain-disabled":{light:"#ae2c004d",dark:"#ff895d4d"},"upvote-plain-weaker":{light:"#FF4500",dark:"#FF4500"},"warning-background":{light:"#B78800",dark:"#B78800"},"warning-background-hover":{light:"#977000",dark:"#D8A100"},"warning-content":{light:"#785800",dark:"#B78800"},"warning-content-hover":{light:"#5B4200",dark:"#D8A100"},"warning-onBackground":{light:"#000000",dark:"#000000"}};var jd={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",rebeccapurple:"#663399",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",transparent:"#FFFFFF00",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"},Wd=i=>!!i.match(/^(#[0-9a-fA-F]{3,8}).*/),Vd=i=>i in $o,Ko=i=>i in jd,Gd=i=>!!i.match(/^rgba?\(.*/),Jd=i=>!!i.match(/^hsla?\(.*/),zd=(i,e="light")=>{if(Ko(i))return Gs(i);let r=$o[i];return typeof r=="string"?r:r[e]},Gs=i=>jd[i]??i,qd=i=>{let[e,t,r,s]=i.replace(/^rgba?\(|\s+|\)$/g,"").split(",");if(!e||!t||!r)return i;let d=[...[e,t,r].map(m=>parseFloat(m))];if(s){let m=parseFloat(s),y=Math.round(m*255);d.push(y)}return`#${d.map(m=>m.toString(16).padStart(2,"0")).join("")}`};import{BlockStackDirection as Js}from"@devvit/protos";var Zo={stackParentLayout:{hasHeight:!0,hasWidth:!0,direction:Js.UNRECOGNIZED,alignment:void 0}};function Kd(i,e,t){if(!e)return{hasHeight:!1,hasWidth:!1};let{growDirection:r,stretchDirection:s}=am(i?.grow,e.direction,e.alignment),o=t?.height?.value?.value||t?.height?.min?.value||$d(2,r,s,e.hasHeight),d=t?.width?.value?.value||t?.width?.min?.value||$d(1,r,s,e.hasWidth);return{hasHeight:!!o,hasWidth:!!d}}function $d(i,e,t,r){return e===i&&r||t===i&&r}function am(i,e,t){let r=e===Js.STACK_VERTICAL||e===Js.UNRECOGNIZED,s=e===Js.STACK_HORIZONTAL,o=0;s&&i?o=1:r&&i&&(o=2);let d=t===void 0||t.horizontal===void 0,c=t===void 0||t.vertical===void 0,m=s?!!c:r?!!d:!1,y=0;return s&&m?y=2:r&&m&&(y=1),{growDirection:o,stretchDirection:y}}import{BlockSizeUnit as xt,BlockStackDirection as zs}from"@devvit/protos";function bi(i){if(i==null)return;if(typeof i=="number")return{value:i,unit:xt.SIZE_UNIT_PERCENT};let e=i.match(/^(\d+(?:\.\d+)?)(px|%)?$/);if(e==null)return;let t=xt.SIZE_UNIT_PERCENT;return e.at(2)==="px"&&(t=xt.SIZE_UNIT_PIXELS),{value:Number.parseFloat(e[1]),unit:t}}function dm(i,e){return(i.width?.value?.unit===xt.SIZE_UNIT_PERCENT||i.width?.min?.unit===xt.SIZE_UNIT_PERCENT)&&(e.direction===zs.STACK_HORIZONTAL||e.direction===zs.STACK_DEPTH)&&(e.hasWidth||(i.width=void 0)),(i.height?.value?.unit===xt.SIZE_UNIT_PERCENT||i.height?.min?.unit===xt.SIZE_UNIT_PERCENT)&&(e.direction===zs.STACK_VERTICAL||e.direction===zs.STACK_DEPTH)&&(e.hasHeight||(i.height=void 0)),i}function Xo(i,e){if(i){let t=i.width!=null||i.minWidth!=null||i.maxWidth!=null,r=i.height!=null||i.minHeight!=null||i.maxHeight!=null;if(t||r||i.grow!=null){let s={width:t?{value:bi(i.width),min:bi(i.minWidth),max:bi(i.maxWidth)}:void 0,height:r?{value:bi(i.height),min:bi(i.minHeight),max:bi(i.maxHeight)}:void 0,grow:i.grow};return e.stackParentLayout&&(s=dm(s,e.stackParentLayout)),s}}}var Yd="data-",lm=new Set(["onPress","onMessage"]),um=new Map([["onPress",oa.ACTION_CLICK],["onMessage",oa.ACTION_WEBVIEW]]),Hr,vi=class{constructor(e=()=>{}){l(this,Hr);a(this,Hr,e)}createBlocksElementOrThrow({type:e,props:t,children:r}){let s=this.createBlocksElement({type:e,props:t,children:r},Zo);if(!s)throw new Error(`Could not create block of type ${e}`);return s}createBlocksElement({type:e,props:t,children:r},s){switch(e){case"blocks":return this.makeRoot(t,...r);case"hstack":return this.makeHStack(t,s,...r);case"vstack":return this.makeVStack(t,s,...r);case"zstack":return this.makeZStack(t,s,...r);case"text":return this.makeText(t,s,...r);case"button":return this.makeButton(t,s,...r);case"image":return this.makeImage(t,s);case"spacer":return this.makeSpacer(t,s);case"icon":return this.makeIcon(t,s);case"avatar":return this.makeAvatar(t,s);case"webview":return this.makeWebView(t,s);case"__fragment":throw new Error("root fragment is not supported - use 'blocks' instead")}}makeRootHeight(e){switch(e){case"regular":return 320;case"tall":return 512}}makeBlockPadding(e){switch(e){case"none":return Lr.PADDING_NONE;case"xsmall":return Lr.PADDING_XSMALL;case"small":return Lr.PADDING_SMALL;case"medium":return Lr.PADDING_MEDIUM;case"large":return Lr.PADDING_LARGE}}makeBlockRadius(e){switch(e){case"none":return _r.RADIUS_NONE;case"small":return _r.RADIUS_SMALL;case"medium":return _r.RADIUS_MEDIUM;case"large":return _r.RADIUS_LARGE;case"full":return _r.RADIUS_FULL}}makeBlockGap(e){switch(e){case"none":return $s.GAP_NONE;case"small":return $s.GAP_SMALL;case"medium":return $s.GAP_MEDIUM;case"large":return $s.GAP_LARGE}}makeBlockAlignment(e){if(e===void 0)return;let t,r;if(e.includes("top")?t=sa.ALIGN_TOP:e.includes("middle")?t=sa.ALIGN_MIDDLE:e.includes("bottom")&&(t=sa.ALIGN_BOTTOM),e.includes("start")?r=Yo.ALIGN_START:e.includes("center")?r=Yo.ALIGN_CENTER:e.includes("end")&&(r=Yo.ALIGN_END),t!==void 0||r!==void 0)return{vertical:t,horizontal:r}}makeBlockBorder(e,t,r,s){if(!e&&!t)return;let o;switch(e){case"none":o=qs.BORDER_WIDTH_NONE;break;case"thin":o=qs.BORDER_WIDTH_THIN;break;case"thick":o=qs.BORDER_WIDTH_THICK;break;default:o=qs.BORDER_WIDTH_THIN;break}let d=t??"neutral-border-weak",c=this.getThemedColors(d,r,s);return{width:o,color:c?.light,colors:c}}makeBlockTextSize(e){switch(e){case"xsmall":return yi.TEXT_SIZE_XSMALL;case"small":return yi.TEXT_SIZE_SMALL;case"medium":return yi.TEXT_SIZE_MEDIUM;case"large":return yi.TEXT_SIZE_LARGE;case"xlarge":return yi.TEXT_SIZE_XLARGE;case"xxlarge":return yi.TEXT_SIZE_XXLARGE}}makeBlockTextStyle(e){switch(e){case"body":return na.TEXT_STYLE_BODY;case"metadata":return na.TEXT_STYLE_METADATA;case"heading":return na.TEXT_STYLE_HEADING}}makeBlockTextOutline(e){switch(e){case"none":return ia.TEXT_OUTLINE_NONE;case"thin":return ia.TEXT_OUTLINE_THIN;case"thick":return ia.TEXT_OUTLINE_THICK}}makeBlockTextWeight(e){switch(e){case"regular":return Qd.TEXT_WEIGHT_REGULAR;case"bold":return Qd.TEXT_WEIGHT_BOLD}}makeBlockTextOverflow(e){switch(e){case"clip":return ra.TEXT_OVERFLOW_CLIP;case"ellipsis":return ra.TEXT_OVERFLOW_ELLIPSE}return ra.TEXT_OVERFLOW_ELLIPSE}makeBlockButtonAppearance(e){switch(e){case"secondary":return Xe.BUTTON_APPEARANCE_SECONDARY;case"primary":return Xe.BUTTON_APPEARANCE_PRIMARY;case"plain":return Xe.BUTTON_APPEARANCE_PLAIN;case"bordered":return Xe.BUTTON_APPEARANCE_BORDERED;case"media":return Xe.BUTTON_APPEARANCE_MEDIA;case"destructive":return Xe.BUTTON_APPEARANCE_DESTRUCTIVE;case"caution":return Xe.BUTTON_APPEARANCE_CAUTION;case"success":return Xe.BUTTON_APPEARANCE_SUCCESS}}makeBlockButtonSize(e){switch(e){case"small":return Qo.BUTTON_SIZE_SMALL;case"medium":return Qo.BUTTON_SIZE_MEDIUM;case"large":return Qo.BUTTON_SIZE_LARGE}}makeBlockImageResizeMode(e){switch(e){case"none":return Nr.IMAGE_RESIZE_NONE;case"fit":return Nr.IMAGE_RESIZE_FIT;case"fill":return Nr.IMAGE_RESIZE_FILL;case"cover":return Nr.IMAGE_RESIZE_COVER;case"scale-down":return Nr.IMAGE_RESIZE_SCALE_DOWN}}makeBlockSpacerSize(e){switch(e){case"xsmall":return Zs.SPACER_XSMALL;case"small":return Zs.SPACER_SMALL;case"medium":return Zs.SPACER_MEDIUM;case"large":return Zs.SPACER_LARGE}}makeBlockSpacerShape(e){switch(e){case"invisible":return ea.SPACER_INVISIBLE;case"thin":return ea.SPACER_THIN;case"square":return ea.SPACER_SQUARE}}makeBlockIconSize(e){switch(e){case"xsmall":return Ks.ICON_SIZE_XSMALL;case"small":return Ks.ICON_SIZE_SMALL;case"medium":return Ks.ICON_SIZE_MEDIUM;case"large":return Ks.ICON_SIZE_LARGE}}makeBlockAvatarSize(e){switch(e){case"xxsmall":return Ze.AVATAR_SIZE_XXSMALL;case"xsmall":return Ze.AVATAR_SIZE_XSMALL;case"small":return Ze.AVATAR_SIZE_SMALL;case"medium":return Ze.AVATAR_SIZE_MEDIUM;case"large":return Ze.AVATAR_SIZE_LARGE;case"xlarge":return Ze.AVATAR_SIZE_XXLARGE;case"xxlarge":return Ze.AVATAR_SIZE_XXLARGE;case"xxxlarge":return Ze.AVATAR_SIZE_XXXLARGE}}makeBlockAvatarFacing(e){switch(e){case"left":return Xd.AVATAR_FACING_LEFT;case"right":return Xd.AVATAR_FACING_RIGHT}}makeBlockAvatarBackground(e){switch(e){case"dark":return Zd.AVATAR_BG_DARK;case"light":return Zd.AVATAR_BG_LIGHT}}getDataSet(e){return Object.keys(e).filter(t=>t.startsWith(Yd)).reduce((t,r)=>(t[r.substring(Yd.length)]=e[r],t),{})}makeActions(e,t){let r=[],s=this.getDataSet(t);return lm.forEach(o=>{if(o in t){let d=t[o];r.push({type:um.get(o)??oa.UNRECOGNIZED,id:d.toString(),data:s})}}),r}blockColorToHex(e,t="light"){if(e)return e=e.toLowerCase(),Wd(e)?e:Vd(e)?zd(e,t):Ko(e)?Gs(e):Gd(e)?qd(e):Jd(e)?e:(console.warn(`Could not parse color: ${e}.`),Gs("red"))}childrenToBlocks(e,t){return e.flatMap(r=>(typeof r!="string"?this.createBlocksElement(r,t):void 0)??[])}getThemedColors(e,t,r){let s=this.blockColorToHex(t,"light"),o=this.blockColorToHex(r,"dark"),d=[];if(e&&(!s||!o)){let c=Array.from(e?.matchAll(/[\w#-]+(?:\([\w\t ,.#-]+\))?/g)??[]);d.push(...c.map(m=>m[0]))}return s||(s=this.blockColorToHex(d?.at(0),"light")),o||(o=this.blockColorToHex(d?.at(1)??d?.at(0),"dark")),s||o?{light:s,dark:o}:void 0}parsePixels(e){return typeof e=="string"?Number(e.slice(0,-2)):e}resolveAssetUrl(e,t){return n(this,Hr).call(this)?.getURL(e,t)??e}childrenToString(e){return e.map(t=>t.toString()).join("")}makeRoot(e,...t){return this.wrapRoot(e,this.childrenToBlocks(t,Zo))}wrapRoot(e,t){return this.makeBlock(Ae.BLOCK_ROOT,{},{},{rootConfig:{children:t,height:this.makeRootHeight(u.customPostType?.height??e?.height??"regular")}})}makeStackBlock(e,t,r,s){let o=this.getThemedColors(t?.backgroundColor,t?.lightBackgroundColor,t?.darkBackgroundColor),d=this.makeBlockAlignment(t?.alignment),c=Xo(t,r),m=Kd(t,r.stackParentLayout,c);return this.makeBlock(Ae.BLOCK_STACK,t,r,{stackConfig:{alignment:d,backgroundColor:o?.light,backgroundColors:o,border:this.makeBlockBorder(t?.border,t?.borderColor,t?.lightBorderColor,t?.darkBorderColor),children:this.childrenToBlocks(s,{stackParentLayout:{...m,direction:e,alignment:d}}),cornerRadius:this.makeBlockRadius(t?.cornerRadius),direction:e,gap:this.makeBlockGap(t?.gap),padding:this.makeBlockPadding(t?.padding),reverse:t?.reverse}})}makeHStack(e,t,...r){return this.makeStackBlock(ta.STACK_HORIZONTAL,e,t,r)}makeVStack(e,t,...r){return this.makeStackBlock(ta.STACK_VERTICAL,e,t,r)}makeZStack(e,t,...r){return this.makeStackBlock(ta.STACK_DEPTH,e,t,r)}makeText(e,t,...r){let s=this.getThemedColors(e?.color,e?.lightColor,e?.darkColor);return this.makeBlock(Ae.BLOCK_TEXT,e,t,{textConfig:{alignment:this.makeBlockAlignment(e?.alignment),color:s?.light,colors:s,outline:this.makeBlockTextOutline(e?.outline),size:this.makeBlockTextSize(e?.size),style:this.makeBlockTextStyle(e?.style),text:this.childrenToString(r),weight:this.makeBlockTextWeight(e?.weight),selectable:e?.selectable,wrap:e?.wrap,overflow:this.makeBlockTextOverflow(e?.overflow)}})}makeButton(e,t,...r){let s=this.getThemedColors(e?.textColor,e?.lightTextColor,e?.darkTextColor);return this.makeBlock(Ae.BLOCK_BUTTON,e,t,{buttonConfig:{buttonAppearance:this.makeBlockButtonAppearance(e?.appearance),icon:e?.icon,buttonSize:this.makeBlockButtonSize(e?.size),text:this.childrenToString(r),textColor:s?.light,textColors:s,disabled:e?.disabled}})}makeImage(e,t){return e&&this.makeBlock(Ae.BLOCK_IMAGE,e,t,{imageConfig:{description:e?.description,resizeMode:this.makeBlockImageResizeMode(e.resizeMode),url:this.resolveAssetUrl(e.url),width:this.parsePixels(e.imageWidth),height:this.parsePixels(e.imageHeight)}})}makeSpacer(e,t){return this.makeBlock(Ae.BLOCK_SPACER,e,t,{spacerConfig:{size:this.makeBlockSpacerSize(e?.size),shape:this.makeBlockSpacerShape(e?.shape)}})}makeIcon(e,t){let r=this.getThemedColors(e?.color,e?.lightColor,e?.darkColor);return e&&this.makeBlock(Ae.BLOCK_ICON,e,t,{iconConfig:{icon:e.name,color:r?.light,colors:r,size:this.makeBlockIconSize(e.size)}})}makeAvatar(e,t){return e&&this.makeBlock(Ae.BLOCK_AVATAR,e,t,{avatarConfig:{thingId:e.thingId,size:this.makeBlockAvatarSize(e.size),facing:this.makeBlockAvatarFacing(e.facing),background:this.makeBlockAvatarBackground(e.background)}})}makeWebView(e,t){return e&&this.makeBlock(Ae.BLOCK_WEBVIEW,e,t,{webviewConfig:{url:this.resolveAssetUrl(e.url,{webView:!0}),state:e.state}})}makeBlock(e,t,r,s){return{type:e,sizes:Xo(t,r),config:s,actions:(t&&this.makeActions(e,t))??[],id:t?.id,key:t?.key}}ensureRootBlock(e){let t;if(e.type===Ae.BLOCK_ROOT?(e.config?.rootConfig&&u.customPostType?.height&&(e.config.rootConfig.height=this.makeRootHeight(u.customPostType?.height)),t=e):t=this.wrapRoot(void 0,[e]),!t)throw new Error("Could not create root block");return t}};Hr=new WeakMap;function tl(i){if(typeof i=="string")throw new Error("Root element cannot be a string")}var il=i=>{let e="",t=i.props?Object.keys(i.props).map(r=>r==="onPress"?"":`${r}="${i.props[r]}"`).join(" "):"";e+=`<${i.type}${t?" "+t:""}>`;for(let r of i.children)typeof r=="string"?e+=r:e+=il(r);return e+=`</${i.type}>`,e};function cm(i){return" ".repeat(i)}function mm(i){let e="",t=0,r=i.split(/>\s*</);for(let s=0;s<r.length;s++){let o=r[s];s===0&&(o=o.trim()),s===r.length-1&&(o=o.trim());let d=o.charAt(0)==="/";d&&t--,e+=cm(t),s!==0&&(e+="<"),e+=o,s!==r.length-1&&(e+=`>
|
|
2
|
-
`),!d&&o.indexOf("</")===-1&&o.charAt(o.length-1)!=="/"&&t++}return e}var Ce,rl,jr,da,Wr,De=class{constructor(e,t,r,s,o){l(this,Ce);this.renderState={};this.currentComponentKey=[];this.currentHookIndex=0;this.actions=new Map;this.forms=new Map;this.realtimeChannels=[];this.realtimeUpdated=!1;this.pendingHooks=[];this.isRendering=!1;this.transformer=new vi(()=>this.assets);this.effects=[];l(this,Wr,!1);this.component=e,this.event=t,this.state={__renderState:{},...r},this.metadata=s,this.state.__realtimeChannels&&(this.realtimeChannels=this.state.__realtimeChannels);let d=ke({reconciler:this,hooks:!0,ui:!0,metadata:s});this.cache=d.cache,this.modLog=d.modLog,this.reddit=d.reddit,this.kvStore=d.kvStore,this.redis=d.redis,this.settings=d.settings,this.scheduler=d.scheduler,this.media=d.media,this.assets=d.assets,this.realtime=d.realtime,this.dimensions=o,this.ui=d.ui,this.hooks={useState:d.useState,useInterval:d.useInterval,useForm:d.useForm,useChannel:d.useChannel}}emitEffect(e,t){this.effects.push(t)}async render(){await this.reconcile(),this.isRendering=!0;let e=await this.buildBlocksUI();return this.isRendering=!1,e}makeUniqueActionID(e){let t=e,r=1;for(;this.actions.has(t);)t=`${e}.${r++}`;return t}async reconcile(){let e=h(this,Ce,jr).call(this),t={type:this.component,props:e,children:[]},r=await this.processBlock(t);if(tl(r),this.transformer.createBlocksElementOrThrow(r),this.isUserActionRender&&this.blockRenderEventId){let s=this.actions.get(this.blockRenderEventId);s&&await s(this.event.data)}for(let s of this.pendingHooks)await s();this.buildNextState(),h(this,Ce,rl).call(this)}async buildBlocksUI(){let e=h(this,Ce,jr).call(this),t={type:this.component,props:e,children:[]},r=await this.renderElement(e,t);return this.transformer.ensureRootBlock(r)}async renderElement(e,t){let r=await this.processBlock(t);return tl(r),(u.debug.emitSnapshots||e.debug.emitSnapshots)&&console.debug(mm(il(r))),(u.debug.emitState||e.debug.emitState)&&console.debug(JSON.stringify(this.state,void 0,2)),this.transformer.createBlocksElementOrThrow(r)}async processProps(e){let t=e.props??{},r=["onPress","onMessage"];for(let s of r)if(s in t){let o=t[s],d=o?.name,c=this.makeUniqueActionID(`${e.type}.${d??s}`);this.actions.set(c,o),t[s]=c}}async processBlock(e,t=Hd(),r=[]){let s=e;if(typeof s.type=="string"){let c=[];for(let f=0;f<s.children.length;f++){let S=s.children[f];S!=null&&c.push(await this.processBlock(S,t,[...r,`${s.type}.${f}`]))}let m=c.flat(),y=h(this,Ce,da).call(this,m);return await this.processProps(s),{type:s.type,props:s.props,children:y}}if(typeof s.type=="function"){let c=t(`${r.length?r.join("."):"root"}.${s.type.name.length?s.type.name:"anonymous"}`);this.currentComponentKey.push(c),this.renderState[c]||(this.renderState[c]={});let m=s.children.flatMap(f=>f),y={...h(this,Ce,jr).call(this),...s.props,children:m},v;for(;v===void 0;)try{v=await s.type(y,h(this,Ce,jr).call(this))}catch(f){if(f instanceof Promise)v=await f;else throw f}if(!this.isInitialRender){let f=this.getPreviousComponentState();if(Object.keys(f).length!==this.currentHookIndex)throw new Error("Invalid hook call. Hooks can only be called at the top-level of a function component. Make sure that you are not calling hooks inside loops, conditions, or nested functions.")}if(this.currentComponentKey.pop(),this.currentHookIndex=0,typeof v=="object")return this.processBlock(v,t,[...r,s.type.name])}if(typeof s=="string")return s;if(typeof s=="number")return`${s}`;let o=[],d="";return Array.isArray(s)?o=s:typeof s.type>"u"&&s.children&&(o=s.children,d="fragmentChild."),{type:"__fragment",props:void 0,children:await Promise.all(o.flatMap(async(c,m)=>await this.processBlock(c,t,[...r,`${d}${m}`])))}}getCurrentComponentKey(){if(!this.currentComponentKey.at(-1))throw new Error("Current component key is missing");return this.currentComponentKey}getCurrentComponentState(){let e=this.currentComponentKey.at(-1);if(!e)throw new Error("Current component key is missing");return this.renderState[e]}getPreviousComponentState(){let e=this.currentComponentKey.at(-1);if(!e)throw new Error("Current component key is missing");return this.state.__renderState[e]||(this.state.__renderState[e]={}),this.state.__renderState[e]}get isInitialRender(){return this.event?this.event.type===aa.RENDER_INITIAL:!1}get isUserActionRender(){return this.event?this.event.type===aa.RENDER_USER_ACTION:!1}get isEffectRender(){return this.event?this.event.type===aa.RENDER_EFFECT_EVENT:!1}get formSubmittedEvent(){return this.event?this.event.formSubmitted:!1}get blockRenderEventId(){return this.event?this.event.id:!1}get realtimeEvent(){if(!this.event)return!1;let e=this.event.realtimeEvent;return e?.event?.channel?e:!1}runHook(e){this.pendingHooks.push(e)}rerenderIn(e){n(this,Wr)||(a(this,Wr,!0),this.effects.push({type:el.EFFECT_RERENDER_UI,rerenderUi:{delaySeconds:e/1e3}}))}addRealtimeChannel(e){this.realtimeChannels.push(e),this.realtimeUpdated=!0}removeRealtimeChannel(e){this.realtimeChannels=this.realtimeChannels.filter(t=>t!==e),this.realtimeUpdated=!0}get realtimeEffect(){return this.realtimeUpdated&&this.realtimeChannels.length>0?[{type:el.EFFECT_REALTIME_SUB,realtimeSubscriptions:{subscriptionIds:this.realtimeChannels}}]:[]}getEffects(){return[...fi(this.ui),...this.effects,...this.realtimeEffect]}buildNextState(){for(let e of Object.keys(this.renderState))this.renderState[e]=Object.values(this.renderState[e]);this.state={__postData:this.state.__postData,__renderState:this.renderState,__cache:this.state.__cache,...this.realtimeChannels.length>0?{__realtimeChannels:this.realtimeChannels}:{}}}};Ce=new WeakSet,rl=function(){this.actions.clear(),this.currentComponentKey=[],this.currentHookIndex=0,this.pendingHooks=[],this.realtimeChannels=[],this.realtimeUpdated=!1},jr=function(){let e={...se(this.metadata,this.state.__postData?.thingId),modLog:this.modLog,reddit:this.reddit,cache:this.cache,kvStore:this.kvStore,redis:this.redis,settings:this.settings,scheduler:this.scheduler,media:this.media,assets:this.assets,realtime:this.realtime,ui:this.ui,dimensions:this.dimensions,uiEnvironment:{timezone:this.metadata[P.Timezone]?.values[0],locale:this.metadata[P.Language]?.values[0],dimensions:this.dimensions},...this.hooks};return e.debug.effects=this,e},da=function(e){let t=[];for(let r of e)typeof r=="string"?t.push(r):r.type==="__fragment"?t.push(...h(this,Ce,da).call(this,r.children)):t.push(r);return t},Wr=new WeakMap;async function hm(i,e){let t=u.customPostType;if(!t)throw new Error("Custom post type not registered");let r=new De((o,d)=>t.render(d),i.blocks,i.state,e,i.dimensions),s=await r.render();return gm.fromJSON({state:r.state,blocks:{ui:s},effects:r.getEffects()})}function nl(i){i.provides(pm),R("RenderPost",hm)}import{GetFieldsResponse as fm,InstallationSettingsDefinition as bm}from"@devvit/protos";async function ym(){if(!u.installationSettings)throw new Error("Installation settings were not defined.");return fm.fromJSON({fields:{fields:Ue(u.installationSettings)}})}async function vm(i,e){return Vs(i,u.installationSettings,e)}function sl(i){i.provides(bm),R("GetSettingsFields",ym),R("ValidateForm",vm)}import{ContextActionDefinition as km,ContextActionList as Cm,ContextActionResponse as Sm}from"@devvit/protos";function la(i){let e=i.debug.metadata[P.User].values[0];if(!e)throw new Error("User missing from context");return e}function ua(i){let e=i.debug.metadata[P.Subreddit].values[0];if(!e)throw new Error("Subreddit missing from context");return e}async function ol(i,e){let t=la(i),r=ua(i);if(!t||!r)throw new Error("User or subreddit missing from context");let s=e.comment?.id&&`t1_${e.comment.id}`,o=e.post?.id&&`t3_${e.post.id}`,d=e.subreddit?.id&&`t5_${e.subreddit.id}`,c=s||o||d;if(!c)throw new Error("targetId is missing from ContextActionRequest");if(s){let f=await i.reddit.getCommentById(s);if(!f)throw new Error(`Comment ${s} not found`);if(f.subredditId!==r)throw new Error("Comment does not belong to the subreddit")}if(o){let f=await i.reddit.getPostById(o);if(!f)throw new Error(`Post ${o} not found`);if(f.subredditId!==r)throw new Error("Post does not belong to the subreddit")}if(d&&d!==r)throw new Error(`Subreddit ${d} ${r} not found`);let m=Vr(e.actionId);if(!m)throw new Error("Action not found");let y=!!m.forUserType?.includes("moderator");if(y&&!al(i))throw new Error("User is not a moderator");let v={needsModCheck:y};await i.redis.set(`${t}${r}${c}${e.actionId}`,JSON.stringify(v)),await i.redis.expire(`${t}${r}${c}${e.actionId}`,600),console.debug("CSRF token added: "+JSON.stringify(v))}async function al(i){let e=la(i),t=ua(i),r=await i.reddit.getSubredditInfoById(t);return!!(await i.reddit.getModerators({subredditName:r.name}).all()).find(o=>o.id===e)}async function dl(i,e){let t=la(i),r=ua(i),{actionId:s,thingId:o}=e.state?.__contextAction??{},d=await i.redis.get(`${t}${r}${o}${s}`);if(!d)throw new Error("CSRF token not found");if(JSON.parse(d).needsModCheck&&!await al(i))throw new Error("User is not a moderator: "+t+"; "+r);console.debug("CSRF token validated: "+d)}var ll=i=>`menuItem.${i}`;function Vr(i){return u.menuItems.find((e,t)=>ll(t)===i)}async function Pm(i,e){let t=u.menuItems;if(!t.length)throw new Error("No menu items registered.");let r=t.map((s,o)=>({actionId:ll(o),name:s.label,description:s.description,contexts:{subreddit:s.location.includes("subreddit"),post:s.location.includes("post"),comment:s.location.includes("comment")},users:{loggedOut:s.forUserType?.includes("loggedOut"),moderator:s.forUserType?.includes("moderator")},postFilters:s.postFilter==="currentApp"?{currentApp:!0}:void 0}));return Cm.fromJSON({actions:r})}async function wm(i,e){let t=Vr(i.actionId);if(!t)throw new Error(`MenuItem ${i.actionId} not found`);let r=i.comment?.id&&`t1_${i.comment.id}`,s=i.post?.id&&`t3_${i.post.id}`,o=i.subreddit?.id&&`t5_${i.subreddit.id}`,d=r||s||o;p(d,"targetId is missing from ContextActionRequest");let c={targetId:d,location:i.comment?"comment":i.post?"post":"subreddit"},m=Object.assign(ke({ui:!0,metadata:e}),se(e,s,r),{uiEnvironment:{timezone:e[P.Timezone]?.values[0],locale:e[P.Language]?.values[0]}});return await ol(m,i),await t.onPress(c,m),Sm.fromJSON({effects:fi(m.ui)})}function ul(i){i.provides(km),R("GetActions",Pm),R("OnAction",wm)}function Ne(i){return i?i===!0?!0:i.enabled:!1}import{SchedulerHandlerDefinition as Fm}from"@devvit/protos";async function xm(i,e){let t=i.type,r=u.scheduledJobHandlers.get(t);if(!r)throw new Error(`Job ${t} not found`);let s={name:t,data:i.data},o=Object.assign(ke({metadata:e}),se(e));await r(s,o)}function cl(i){i.provides(Fm),R("HandleScheduledAction",xm)}import{OnAppInstallDefinition as Im,OnAppUpgradeDefinition as Em,OnAutomoderatorFilterCommentDefinition as Am,OnAutomoderatorFilterPostDefinition as Tm,OnCommentCreateDefinition as Rm,OnCommentDeleteDefinition as Om,OnCommentReportDefinition as Bm,OnCommentSubmitDefinition as Mm,OnCommentUpdateDefinition as Um,OnModActionDefinition as Dm,OnModMailDefinition as Nm,OnPostCreateDefinition as Lm,OnPostDeleteDefinition as _m,OnPostFlairUpdateDefinition as Hm,OnPostNsfwUpdateDefinition as jm,OnPostReportDefinition as Wm,OnPostSpoilerUpdateDefinition as Vm,OnPostSubmitDefinition as Gm,OnPostUpdateDefinition as Jm}from"@devvit/protos";var ki;(function(i){function e(d,c){return d.length<=c?d:`${d.slice(0,c-1)}\u2026`}i.ellipsize=e;function t(d){return d[0]==null?d:`${d[0].toLocaleUpperCase()}${d.slice(1)}`}i.capitalize=t;function r(d){return d==null||/^\s*$/.test(d)}i.isBlank=r;function s(d,c="stack"){return d instanceof Error?`${d[c]||d.stack||d.message||d.name}`:String(d)}i.caughtToString=s;function o(d,c="stack"){return d instanceof Error?`${d[c]||d.stack||d.message||d.name}`:String(d)}i.caughtToStringUntyped=o})(ki||(ki={}));function q(i,e){return p(e),async(t,r)=>{let s={...t,type:i},o=Object.assign(ke({metadata:r}),se(r)),d=await Promise.allSettled(e.map(m=>m(s,o))),c=zm(d);if(c)throw c.err;return{}}}function ml(i){for(let e of u.triggerOnEventHandlers.keys())switch(e){case"PostSubmit":i.provides(Gm),R("OnPostSubmit",q("PostSubmit",u.triggerOnEventHandlers.get(e)));break;case"PostCreate":i.provides(Lm),R("OnPostCreate",q("PostCreate",u.triggerOnEventHandlers.get(e)));break;case"PostUpdate":i.provides(Jm),R("OnPostUpdate",q("PostUpdate",u.triggerOnEventHandlers.get(e)));break;case"PostReport":i.provides(Wm),R("OnPostReport",q("PostReport",u.triggerOnEventHandlers.get(e)));break;case"PostDelete":i.provides(_m),R("OnPostDelete",q("PostDelete",u.triggerOnEventHandlers.get(e)));break;case"PostFlairUpdate":i.provides(Hm),R("OnPostFlairUpdate",q("PostFlairUpdate",u.triggerOnEventHandlers.get(e)));break;case"CommentSubmit":i.provides(Mm),R("OnCommentSubmit",q("CommentSubmit",u.triggerOnEventHandlers.get(e)));break;case"CommentCreate":i.provides(Rm),R("OnCommentCreate",q("CommentCreate",u.triggerOnEventHandlers.get(e)));break;case"CommentUpdate":i.provides(Um),R("OnCommentUpdate",q("CommentUpdate",u.triggerOnEventHandlers.get(e)));break;case"CommentReport":i.provides(Bm),R("OnCommentReport",q("CommentReport",u.triggerOnEventHandlers.get(e)));break;case"CommentDelete":i.provides(Om),R("OnCommentDelete",q("CommentDelete",u.triggerOnEventHandlers.get(e)));break;case"AppInstall":i.provides(Im),R("OnAppInstall",q("AppInstall",u.triggerOnEventHandlers.get(e)));break;case"AppUpgrade":i.provides(Em),R("OnAppUpgrade",q("AppUpgrade",u.triggerOnEventHandlers.get(e)));break;case"ModAction":i.provides(Dm),R("OnModAction",q("ModAction",u.triggerOnEventHandlers.get(e)));break;case"ModMail":i.provides(Nm),R("OnModMail",q("ModMail",u.triggerOnEventHandlers.get(e)));break;case"PostNsfwUpdate":i.provides(jm),R("OnPostNsfwUpdate",q("PostNsfwUpdate",u.triggerOnEventHandlers.get(e)));break;case"PostSpoilerUpdate":i.provides(Vm),R("OnPostSpoilerUpdate",q("PostSpoilerUpdate",u.triggerOnEventHandlers.get(e)));break;case"AutomoderatorFilterPost":i.provides(Tm),R("OnAutomoderatorFilterPost",q("AutomoderatorFilterPost",u.triggerOnEventHandlers.get(e)));break;case"AutomoderatorFilterComment":i.provides(Am),R("OnAutomoderatorFilterComment",q("AutomoderatorFilterComment",u.triggerOnEventHandlers.get(e)));break;default:throw new Error(`Unknown trigger event: ${e}`)}}function zm(i){let e=i.reduce((t,r)=>r.status==="rejected"?[...t,r.reason]:t,[]);if(e.length!==0)return e.length===1?{err:e[0]}:{err:new Error(e.map(t=>ki.caughtToString(t)).join(`
|
|
3
|
-
`))}}import{EffectType as fp,HandleUIEventResponse as pa,UIEventHandlerDefinition as bp}from"@devvit/protos";var Al=ed(wl(),1);function Fl(i){return i?.constructor===Object}function It(i,e){return Object.is(i,e)?!0:typeof i!=typeof e?!1:Array.isArray(i)&&Array.isArray(e)?xl(i,e):i instanceof Date&&e instanceof Date?i.getTime()===e.getTime():i instanceof RegExp&&e instanceof RegExp?i.toString()===e.toString():Fl(i)&&Fl(e)?hp(i,e):i instanceof ArrayBuffer&&e instanceof ArrayBuffer?Il(new DataView(i),new DataView(e)):i instanceof DataView&&e instanceof DataView?Il(i,e):El(i)&&El(e)?i.byteLength!==e.byteLength?!1:xl(i,e):!1}function hp(i,e){let t=Object.keys(i),r=Object.keys(e);if(!It(t,r))return!1;for(let s of t)if(!It(i[s],e[s]))return!1;return!0}function xl(i,e){return i.length!==e.length?!1:i.every((t,r)=>It(t,e[r]))}function Il(i,e){if(i.byteLength!==e.byteLength)return!1;for(let t=0;t<i.byteLength;t++)if(i.getUint8(t)!==e.getUint8(t))return!1;return!0}function El(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}async function yp(i,e){let t=i.state??{},r=(0,Al.default)(t),s=ke({ui:!0,metadata:e});if(i.event?.formSubmitted&&i.event.formSubmitted.formId){let m=i.event.formSubmitted.formId;if(m.includes("form.hook.")&&u.customPostType){let b=new De((O,L)=>u.customPostType?.render(L)??null,i.event,i.state,e,void 0);return await b.reconcile(),pa.fromJSON({state:b.state,effects:b.getEffects()})}let y=u.formDefinitions.get(m);if(!y)throw new Error(`Form with key ${m} not found`);let v,f;if(r.__contextAction){let{actionId:b,thingId:O}=r.__contextAction,L=Vr(b);L?.location==="post"?v=O:L?.location==="comment"&&(f=O)}let S=Object.assign(s,se(e,v,f),{uiEnvironment:{timezone:e[P.Timezone]?.values[0],locale:e[P.Language]?.values[0]}});await dl(S,i),await y.onSubmit({values:Je(i.event.formSubmitted.results)},S)}else if(i.event?.realtimeEvent){if(u.customPostType){let m=new De((y,v)=>u.customPostType?.render(v)??null,i.event,i.state,e,void 0);return await m.reconcile(),pa.fromJSON({state:m.state,effects:m.getEffects()})}}else if(i.event?.toastAction)throw new Error("Toast actions not yet implemented");let o=!It(t,r),d=fi(s.ui),c=o?[...d,{type:fp.EFFECT_RERENDER_UI,rerenderUi:{delaySeconds:0}}]:d;return pa.fromJSON({state:r,effects:c})}function Tl(i){i.provides(bp),R("HandleUIEvent",yp)}import{CustomPostDefinition as uo,UIResponse as nu}from"@devvit/protos";import{UIEventScope as xp}from"@devvit/protos";var ga="ServerCallRequired";function Xs(i){return i?.message===ga}var ya={now(){return new Date}};function Rl(i){return`__autocache__${i}`}function Ol(i){return`__lock__${i}`}var vp=300,kp=1e3,Qs=5e3,ha=3,Bl=.1,Ml=1e3,Cp=3e4;function Ul(i){if(i.error)throw new Error(i.error);return i.value}var Qe,Ye,Se,Ci,z,Dl,Nl,Ll,fa,_l,Hl,ba,jl,Ys=class{constructor(e,t,r=ya){l(this,z);l(this,Qe);l(this,Ye,{});l(this,Se);l(this,Ci);a(this,Qe,e),a(this,Ci,t),a(this,Se,r)}async cache(e,t){var d;(d=n(this,Ci)).__cache??(d.__cache={}),a(this,Ye,n(this,Ci).__cache),h(this,z,jl).call(this,t);let r=h(this,z,Dl).call(this,t.key);if(r!==void 0)return r;let s=await h(this,z,ba).call(this,t.key),o=await h(this,z,Nl).call(this,t,s,e);return Ul(o)}};Qe=new WeakMap,Ye=new WeakMap,Se=new WeakMap,Ci=new WeakMap,z=new WeakSet,Dl=function(e){let t=n(this,Ye)[e];if(t){let r=n(this,Se).now().getTime(),s=t?.error&&t?.errorTime&&t.errorCount<ha&&Math.random()<Bl&&t.errorTime+Ml<r;if(t?.expires&&t.expires<r&&t.checkedAt+Ml<r||s){delete n(this,Ye)[e];return}else return Ul(t)}},Nl=async function(e,t,r){let s=t?.expires,o=s?h(this,z,Hl).call(this,s):1;return!t||t?.error&&t.errorCount<ha&&Bl>Math.random()||o>Math.random()?h(this,z,Ll).call(this,e,t,r):t},Ll=async function(e,t,r){let s=Ol(e.key),o=n(this,Se).now().getTime(),d=new Date(o+e.ttl/2);if(await n(this,Qe).set(s,"1",{expiration:d,nx:!0}))return h(this,z,_l).call(this,e.key,t,r,e.ttl);if(t)return t;{let m=n(this,Se).now();return h(this,z,fa).call(this,m,e.key,e.ttl)}},fa=async function(e,t,r){let s=Math.min(r,kp),o=await h(this,z,ba).call(this,t);if(o)return o;if(n(this,Se).now().getTime()-e.getTime()>=s)throw new Error(`Cache request timed out trying to get data at key: ${t}`);return await new Promise(d=>setTimeout(d,vp)),h(this,z,fa).call(this,e,t,r)},_l=async function(e,t,r,s){let o=n(this,Se).now().getTime()+s;t=t??{value:null,expires:o,errorCount:0,error:null,errorTime:null,checkedAt:0};try{t.value=await r(),t.error=null,t.errorCount=0,t.errorTime=null}catch(d){t.value=null,t.error=d.message??"Unknown error",t.errorTime=n(this,Se).now().getTime(),t.errorCount++}return n(this,Ye)[e]=t,await n(this,Qe).set(Rl(e),JSON.stringify(t),{expiration:new Date(o+Cp)}),t.error&&t.errorCount<ha&&await n(this,Qe).del(Ol(e)),t},Hl=function(e){let t=n(this,Se).now().getTime(),r=e-t;return r<0?1:r<1e3?.1:r<2e3?.01:r<3e3?.001:0},ba=async function(e){let t=await n(this,Qe).get(Rl(e));if(t){let r=JSON.parse(t);return r.checkedAt=n(this,Se).now().getTime(),n(this,Ye)[e]=r,r}},jl=function(e){e.ttl<Qs&&(console.warn(`Cache TTL cannot be less than ${Qs} milliseconds! Updating ttl value of ${e.ttl} to ${Qs}.`),e.ttl=Qs)};function Wl(i,e,t=ya){let r=new Ys(i,e,t);return r.cache.bind(r)}import{EffectType as eo,ToastAppearance as Jl}from"@devvit/protos";function Vl(i){let e=i.match(/form\.hook\.(.+)\.0/);if(e?.[1])return e[1]}var va=class{constructor(e,t,r){this.state=null;this.hookId=e.hookId,this.form=t,this.onSubmit=r,this.onUIEvent=async s=>{s.formSubmitted&&await r(Je(s.formSubmitted.results))}}};function ka(i,e){let t=ce({namespace:"useForm",initializer:r=>new va(r,i,e)});return Sp({id:t.hookId})}function Sp(i){return`form.hook.${i.id}.0`}function Gl(i,e){let t=Vl(e);return i.getHook({id:t})}var Le,io,Gr,ro,to=class{constructor(e){l(this,Le);l(this,io,0);l(this,Gr);l(this,ro,(e,t)=>{let r=t!==void 0?e:"",s=t!==void 0?t:e;n(this,Le).emitEffect(`postMessage${td(this,io)._++}`,{type:eo.EFFECT_WEB_VIEW,webView:{postMessage:{webViewId:r,app:{message:s}}}})});a(this,Le,e),a(this,Gr,{postMessage:n(this,ro)})}get webView(){return n(this,Gr)}showForm(e,t){let r=Gl(n(this,Le),e);if(!r)throw new Error("Form does not exist. Make sure you have added it using useForm.");let s=r.form instanceof Function?r.form(t??{}):r.form,o={fields:[],id:e,title:s.title,acceptLabel:s.acceptLabel,cancelLabel:s.cancelLabel,shortDescription:s.description};Pt(s.fields),o.fields=Ue(s.fields),n(this,Le).emitEffect(e,{type:eo.EFFECT_SHOW_FORM,showForm:{form:o}})}showToast(e){let t;e instanceof Object?t={text:e.text,appearance:e.appearance==="success"?Jl.SUCCESS:Jl.NEUTRAL}:t={text:e},n(this,Le).emitEffect(e.toString(),{type:eo.EFFECT_SHOW_TOAST,showToast:{toast:t}})}navigateTo(e){let t;typeof e=="string"?t=new URL(e).toString():t=new URL(e.permalink,"https://www.reddit.com").toString(),n(this,Le).emitEffect(t,{type:eo.EFFECT_NAVIGATE_TO_URL,navigateToUrl:{url:t}})}};Le=new WeakMap,io=new WeakMap,Gr=new WeakMap,ro=new WeakMap;import{EffectType as Pp,RealtimeSubscriptionStatus as zl}from"@devvit/protos";var et,Te,tt,Et,Jr,Sa,no=class no{constructor(e,t){l(this,Jr);l(this,et);l(this,Te);l(this,tt);l(this,Et);a(this,et,t.context),a(this,Te,!!t.context._devvitContext?.debug.realtime),a(this,Et,e),a(this,tt,t.invalidate);let r=t.context.meta[P.App]?.values[0];if(!r)throw Error("useChannel missing app ID metadata");let s=t.context.meta[P.Installation]?.values[0];if(!s)throw Error("useChannel missing install ID from metadata");let o=`${r}:${s}:${e.name}`;if(Object.values(n(this,et)._hooks).filter(c=>c instanceof no).some(c=>c.state.channel===o))throw Error(`useChannel channel names must be unique; "${o}" duplicated`);this.state={channel:o,connected:!1,subscribed:!1}}async onUIEvent(e){let t=e.realtimeEvent;if(!(!t||!this.state.subscribed))switch(t.status){case zl.REALTIME_SUBSCRIBED:n(this,Te)&&console.debug(`[realtime] "${this.state.channel}" connected`),this.state.connected=!0,n(this,tt).call(this),await n(this,Et).onSubscribed?.();break;case zl.REALTIME_UNSUBSCRIBED:n(this,Te)&&console.debug(`[realtime] "${this.state.channel}" disconnected`),this.state.connected=!1,n(this,tt).call(this),await n(this,Et).onUnsubscribed?.();break;default:n(this,Te)&&console.debug(`[realtime] "${this.state.channel}" received message: ${JSON.stringify(e,void 0,2)}`),n(this,Et).onMessage(t.event?.data?.msg);break}}async send(e){if(n(this,Te)&&console.debug(`[realtime] "${this.state.channel}" send message: ${JSON.stringify(e,void 0,2)}`),!this.state.subscribed||!this.state.connected)throw console.debug(`[realtime] "${this.state.channel}" send failed; channel not connected`),Error(`useChannel send failed; "${this.state.channel}" channel not connected`);await n(this,et).devvitContext.realtime.send(this.state.channel,e)}get status(){return this.state.subscribed&&this.state.connected?2:this.state.subscribed&&!this.state.connected?1:!this.state.subscribed&&this.state.connected?3:4}subscribe(){this.state.subscribed||(n(this,Te)&&console.debug(`[realtime] "${this.state.channel}" subscribed`),this.state.subscribed=!0,n(this,tt).call(this),h(this,Jr,Sa).call(this))}unsubscribe(){this.state.subscribed&&(n(this,Te)&&console.debug(`[realtime] "${this.state.channel}" unsubscribed`),this.state.subscribed=!1,n(this,tt).call(this),h(this,Jr,Sa).call(this))}};et=new WeakMap,Te=new WeakMap,tt=new WeakMap,Et=new WeakMap,Jr=new WeakSet,Sa=function(){let e=Object.values(n(this,et)._hooks).filter(t=>t instanceof no&&t.state.subscribed).map(t=>t.state.channel);n(this,et).emitEffect(this.state.channel,{type:Pp.EFFECT_REALTIME_SUB,realtimeSubscriptions:{subscriptionIds:e}})};var Ca=no;function Pa(i){if(!i.name||/[^a-zA-Z0-9_]/.test(i.name))throw Error(`useChannel error: The name "${i.name}" you provided for the hook is invalid. Valid names can only contain letters, numbers, and underscores (_).`);let e=`useChannel:${i.name}`;return ce({id:e,namespace:e,initializer:t=>new Ca(i,t)})}import{EffectType as wa}from"@devvit/protos";function ql(i){return typeof i=="object"&&i!==null&&"__deleted"in i}var At,it,Si=class Si{constructor(e,t){l(this,At);this._segments=[];l(this,it,{});this._prevHooks={};this._prevHookId="";this._effects={};this._changed={};this._touched={};this._requeueEvents=[];this._rootProps={};this._generated={};this._undeliveredHandlers={};this.request=e,this.meta=t,a(this,At,e.state??{__cache:{}}),this._rootProps=e.props??{}}get devvitContext(){if(!this._devvitContext)throw new Error("Devvit context not available");return this._devvitContext}set devvitContext(e){this._devvitContext=e}get _changedState(){let e={__cache:n(this,At).__cache??{}};for(let r in this._changed)e[r]=this._state[r];let t=new Set(Object.keys(this._state));return Object.keys(n(this,it)).forEach(r=>{r!=="__cache"&&t.delete(r)}),t.forEach(r=>{if(r==="__cache")return;let s={__deleted:!0};this._state[r]=e[r]=s}),e}get _hooks(){return n(this,it)}set _hooks(e){this._prevHooks=n(this,it),a(this,it,e)}get _state(){return n(this,At)}set _state(e){a(this,At,e)}push(e){this._segments.push({...e,next:0})}pop(){this._segments.pop()}addUndeliveredEventHandler(e,t){this._undeliveredHandlers[e]=t}addGlobalUndeliveredEventHandler(e,t){Si.addGlobalUndeliveredEventHandler(e,t)}getHook(e){return n(this,it)[e.id]}static addGlobalUndeliveredEventHandler(e,t){Si._staticUndeliveredHandlers[e]=t}async handleUndeliveredEvent(e){let t={...Si._staticUndeliveredHandlers,...this._undeliveredHandlers};for(let[r,s]of Object.entries(t))await s(e,this)}emitEffect(e,t){this._effects[e]=t}addToRequeueEvents(...e){this._devvitContext?.debug.blocks&&console.debug("[blocks] requeueing events",e);let t=e.reduce((r,s)=>(s.retry?r.retry.push(s):r.normal.push(s),r),{retry:[],normal:[]});this._requeueEvents=[...t.retry,...this._requeueEvents,...t.normal]}get effects(){return Object.values(this._effects)}nextHookId(e){e.key===void 0&&(e.key=this._segments[this._segments.length-1].next+++""),this.push(e);try{let t=[];for(let s=this._segments.length-1;s>=0;s--){let o=this._segments[s];if(o.id){t.unshift(o.id);break}let d=[];o.namespace&&d.push(o.namespace),o.key!==void 0&&o.key!==!1&&d.push(o.key),t.unshift(d.join("-"))}let r=t.join(".");if(this._generated[r]&&!e.shared)throw new Error(`Hook id ${r} already used, cannot register another hook with the same id`);return this._generated[r]=!0,this._prevHookId=r,r}finally{this.pop()}}};At=new WeakMap,it=new WeakMap,Si._staticUndeliveredHandlers={};var Pi=Si;var rt={};Pi.addGlobalUndeliveredEventHandler("intervals",async(i,e)=>{i.timer&&i.hook&&(delete rt[i.hook],e.emitEffect("timers",{type:wa.EFFECT_SET_INTERVALS,interval:{intervals:rt}}))});var nt,wi,zr,Fi,Fa=class{constructor(e,t,r){l(this,nt);l(this,wi);l(this,zr);l(this,Fi);this.state={duration:{seconds:0,nanos:0},running:!1};a(this,wi,r.invalidate),a(this,nt,r.hookId),a(this,zr,e),a(this,Fi,r.context);let s=Math.floor(t/1e3),o=t%1e3*1e6;this.state.duration={seconds:s,nanos:o}}onStateLoaded(){this.state.running?rt[n(this,nt)]={duration:this.state.duration}:delete rt[n(this,nt)]}async onUIEvent(e){await n(this,zr).call(this)}start(){rt[n(this,nt)]={duration:this.state.duration},this.state.running=!0,n(this,wi).call(this),n(this,Fi).emitEffect("timers",{type:wa.EFFECT_SET_INTERVALS,interval:{intervals:rt}})}stop(){delete rt[n(this,nt)],this.state.running=!1,n(this,wi).call(this),n(this,Fi).emitEffect("timers",{type:wa.EFFECT_SET_INTERVALS,interval:{intervals:rt}})}};nt=new WeakMap,wi=new WeakMap,zr=new WeakMap,Fi=new WeakMap;function xa(i,e){let t=ce({namespace:"useInterval",initializer:r=>new Fa(i,e,r)});return{start:()=>t.start(),stop:()=>t.stop()}}import{UIEventScope as Fp}from"@devvit/protos";var Tt=class extends Error{};import{UIEventScope as $l}from"@devvit/protos";function Ea(i){if(i instanceof Error){if(i.message===ga)throw i;return console.error(i),{message:i.message,details:i.stack??""}}else return console.error(i),{message:"Unknown error",details:ki.caughtToString(i)}}var Fe,Re,xi,qr,Ii,Ia=class{constructor(e,t,r){l(this,Fe);l(this,Re);l(this,xi);l(this,qr);l(this,Ii);a(this,Fe,!!r.context.devvitContext.debug.useAsync),n(this,Fe)&&console.debug("[useAsync] v1",t),this.state={data:null,load_state:"initial",error:null,depends:null},a(this,Re,r.hookId),this.initializer=e,a(this,xi,r.invalidate),a(this,qr,r.context),this.localDepends=t.depends??null,a(this,Ii,t)}onStateLoaded(){if(n(this,Fe)&&console.debug("[useAsync] async onLoad ",n(this,Re),this.state),n(this,Fe)&&console.debug("[useAsync] async onLoad have ",this.localDepends,"and",this.state.depends),!It(this.localDepends,this.state.depends)||this.state.load_state==="initial"){n(this,Fe)&&console.debug("[useAsync] attempting to resolve for hookId",n(this,Re)),this.state.load_state="loading",this.state.depends=this.localDepends,n(this,xi).call(this);let e={scope:$l.ALL,hook:n(this,Re),async:!0,asyncRequest:{requestId:n(this,Re)+"-"+JSON.stringify(this.state.depends)}};n(this,Fe)&&console.debug("[useAsync] onLoad requeue"),n(this,qr).addToRequeueEvents(e)}}async onUIEvent(e,t){if(e.asyncRequest){let r={requestId:e.asyncRequest.requestId};try{r.data={value:await this.initializer()}}catch(o){r.error=Ea(o)}let s={scope:$l.ALL,asyncResponse:r,hook:n(this,Re)};n(this,Fe)&&console.debug("[useAsync] onReq requeue"),t.addToRequeueEvents(s)}else if(e.asyncResponse){let r=n(this,Re)+"-"+JSON.stringify(this.state.depends);e.asyncResponse.requestId===r?(this.state={...this.state,data:e.asyncResponse.data?.value??null,error:e.asyncResponse.error??null,load_state:e.asyncResponse.error?"error":"loaded"},n(this,Ii).finally&&await n(this,Ii).finally(this.state.data,this.state.error?new Error(this.state.error?.message??"Unknown error"):null),n(this,xi).call(this)):n(this,Fe)&&console.debug("[useAsync] onResp skip, stale event",e.asyncResponse.requestId," !== ",r)}else throw new Error("Unknown event type")}};Fe=new WeakMap,Re=new WeakMap,xi=new WeakMap,qr=new WeakMap,Ii=new WeakMap;function wp(i,e={}){let t=ce({namespace:"useAsync",initializer:r=>new Ia(i,e,r)});return{data:t.state.data,error:t.state.error,loading:t.state.load_state==="loading"}}var _e,Ei,Rt,Ot,Aa=class{constructor(e,t){this.state={value:null,load_state:"initial",error:null};l(this,_e);l(this,Ei);l(this,Rt);l(this,Ot);a(this,Rt,e),a(this,Ot,t.hookId),a(this,_e,t.invalidate),a(this,Ei,t.context)}async onUIEvent(){if(this.state.load_state==="loading"&&this._promise){try{this.state.value=await this._promise,this.state.load_state="loaded"}catch(e){this.state.load_state="error",this.state.error=Ea(e)}n(this,_e).call(this)}else console.warn("Invalid state: ",this.state.load_state,this._promise)}setter(e){this.state.value=e instanceof Function?e(this.state.value):e,this.state.load_state="loaded",n(this,_e).call(this)}onStateLoaded(){if(this._promise=n(this,Ei)._prevHooks[n(this,Ot)]?._promise,this.state.load_state==="loading")throw new Tt;if(this.state.load_state==="error")throw new Error(this.state.error?.message??"Unknown error");if(this.state.load_state==="initial"){let e;try{e=n(this,Rt)instanceof Function?n(this,Rt).call(this):n(this,Rt)}catch(t){console.log("error in loading async",t),this.state.load_state="error",n(this,_e).call(this);return}if(e instanceof Promise){this._promise=e,this.state.load_state="loading";let t={scope:Fp.ALL,asyncRequest:{requestId:n(this,Ot)},hook:n(this,Ot)};throw n(this,Ei).addToRequeueEvents(t),n(this,_e).call(this),new Tt}else this.state.value=e,this.state.load_state="loaded";n(this,_e).call(this)}}};_e=new WeakMap,Ei=new WeakMap,Rt=new WeakMap,Ot=new WeakMap;function Ta(i){let e=ce({namespace:"useState",initializer:t=>new Aa(i,t)});return[e.state.value,e.setter.bind(e)]}var so=class{buildContext(e,t,r){let s=new di(r),o=new oi(r),d=new mi(r),c=new ui(r),m=new pi(r),y=new gi(r),v=new to(e),f=new ai(r),S=new ni,b=new li(r),O=Wl(d,e._state),L={modLog:s,kvStore:o,redis:d,reddit:c,scheduler:m,settings:y,media:f,assets:S,realtime:b,ui:v,useState:Ta,useChannel:Pa,useInterval:xa,useForm:ka,cache:O,dimensions:t.env?.dimensions,uiEnvironment:{timezone:r[P.Timezone]?.values[0],locale:r[P.Language]?.values[0],dimensions:t.env?.dimensions,colorScheme:t.env?.colorScheme}},B=se(r,t.props?.postId);return B.debug.effects=e,{...B,...L}}};var me=null;function Kl(i){return JSON.parse(JSON.stringify(i))}function Ip(i){if(!(i!==""&&!/[-.]/.test(i)))throw new Error(`Hook with namespace '${i}' is invalid. Hook namespaces cannot be empty string or contain dashes/dots because they are used as delimiters internally. Please update the hook namespace and try again.`)}function ce({initializer:i,...e}){if(!me)throw new Error("Hooks can only be declared at the top of a component. You cannot declare hooks outside of components or inside of event handlers. It's almost always a mistake to declare hooks inside of loops or conditionals.");Ip(e.namespace);let t=me.nextHookId(e),r=me,s={hookId:t,invalidate:()=>{r._changed[t]=!0,r._state[t]=r?._hooks[t]?.state},context:me},o=me._state[t]===void 0||ql(me._state[t]);me._hooks[t]=me._hooks[t]??i(s);let d=me._hooks[t];return o||(d.state=me._state[t]),d.onStateLoaded?.(),o&&d.state!==void 0&&d.state!==null&&s.invalidate(),d}var Ep=null,Zl=64,Ai,lo,$r,w,oe,oo,Xl,Ra,Ql,Oa,Ba,ao,Ma,Yl,Bt=class{constructor(e){l(this,w);l(this,Ai);l(this,lo,new so);l(this,$r,new vi(()=>this._latestRenderContext?.devvitContext?.assets));this._latestRenderContext=null;n(this,w,oe)&&console.debug("[blocks] BlocksHandler v1"),a(this,Ai,e),Ep=this}async handle(e,t){let r=new Pi(e,t),s=n(this,lo).buildContext(r,e,t);r.devvitContext=s;let o,d=e.events,m=!e.events?.length||d.some(O=>!O.async),y=d.some(O=>O.blocking),v,f,S=[...d];d.length===0&&d.push({scope:xp.ALL}),n(this,w,oe)&&console.debug("[blocks] starting processing events");let b=0;for(;d.length>0;){if(b++>Zl)throw new Error(`Exceeded maximum iterations of ${Zl}`);n(this,w,oe)&&console.debug("[blocks] processing events loop iteration",d.length);let O=[];if(!d[0].async)O.push(d.shift());else for(;d[0]?.async;)O.push(d.shift());if(!O.length)throw Error("batch must have at least one event");try{if(O[0].async){let B=Kl(r._state);await h(this,w,Xl).call(this,r,...O),r._state=B}else await h(this,w,Ql).call(this,r,...O)}catch(B){if(!Xs(B))throw B;if(n(this,w,oe)&&console.debug("[blocks] caught in handler",B),r._latestRenderContent=void 0,f){r._state=f._state,r._changed=v,r._effects=f._effects;let Y=S.map(Xt=>{let Mo={...Xt};return Mo.retry=!0,Mo});r.addToRequeueEvents(...Y);break}else throw Xs(B)||console.error("[blocks] unhandled error in handler",B),B}n(this,w,oe)&&console.debug("[blocks] remaining events",r._requeueEvents);let L=[];for(let B of r._requeueEvents){if(!m&&!B.async){n(this,w,oe)&&console.debug("[blocks] NOT reprocessing event in BlocksHandler, sync mismatch A",B),L.push(B);continue}if(m&&B.async&&!y){n(this,w,oe)&&console.debug("[blocks] NOT reprocessing event in BlocksHandler, sync mismatch B",B),L.push(B);continue}n(this,w,oe)&&console.debug("[blocks] reprocessing event in BlocksHandler",B),d.push(B)}r._requeueEvents=L,d.length>0&&(v={...r._changed},f={_state:Kl(r._state),_effects:{...r._effects}},S=[...d])}if(m){r._latestRenderContent||(r._latestRenderContent=h(this,w,Oa).call(this,n(this,Ai),r.request.props??{},r));let O=r._latestRenderContent;O&&(o=n(this,$r).createBlocksElementOrThrow(O),o=n(this,$r).ensureRootBlock(o))}return{state:r._changedState,effects:r.effects,blocks:o,events:r._requeueEvents}}};Ai=new WeakMap,lo=new WeakMap,$r=new WeakMap,w=new WeakSet,oe=function(){return!!this._latestRenderContext?.devvitContext.debug.blocks},oo=function(e,...t){e._hooks={},h(this,w,Oa).call(this,n(this,Ai),e.request.props??{},e)},Xl=async function(e,...t){h(this,w,oo).call(this,e,...t),await Promise.all(t.map(async r=>{if(!r.async)throw new Error("You can't mix main and other queues in one batch. This is likely a platform bug. Please file an issue in the Discord for someone to help! https://discord.com/channels/1050224141732687912/1115441897079574620");await h(this,w,Ra).call(this,e,r)}))},Ra=async function(e,t){let r=e._hooks[t.hook];if(r?.onUIEvent)try{await r.onUIEvent(t,e)}catch(s){throw Xs(s)?n(this,w,oe)&&console.error("Server call required",s):console.error("Error in event handler",s),s}else await e.handleUndeliveredEvent(t)},Ql=async function(e,...t){for(let r of t)n(this,w,oe)&&console.log("[blocks] handling main queue event",r),n(this,w,oe)&&console.log("[blocks] before",e._state),h(this,w,oo).call(this,e,r),await h(this,w,Ra).call(this,e,r),n(this,w,oe)&&console.log("[blocks] after",e._state);h(this,w,oo).call(this,e)},Oa=function(e,t,r){n(this,w,oe)&&console.debug("[blocks] renderRoot"),r._generated={},me=r,this._latestRenderContext=r;try{let s=h(this,w,Ba).call(this,e,t,r);if(s.length!==1)throw new Error(`There can only be one root element, received: ${s.length}. Please wrap these elements in a <vstack></vstack> or <hstack></hstack> to continue. Fragments cannot be used as a root element.`);let o=s[0];if(o==="[object Promise]")throw new Error('Root elements cannot be async. To use data from an async endpoint, please use "const [data] = useState(async () => {/** your async code */})".');if(typeof o=="string")throw new Error("The root element must return a valid block, not a string. Try wrapping the element in a <text>your content</text> tag to continue.");return r._latestRenderContent=o,o}catch(s){if(s instanceof Tt)return;throw s}finally{me=null}},Ba=function(e,t,r){r.push({namespace:e.name||"anonymous",...t});try{let s=e(t,r.devvitContext);if(s instanceof Promise)throw new Error(`Components (found: ${e.name??"unknown component"}) cannot be async. To use data from an async endpoint, please use "const [data] = useState(async () => {/** your async code */})".`);return h(this,w,Ma).call(this,s,r)}finally{r.pop()}},ao=function(e,t){return e=e.flat(1/0),e.flatMap((r,s)=>(r&&typeof r=="object"&&"props"in r&&(r.props?.key||(r.props=r.props??{},r.props.key=`${s}`)),h(this,w,Ma).call(this,r,t)))},Ma=function(e,t){if(Array.isArray(e))return h(this,w,ao).call(this,e,t);if(Ap(e))if(e.type===void 0)try{return t.push({namespace:"fragment",...e.props}),h(this,w,ao).call(this,e.children,t)}finally{t.pop()}else if(typeof e.type=="function"){let r={...e.props,children:e.children.flat(1/0)};return h(this,w,Ba).call(this,e.type,r,t)}else try{t.push({namespace:e.type,...e.props});let r=h(this,w,ao).call(this,e.children,t),s=h(this,w,Yl).call(this,e.props??{});return[{type:e.type,children:r,props:s}]}finally{t.pop()}else return[(e??"").toString()]},Yl=function(e){let t={};for(let r in e)if(!(typeof e[r]>"u"))if(typeof e[r]=="function"){let s=ce({namespace:r,key:!1,initializer:({hookId:o})=>({hookId:o,state:null,onUIEvent:d=>{if(d.userAction)return e[r](d.userAction.data);if(d.webView?.postMessage)return e[r](d.webView.postMessage.message)}})});t[r]=s.hookId,"captureHookRef"in e[r]&&e[r].captureHookRef()}else{let s=JSON.parse(JSON.stringify(e[r]));s!=null&&(t[r]=s)}return t};function Ap(i){return typeof i=="object"&&i!=null&&"type"in i}var eu=i=>{let e=Number(i.trim().split(".").pop());return isNaN(e)?void 0:e},tu=i=>{let[e,t,r]=i.trim().split(";");if(!e||!t||!r){console.warn(`Received a malformed devvit-user-agent! Received: '${i}'`);return}if(e!=="Reddit"){console.warn(`Received unknown company name in user agent! Received: '${i}'`);return}if(t==="iOS"){let s=eu(r);if(s===void 0){console.warn(`Could not parse version number from user agent! Received: '${i}'`);return}return{company:"Reddit",platform:"iOS",rawVersion:r,versionNumber:s}}if(t==="Android"){let s=eu(r);if(s===void 0){console.warn(`Could not parse version number from user agent! Received: '${i}'`);return}return{company:"Reddit",platform:"Android",rawVersion:r,versionNumber:s}}if(t==="Shreddit")return{company:"Reddit",platform:"Shreddit",rawVersion:r};if(t==="Play")return{company:"Reddit",platform:"Play",rawVersion:r};console.warn("Received unknown platform:",t)},iu=i=>i?i.platform==="Android"?i.versionNumber<1875012:i.platform==="iOS"?i.versionNumber<614973:!1:(console.warn(`Could not parse devvit-user-agent! Received: '${JSON.stringify(i)}'`),!1),Tp=i=>{switch(i){case"Android":return"https://play.google.com/store/apps/details?id=com.reddit.frontpage";case"iOS":return"https://apps.apple.com/us/app/reddit/id1064216828";case"Play":case"Shreddit":break;default:console.error(`No upgrade link for platform: ${i}`)}},Rp=({platform:i},e)=>u.createElement("blocks",null,u.createElement("vstack",{alignment:"middle center",height:100,width:100},u.createElement("vstack",{maxWidth:"300px",gap:"large",alignment:"middle center"},u.createElement("vstack",{gap:"medium",alignment:"middle center"},u.createElement("image",{imageHeight:100,imageWidth:100,url:"https://i.redd.it/p1vmc5ulmpib1.png"}),u.createElement("text",{size:"large",weight:"bold",wrap:!0,alignment:"center"},"Uh oh, the app you're trying to use requires the latest version of Reddit. Please upgrade your app to continue.")),u.createElement("hstack",{alignment:"middle center"},u.createElement("button",{onPress:()=>{let t=Tp(i);t?e.ui.navigateTo(t):console.warn("No upgrade link found for platform:",i)}},"Upgrade"))))),ru=i=>()=>u.createElement(Rp,{platform:i});var Op=()=>u.createElement("vstack",{alignment:"center middle",width:"100%",height:"100%"},u.createElement("text",null,"This feature is not available yet")),Bp=[[uo,uo.methods.renderPostContent,(i,e)=>u.customPostType?.render(e)??null],[uo,uo.methods.renderPostComposer,(i,e)=>u.createElement(Op,null)]];function Mp(i){return async(e,t)=>{let r=tu(t["devvit-user-agent"]?.values?.[0]??"");if(r&&iu(r)){let o=new Bt(ru(r.platform));return nu.fromJSON(await o.handle(e,t))}let s=new Bt(i);return nu.fromJSON(await s.handle(e,t))}}function su(i){for(let[e,t,r]of Bp)i.provides(e),R(t.name,Mp(r))}var Ti,Kr,Ri,Mt,Ut,Oi,Bi,Dt,st,Zr,Xr,Nt,j,U=class U extends Ms{static configure(e){a(this,Ri,{...n(this,Ri),...e}),Ne(e.http)&&this.use(k.HTTPDefinition),(e.redis===void 0||Ne(e.kvStore)||Ne(e.redis))&&(this.use(k.KVStoreDefinition),this.use(k.RedisAPIDefinition)),Ne(e.media)&&this.use(k.MediaServiceDefinition),Ne(e.modLog)&&this.use(k.ModlogDefinition),Ne(e.redditAPI)&&(this.use(k.FlairDefinition),this.use(k.GraphQLDefinition),this.use(k.LinksAndCommentsDefinition),this.use(k.ListingsDefinition),this.use(k.ModerationDefinition),this.use(k.ModNoteDefinition),this.use(k.NewModmailDefinition),this.use(k.PrivateMessagesDefinition),this.use(k.SubredditsDefinition),this.use(k.UsersDefinition),this.use(k.WidgetsDefinition),this.use(k.WikiDefinition)),Ne(e.realtime)&&this.use(k.RealtimeDefinition)}static addMenuItem(e){n(this,Bi).push(e)}static addCustomPostType(e){a(this,Mt,e)}static createForm(e,t){let r=`form.${n(this,Ut).size}`;return n(this,Ut).set(r,{form:e,onSubmit:t}),r}static addSchedulerJob(e){if(n(this,j)[k.SchedulerDefinition.fullName]||this.use(k.SchedulerDefinition),n(this,Dt).has(e.name))throw new Error(`Job ${e.name} is already defined`);n(this,Dt).set(e.name,e.onRun)}static addSettings(e){Pt(e);let t=e.filter(s=>s.type==="group"||!s.scope||s.scope==="installation"),r=e.filter(s=>s.type!=="group"&&s.scope==="app");t.length>0&&a(this,Oi,t),r.length>0&&a(this,Ti,r),n(this,j)[k.SettingsDefinition.fullName]||this.use(k.SettingsDefinition)}static addTrigger(e){if("events"in e){for(let t of e.events)this.addTrigger({event:t,onEvent:(r,s)=>e.onEvent(r,s)});return this}return n(this,st).has(e.event)?n(this,st).get(e.event)?.push(e.onEvent):n(this,st).set(e.event,[e.onEvent]),U}static provide(e){n(this,Xr).push(e)}static use(e,t){n(this,Nt)[e.fullName]={def:e,options:t??{},handler:void 0};let r={};for(let s of Object.values(e.methods))r[s.name]=(o,d)=>n(this,Nt)[e.fullName].handler?.[s.name]?.(s.requestType?.fromPartial(o??{}),d);return n(this,j)[e.fullName]=r,r}static get redditAPIPlugins(){if(!Ne(n(this,Ri).redditAPI))throw new Error("Reddit API is not enabled. You can enable it by passing `redditAPI: true` to `Devvit.configure`.");return{Flair:n(this,j)[k.FlairDefinition.fullName],GraphQL:n(this,j)[k.GraphQLDefinition.fullName],LinksAndComments:n(this,j)[k.LinksAndCommentsDefinition.fullName],Listings:n(this,j)[k.ListingsDefinition.fullName],Moderation:n(this,j)[k.ModerationDefinition.fullName],ModNote:n(this,j)[k.ModNoteDefinition.fullName],NewModmail:n(this,j)[k.NewModmailDefinition.fullName],PrivateMessages:n(this,j)[k.PrivateMessagesDefinition.fullName],Subreddits:n(this,j)[k.SubredditsDefinition.fullName],Users:n(this,j)[k.UsersDefinition.fullName],Widgets:n(this,j)[k.WidgetsDefinition.fullName],Wiki:n(this,j)[k.WikiDefinition.fullName]}}static get modLogPlugin(){let e=n(this,j)[k.ModlogDefinition.fullName];if(!e)throw new Error("ModLog is not enabled. You can enable it by passing `modLog: true` to `Devvit.configure`");return e}static get schedulerPlugin(){let e=n(this,j)[k.SchedulerDefinition.fullName];if(!e)throw new Error("Scheduler is not enabled. You can enable it by calling `Devvit.addSchedulerJob` at the top level of your app.");return e}static get kvStorePlugin(){let e=n(this,j)[k.KVStoreDefinition.fullName];if(!e)throw new Error("Key Value Store is not enabled. You can enable it by passing `kvStore: true` to `Devvit.configure`");return e}static get redisPlugin(){let e=n(this,j)[k.RedisAPIDefinition.fullName];if(!e)throw new Error("Redis is not enabled. You can enable it by passing `redis: true` to `Devvit.configure`");return e}static get mediaPlugin(){let e=n(this,j)[k.MediaServiceDefinition.fullName];if(!e)throw new Error("MediaService is not enabled. You can enable it by passing `media: true` to `Devvit.configure`");return e}static get settingsPlugin(){let e=n(this,j)[k.SettingsDefinition.fullName];if(!e)throw new Error("Settings must first be configured with `Devvit.addSettings()` before they can be accessed");return e}static get realtimePlugin(){let e=n(this,j)[k.RealtimeDefinition.fullName];if(!e)throw new Error("Realtime is not enabled. You can enable it by passing `realtime: true` to `Devvit.configure`");return e}static get menuItems(){return n(this,Bi)}static get customPostType(){return n(this,Mt)}static get formDefinitions(){return n(this,Ut)}static get scheduledJobHandlers(){return n(this,Dt)}static get installationSettings(){return n(this,Oi)}static get appSettings(){return n(this,Ti)}static get triggerOnEventHandlers(){return n(this,st)}static get assets(){return n(this,Kr)}static get webViewAssets(){return n(this,Zr)}constructor(e){super(e),a(U,Kr,e.assets??{}),a(U,Zr,e.webviewAssets??{});for(let t in n(U,Nt)){let r=n(U,Nt)[t];r.handler=e.use(r.def,r.options)}n(U,Bi).length>0&&ul(e),n(U,Dt).size>0&&cl(e),n(U,Mt)&&(nl(e),su(e)),(n(U,Mt)||n(U,Ut).size>0)&&Tl(e),n(U,Oi)&&sl(e),n(U,Ti)&&_d(e),n(U,st).size>0&&ml(e);for(let t of n(U,Xr))e.provides(t)}};Ti=new WeakMap,Kr=new WeakMap,Ri=new WeakMap,Mt=new WeakMap,Ut=new WeakMap,Oi=new WeakMap,Bi=new WeakMap,Dt=new WeakMap,st=new WeakMap,Zr=new WeakMap,Xr=new WeakMap,Nt=new WeakMap,j=new WeakMap,U.debug={},l(U,Ti),l(U,Kr,{}),l(U,Ri,{}),l(U,Mt),l(U,Ut,new Map),l(U,Oi),l(U,Bi,[]),l(U,Dt,new Map),l(U,st,new Map),l(U,Zr,{}),l(U,Xr,[]),l(U,Nt,{}),l(U,j,{});var u=U;(e=>{function i(t,r,...s){return{type:t,props:r,children:s}}e.createElement=i})(u||(u={}));function K(i){let e=Object.getOwnPropertyDescriptors(i.constructor.prototype);for(let[t,r]of Object.entries(e))r.get&&Object.defineProperty(i,t,{...r,enumerable:!0})}var Ua;(function(i){i[i.bold=1]="bold",i[i.italic=2]="italic",i[i.underline=4]="underline",i[i.strikethrough=8]="strikethrough",i[i.subscript=16]="subscript",i[i.superscript=32]="superscript",i[i.monospace=64]="monospace"})(Ua||(Ua={}));var ou="text",au="raw",du="br",lu="link",uu="c/",cu="p/",mu="r/",pu="u/",gu="@",hu="spoilertext",fu="par",bu="h",yu="hr",vu="blockquote",ku="code",Cu="li",Su="list",Pu="L",wu="R",Fu="C",xu="table",Iu="embed",Eu="img",Au="gif",Tu="video";function Ru(i){return{e:Au,id:i.mediaId,...i.caption&&{c:i.caption},...i.blur&&{o:i.blur}}}function Ou(i,e){let t={},r=[];return Object.assign(t,Qr(t,r),Yr(t,r),en(t,r),nn(t,r),sn(t,r),on(t,r)),e(t),{e:vu,c:r,...i.author&&{a:i.author}}}function Bu(i,e){let t={},r=[];return Object.assign(t,Na(t,r)),e(t),{e:ku,c:r,...i.language&&{l:i.language}}}function Mu(i){return{e:uu,t:i.permalink}}function Uu(i,e){let t={},r=[];return Object.assign(t,Na(t,r),rn(t,r)),e(t),{e:bu,l:i.level,c:r}}function Du(i){return{e:Iu,u:i.sourceUrl,c:i.contentUrl,x:i.width,y:i.height}}function Nu(){return{e:yu}}function Lu(i){return{e:Eu,id:i.mediaId,...i.caption&&{c:i.caption},...i.blur&&{o:i.blur}}}function _u(){return{e:du}}function Hu(i){return{e:lu,t:i.text,u:i.url,...i.formatting&&{f:i.formatting},...i.tooltip&&{a:i.tooltip}}}function ju(i,e){let t={},r=[];return Object.assign(t,rc(t,r)),e(t),{e:Su,o:i.ordered,c:r}}function Wu(i){let e={},t=[];return Object.assign(e,Qr(e,t),Yr(e,t),en(e,t),co(e,t),nn(e,t),sn(e,t),on(e,t)),i(e),{e:Cu,c:t}}function Vu(i){let e={},t=[];return Object.assign(e,mo(e,t),rn(e,t),Da(e,t),La(e,t),tn(e,t)),i(e),{e:fu,c:t}}function Gu(i){return{e:cu,t:i.permalink}}function Ju(i){return{e:au,t:i}}function zu(i){let e={},t=[];return Object.assign(e,mo(e,t),rn(e,t),Da(e,t)),i(e),{e:hu,c:t}}function qu(i){return{e:mu,t:i.subredditName,l:i.showPrefix}}function $u(i){let e={},t=[],r=[];return Object.assign(e,nc(e,t,r)),i(e),{e:xu,h:t,c:r}}function Ku(i){let[e,t]=ic();return i(e),{c:t}}function Zu(i,e){let[t,r]=ic();e(t);let s;switch(i.columnAlignment){case"left":s=Pu;break;case"right":s=wu;break;case"center":s=Fu;break}return{...s&&{a:s},...r&&{c:r}}}function Xu(i){let e={},t=[];return Object.assign(e,sc(e,t)),i(e),t}function Qu(i){return{e:ou,t:i.text,...i.formatting&&{f:i.formatting}}}function Yu(i){return{e:pu,t:i.username,l:i.showPrefix}}function ec(i){return{e:gu,t:i.username,l:i.showPrefix}}function tc(i){return{e:Tu,id:i.mediaId,...i.caption&&{c:i.caption},...i.blur&&{o:i.blur},...i.thumbnail&&{p:i.thumbnail},...i.convertToGif&&{gifify:i.convertToGif}}}function ic(){let i={},e=[];return Object.assign(i,mo(i,e),rn(i,e),La(i,e),tn(i,e)),[i,e]}function Qr(i,e){return{blockQuote(t,r){return e.push(Ou(t,r)),i}}}function Yr(i,e){return{codeBlock(t,r){return e.push(Bu(t,r)),i}}}function oc(i,e){return{embed(t){return e.push(Du(t)),i}}}function en(i,e){return{heading(t,r){return e.push(Uu(t,r)),i}}}function co(i,e){return{horizontalRule(){return e.push(Nu()),i}}}function tn(i,e){return{image(t){return e.push(Lu(t)),i},animatedImage(t){return e.push(Ru(t)),i}}}function Da(i,e){return{linebreak(){return e.push(_u()),i}}}function rn(i,e){return{link(t){return e.push(Hu(t)),i},commentLink(t){return e.push(Mu(t)),i},postLink(t){return e.push(Gu(t)),i},subredditLink(t){return e.push(qu(t)),i},userLink(t){return e.push(Yu(t)),i},userMention(t){return e.push(ec(t)),i}}}function nn(i,e){return{list(t,r){return e.push(ju(t,r)),i}}}function rc(i,e){return{item(t){return e.push(Wu(t)),i}}}function sn(i,e){return{paragraph(t){return e.push(Vu(t)),i}}}function Na(i,e){return{rawText(t){return e.push(Ju(t)),i}}}function La(i,e){return{spoiler(t){return e.push(zu(t)),i}}}function nc(i,e,t){return{headerCell(r,s){return e.push(Zu(r,s)),i},row(r){return t.push(Xu(r)),i}}}function on(i,e){return{table(t){return e.push($u(t)),i}}}function sc(i,e){return{cell(t){return e.push(Ku(t)),i}}}function mo(i,e){return{text(t){return e.push(Qu(t)),i}}}function ac(i,e){return{video(t){return e.push(tc(t)),i}}}var Up=function(i,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?i!==e||!s:!e.has(i))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(i,t):s?s.value=t:e.set(i,t),t},Dp=function(i,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?i!==e||!r:!e.has(i))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(i):r?r.value:e.get(i)},po,Lt=class{constructor(){po.set(this,void 0);let e=[];Object.assign(this,sn(this,e),en(this,e),co(this,e),Qr(this,e),Yr(this,e),oc(this,e),nn(this,e),on(this,e),tn(this,e),ac(this,e)),Up(this,po,{document:e},"f")}build(){return JSON.stringify(Dp(this,po,"f"))}paragraph(e){return this}heading(e,t){return this}horizontalRule(){return this}blockQuote(e,t){return this}codeBlock(e,t){return this}embed(e){return this}list(e,t){return this}table(e){return this}image(e){return this}animatedImage(e){return this}video(e){return this}};po=new WeakMap;function Mi(i){let e;return i instanceof Lt?e=i.build():typeof i=="object"?e=JSON.stringify(i):e=i,e}var dc=100,lc=1/0,_t,Ht,ot,Ui,Di,go,W=class{constructor(e){l(this,Di);l(this,_t);l(this,Ht);l(this,ot);l(this,Ui,!1);this.pageSize=dc;this.limit=lc;this.children=[];K(this),this._fetch=e.fetch,this.pageSize=e.pageSize??dc,this.limit=e.limit??lc,a(this,Ht,e.after),a(this,_t,e.before),a(this,ot,e.more),e.children&&(this.children=e.children)}get hasMore(){return!n(this,Ui)||!!(n(this,Ht)||n(this,_t)||n(this,ot))}async*[Symbol.asyncIterator](){let e=0;for(;;){if(e===this.children.length)if(this.hasMore){if((await h(this,Di,go).call(this)).length===0)break}else break;if(yield this.children[e],e++,e===this.limit)break}}setMore(e){a(this,ot,e)}preventInitialFetch(){a(this,Ui,!0)}async all(){for(;this.hasMore&&this.children.length<this.limit;)await h(this,Di,go).call(this);return this.children.slice(0,this.limit)}async get(e){let t=e<=this.limit?e:this.limit;for(;this.hasMore&&this.children.length<t;)await h(this,Di,go).call(this);return this.children.slice(0,t)}};_t=new WeakMap,Ht=new WeakMap,ot=new WeakMap,Ui=new WeakMap,Di=new WeakSet,go=async function(){if(!this.hasMore)throw new Error("This listing does not have any more items to load.");let{children:e,before:t,after:r,more:s}=await this._fetch({before:n(this,_t),after:n(this,Ht),limit:this.pageSize,more:n(this,ot)});return this.children.push(...e),a(this,_t,t),a(this,Ht,r),a(this,ot,s),a(this,Ui,!0),e};var an,_a,ye=class{constructor(){}static get(e,t){let r=u.redditAPIPlugins.ModNote;return new W({hasMore:!0,before:e.before,limit:e.limit,pageSize:e.limit,fetch:async s=>{let o=await r.GetNotes({subreddit:e.subreddit,user:e.user,filter:e.filter,before:s.before,limit:s.limit},t);return{children:o.modNotes?.map(d=>h(this,an,_a).call(this,d))||[],before:o.hasNextPage?o.endCursor:void 0,hasMore:o.hasNextPage}}})}static async delete(e,t){let r=u.redditAPIPlugins.ModNote,{deleted:s}=await r.DeleteNotes(e,t);return!!s}static async add(e,t){let s=await u.redditAPIPlugins.ModNote.PostNotes(e,t);if(!s?.created)throw new Error("Failed to create mod note");return h(this,an,_a).call(this,s.created)}static async addRemovalNote(e,t){await u.redditAPIPlugins.ModNote.PostRemovalNote(e,t)}};an=new WeakSet,_a=function(e){return p(e.id,"Mod note ID is null or undefined"),p(e.createdAt,"Mod note createdAt is null or undefined"),p(e.type,"Mod note type is null or undefined"),p(e.subreddit,"Mod note subreddit is null or undefined"),p(e.subredditId,"Mod note subredditId is null or undefined"),p(e.operator,"Mod note operator is null or undefined"),p(e.operatorId,"Mod note operatorId is null or undefined"),p(e.user,"Mod note user is null or undefined"),p(e.userId,"Mod note userId is null or undefined"),p(e.userNoteData,"Mod note userNote is null or undefined"),p(e.modActionData,"Mod note modAction is null or undefined"),{id:e.id,user:{id:te(e.userId??""),name:e.user},subreddit:{id:$(e.subredditId??""),name:e.subreddit},operator:{id:te(e.operatorId??""),name:e.operator},createdAt:new Date(e.createdAt*1e3),userNote:{note:e.userNoteData?.note,redditId:e.userNoteData?.redditId?he(e.userNoteData?.redditId):void 0,label:e.userNoteData?.label},type:e.type}},l(ye,an);var Q=class{static queryWithQueryString(e,t){return u.redditAPIPlugins.GraphQL.Query({query:e},t)}static query(e,t,r,s){return u.redditAPIPlugins.GraphQL.PersistedQuery({operationName:e,id:t,variables:r},s)}};var uc=["all","wiki","posts","access","mail","config","flair","channels","chat_config","chat_operator","community_chat"];function Np(i,e){return e.map(t=>(i.includes(t)?"+":"-")+t).join(",")}function Ha(i){return Np(i,uc)}function cc(i){return i.filter(e=>uc.includes(e))}var Lp=(t=>(t.User="USER_FLAIR",t.Post="LINK_FLAIR",t))(Lp||{}),Wt,Ni,Li,_i,Hi,ji,Wi,Vi,Gi,Ji,zi,ho,xe=class xe{constructor(e,t,r){l(this,Wt);l(this,Ni);l(this,Li);l(this,_i);l(this,Hi);l(this,ji);l(this,Wi);l(this,Vi);l(this,Gi);l(this,Ji);K(this),p(e.id),p(e.text),a(this,Wt,e.id),a(this,Ni,t),a(this,Li,e.text),a(this,_i,_p(e.textColor)),a(this,Hi,Hp(e.backgroundColor)),a(this,ji,jp(e.allowableContent)),a(this,Wi,e.modOnly),a(this,Vi,e.maxEmojis),a(this,Gi,e.textEditable),a(this,Ji,r)}get id(){return n(this,Wt)}get text(){return n(this,Li)}get textColor(){return n(this,_i)}get backgroundColor(){return n(this,Hi)}get allowableContent(){return n(this,ji)}get modOnly(){return n(this,Wi)}get maxEmojis(){return n(this,Vi)}get allowUserEdits(){return n(this,Gi)}async delete(){return xe.deleteFlairTemplate(n(this,Wt),n(this,Ni),n(this,Ji))}async edit(e){return xe.editFlairTemplate({id:n(this,Wt),subredditName:n(this,Ni),text:e.text??n(this,Li),allowableContent:e.allowableContent??n(this,ji),backgroundColor:e.backgroundColor??n(this,Hi),maxEmojis:e.maxEmojis??n(this,Vi),modOnly:e.modOnly??n(this,Wi),textColor:e.textColor??n(this,_i),allowUserEdits:e.allowUserEdits??n(this,Gi)},n(this,Ji))}static async createPostFlairTemplate(e,t){var r;return h(r=xe,zi,ho).call(r,{...e,flairType:"LINK_FLAIR"},t)}static async createUserFlairTemplate(e,t){var r;return h(r=xe,zi,ho).call(r,{...e,flairType:"USER_FLAIR"},t)}static async editFlairTemplate(e,t){var r;return h(r=xe,zi,ho).call(r,e,t)}static async getPostFlairTemplates(e,t){return(await u.redditAPIPlugins.Flair.LinkFlair({subreddit:e},t)).flair?.map(o=>new xe(o,e,t))||[]}static async getUserFlairTemplates(e,t){return(await u.redditAPIPlugins.Flair.UserFlair({subreddit:e},t)).flair?.map(o=>new xe(o,e,t))||[]}static async deleteFlairTemplate(e,t,r){await u.redditAPIPlugins.Flair.DeleteFlairTemplate({subreddit:e,flairTemplateId:t},r)}};Wt=new WeakMap,Ni=new WeakMap,Li=new WeakMap,_i=new WeakMap,Hi=new WeakMap,ji=new WeakMap,Wi=new WeakMap,Vi=new WeakMap,Gi=new WeakMap,Ji=new WeakMap,zi=new WeakSet,ho=async function(e,t){let{subredditName:r,allowableContent:s="all",backgroundColor:o="transparent",flairType:d="",maxEmojis:c=10,modOnly:m=!1,text:y,textColor:v="dark",allowUserEdits:f=!1,id:S=""}=e;if(m&&f)throw new Error("Cannot have a mod only flair that is editable by users");let O=await u.redditAPIPlugins.Flair.FlairTemplate({subreddit:r,allowableContent:s,backgroundColor:o,flairType:d,maxEmojis:c,modOnly:m,text:y,textColor:v,textEditable:f,flairTemplateId:S,cssClass:"",overrideCss:!1},t);return new xe(O,r,t)},l(xe,zi);var ne=xe;function dn(i){return{flairCssClass:i.flairCssClass,user:i.user,flairText:i.flairText}}var at,ja,Wa,jt=class jt{static async getUserFlairBySubreddit(e,t){return u.redditAPIPlugins.Flair.FlairList(e,t)}static setUserFlair(e,t){var r;return h(r=jt,at,ja).call(r,e,t)}static setPostFlair(e,t){var r;return h(r=jt,at,ja).call(r,{...e,postId:de(e.postId)},t)}static async removePostFlair(e,t,r){var s;return h(s=jt,at,Wa).call(s,e,t,void 0,r)}static async removeUserFlair(e,t,r){var s;return h(s=jt,at,Wa).call(s,e,void 0,t,r)}};at=new WeakSet,ja=async function(e,t){await u.redditAPIPlugins.Flair.SelectFlair({subreddit:e.subredditName,flairTemplateId:e.flairTemplateId??"",text:e.text??"",name:e.username,link:e.postId,backgroundColor:e.backgroundColor??"",textColor:e.textColor??"dark",cssClass:e.cssClass??"",returnRtjson:"none"},t)},Wa=async function(e,t,r,s){await u.redditAPIPlugins.Flair.SelectFlair({subreddit:e,name:r??"",link:t??"",flairTemplateId:"",backgroundColor:"",text:"",textColor:"",cssClass:"",returnRtjson:"none"},s)},l(jt,at);var ve=jt;function _p(i){if(p(i,"Flair text color is required"),i==="light"||i==="dark")return i;throw new Error(`Invalid flair text color: ${i}`)}function Hp(i){if(!i||i.length===0||i==="transparent")return"transparent";if(/^#([A-Fa-f0-9]{6})$/.test(i))return i;throw new Error(`Invalid flair background color: ${i}`)}function jp(i){if(i==="all"||i==="text"||i==="emoji")return i;throw new Error(`Invalid allowable content: ${i}`)}import"@devvit/protos";import{Block as hc,UIResponse as Zp}from"@devvit/protos";var Ja=ed(gc(),1);var Ga=i=>"text"in i?i.text:Kp(i.richtext),Kp=i=>i instanceof Lt?i.build():typeof i=="object"?JSON.stringify(i):i;var Xp={NONE:0,BLOCKS:1,UNRECOGNIZED:-1},qi,un,$i,cn,Ki,mn,pn,gn,Gt,hn,fn,bn,yn,vn,kn,dt,Cn,Sn,Jt,Zi,lt,Xi,Qi,Yi,ut,ct,mt,er,pt,gt,ht,He,Pn,wn,tr,ir,M,D=class D{constructor(e,t){l(this,qi);l(this,un);l(this,$i);l(this,cn);l(this,Ki);l(this,mn);l(this,pn);l(this,gn);l(this,Gt);l(this,hn);l(this,fn);l(this,bn);l(this,yn);l(this,vn);l(this,kn);l(this,dt);l(this,Cn);l(this,Sn);l(this,Jt);l(this,Zi);l(this,lt);l(this,Xi);l(this,Qi);l(this,Yi);l(this,ut);l(this,ct);l(this,mt);l(this,er);l(this,pt);l(this,gt);l(this,ht);l(this,He);l(this,Pn);l(this,wn);l(this,tr);l(this,ir);l(this,M);K(this),p(e.id,"Post is missing id"),p(e.title,"Post is missing title"),p(e.createdUtc,"Post is missing created date"),p(e.author,"Post is missing author name"),p(e.subreddit,"Post is missing subreddit name"),p(e.subredditId,"Post is missing subreddit id"),p(e.url,"Post is missing url"),p(e.permalink,"Post is missing permalink"),a(this,qi,de(`t3_${e.id}`)),a(this,$i,e.author),a(this,un,e.authorFullname?te(e.authorFullname):void 0),a(this,Ki,$(e.subredditId)),a(this,mn,e.subreddit),a(this,bn,e.score??0),a(this,yn,e.numComments??0),a(this,vn,e.numReports??0);let r=new Date(0);r.setUTCSeconds(e.createdUtc),a(this,cn,r),a(this,gn,e.title),a(this,Gt,e.selftext),a(this,hn,e.selftextHtml),a(this,fn,e.url),a(this,pn,e.permalink),e.thumbnail&&e.thumbnail!=="self"&&e.thumbnail!=="nsfw"&&e.thumbnailHeight!=null&&e.thumbnailWidth!=null&&a(this,kn,{url:e.thumbnail,height:e.thumbnailHeight,width:e.thumbnailWidth}),a(this,dt,e.approved??!1),a(this,Cn,e.approvedAtUtc??0),a(this,Sn,e.bannedAtUtc??0),a(this,lt,e.removed??!1),a(this,Xi,e.removedBy),a(this,Qi,e.removedByCategory),a(this,Jt,e.spam??!1),a(this,Zi,e.stickied??!1),a(this,Yi,e.archived??!1),a(this,ut,e.edited??!1),a(this,ct,e.locked??!1),a(this,mt,e.over18??!1),a(this,er,e.quarantine??!1),a(this,pt,e.spoiler),a(this,gt,e.hidden??!1),a(this,ht,e.ignoreReports??!1),a(this,He,e.distinguished),a(this,wn,e.secureMedia),a(this,tr,(e.modReports??[]).map(([s])=>s)),a(this,ir,(e.userReports??[]).map(([s])=>s)),a(this,M,t),(e.linkFlairBackgroundColor||e.linkFlairCssClass||e.linkFlairText||e.linkFlairType||e.linkFlairTemplateId||e.linkFlairRichtext||e.linkFlairTextColor)&&a(this,Pn,{backgroundColor:e.linkFlairBackgroundColor,cssClass:e.linkFlairCssClass,text:e.linkFlairText,type:e.linkFlairType,templateId:e.linkFlairTemplateId,richtext:(e.linkFlairRichtext??[]).map(({e:s,t:o,a:d,u:c})=>({elementType:s,text:o,emojiRef:d,url:c})),textColor:e.linkFlairTextColor})}get id(){return n(this,qi)}get authorId(){return n(this,un)}get authorName(){return n(this,$i)}get subredditId(){return n(this,Ki)}get subredditName(){return n(this,mn)}get permalink(){return n(this,pn)}get title(){return n(this,gn)}get body(){return n(this,Gt)}get bodyHtml(){return n(this,hn)}get url(){return n(this,fn)}get thumbnail(){return n(this,kn)}get createdAt(){return n(this,cn)}get score(){return n(this,bn)}get numberOfComments(){return n(this,yn)}get numberOfReports(){return n(this,vn)}get approved(){return n(this,dt)}get approvedAtUtc(){return n(this,Cn)}get bannedAtUtc(){return n(this,Sn)}get spam(){return n(this,Jt)}get stickied(){return n(this,Zi)}get removed(){return n(this,lt)}get removedBy(){return n(this,Xi)}get removedByCategory(){return n(this,Qi)}get archived(){return n(this,Yi)}get edited(){return n(this,ut)}get locked(){return n(this,ct)}get nsfw(){return n(this,mt)}get quarantined(){return n(this,er)}get spoiler(){return n(this,pt)}get hidden(){return n(this,gt)}get ignoringReports(){return n(this,ht)}get distinguishedBy(){return n(this,He)}get comments(){return X.getComments({postId:this.id},n(this,M))}get flair(){return n(this,Pn)}get secureMedia(){return n(this,wn)}get userReportReasons(){return n(this,ir)}get modReportReasons(){return n(this,tr)}toJSON(){return{id:this.id,authorId:this.authorId,authorName:this.authorName,subredditId:this.subredditId,subredditName:this.subredditName,permalink:this.permalink,title:this.title,body:this.body,bodyHtml:this.bodyHtml,url:this.url,thumbnail:this.thumbnail,score:this.score,numberOfComments:this.numberOfComments,numberOfReports:this.numberOfReports,createdAt:this.createdAt,approved:this.approved,spam:this.spam,stickied:this.stickied,removed:this.removed,removedBy:n(this,Xi),removedByCategory:n(this,Qi),archived:this.archived,edited:this.edited,locked:this.locked,nsfw:this.nsfw,quarantined:this.quarantined,spoiler:this.spoiler,hidden:this.hidden,ignoringReports:this.ignoringReports,distinguishedBy:this.distinguishedBy,flair:this.flair,secureMedia:this.secureMedia,modReportReasons:n(this,tr),userReportReasons:n(this,ir)}}isApproved(){return n(this,dt)}isSpam(){return n(this,Jt)}isStickied(){return n(this,Zi)}isRemoved(){return n(this,lt)}isArchived(){return n(this,Yi)}isEdited(){return n(this,ut)}isLocked(){return n(this,ct)}isNsfw(){return n(this,mt)}isQuarantined(){return n(this,er)}isSpoiler(){return n(this,pt)}isHidden(){return n(this,gt)}isIgnoringReports(){return n(this,ht)}isDistinguishedBy(){return n(this,He)}async edit(e){let t=await D.edit({id:this.id,...e},n(this,M));a(this,Gt,t.body),a(this,ut,t.edited)}async setSuggestedCommentSort(e){await D.setSuggestedCommentSort({id:this.id,subredditId:n(this,Ki),suggestedSort:e},n(this,M))}async setCustomPostPreview(e){await D.setCustomPostPreview({id:this.id,ui:e},n(this,M))}async setTextFallback(e){let t=await D.setTextFallback(e,this.id,n(this,M));a(this,Gt,t.body),a(this,ut,t.edited)}async addComment(e){return X.submit({id:this.id,...e},n(this,M))}async delete(){return D.delete(this.id,n(this,M))}async approve(){await D.approve(this.id,n(this,M)),a(this,dt,!0),a(this,lt,!1)}async remove(e=!1){await D.remove(this.id,e,n(this,M)),a(this,lt,!0),a(this,Jt,e),a(this,dt,!1)}async lock(){await D.lock(this.id,n(this,M)),a(this,ct,!0)}async unlock(){await D.unlock(this.id,n(this,M)),a(this,ct,!1)}async hide(){await D.hide(this.id,n(this,M)),a(this,gt,!0)}async unhide(){await D.unhide(this.id,n(this,M)),a(this,gt,!1)}async markAsNsfw(){await D.markAsNsfw(this.id,n(this,M)),a(this,mt,!0)}async unmarkAsNsfw(){await D.unmarkAsNsfw(this.id,n(this,M)),a(this,mt,!1)}async markAsSpoiler(){await D.markAsSpoiler(this.id,n(this,M)),a(this,pt,!0)}async unmarkAsSpoiler(){await D.unmarkAsSpoiler(this.id,n(this,M)),a(this,pt,!1)}async sticky(e){await D.sticky(this.id,e,n(this,M))}async unsticky(){await D.unsticky(this.id,n(this,M))}async distinguish(){let{distinguishedBy:e}=await D.distinguish(this.id,!1,n(this,M));a(this,He,e)}async distinguishAsAdmin(){let{distinguishedBy:e}=await D.distinguish(this.id,!0,n(this,M));a(this,He,e)}async undistinguish(){let{distinguishedBy:e}=await D.undistinguish(this.id,n(this,M));a(this,He,e)}async ignoreReports(){await D.ignoreReports(this.id,n(this,M)),a(this,ht,!0)}async unignoreReports(){await D.unignoreReports(this.id,n(this,M)),a(this,ht,!1)}async getAuthor(){return C.getByUsername(n(this,$i),n(this,M))}async crosspost(e){return D.crosspost({...e,postId:this.id},n(this,M))}addRemovalNote(e){return ye.addRemovalNote({itemIds:[n(this,qi)],...e},n(this,M))}async getEnrichedThumbnail(){return Qp({id:this.id},n(this,M))}static async getById(e,t){let r=u.redditAPIPlugins.LinksAndComments,s=St(e)?e:`t3_${e}`,o=await r.Info({subreddits:[],thingIds:[s]},t);if(!o.data?.children?.length)throw new Error("could not find post");let d=o.data.children[0];if(!d?.data)throw new Error("could not find post");return new D(d.data,t)}static async submit(e,t){let r=u.redditAPIPlugins.LinksAndComments,s;if("preview"in e){p(t,"Missing metadata in `SubmitPostOptions`");let c=await new De(()=>e.preview,void 0,{},t,void 0).buildBlocksUI(),m=hc.encode(c).finish(),{textFallback:y,...v}=e,f=y?Ga(y):"",S={kind:"custom",sr:e.subredditName,richtextJson:(0,Ja.fromByteArray)(m),richtextFallback:f,...v};s=await r.SubmitCustomPost(S,t)}else s=await r.Submit({kind:"kind"in e?e.kind:"url"in e?"link":"self",sr:e.subredditName,richtextJson:"richtext"in e?Mi(e.richtext):void 0,...e},t);if("kind"in e&&["image","video","videogif"].includes(e.kind)&&!s.json?.data?.id&&"url"in e)throw new Error(`Post of ${e.kind} type with ${e.url} is being created asynchronously and should be updated in the subreddit soon.`);if(!s.json?.data?.id||s.json?.errors?.length)throw new Error(`failed to submit post - either post ID is empty or request failed with errors: ${s.json?.errors}`);return D.getById(`t3_${s.json.data.id}`,t)}static async crosspost(e,t){let r=u.redditAPIPlugins.LinksAndComments,{postId:s,subredditName:o,...d}=e,c=await r.Submit({kind:"crosspost",sr:o,crosspostFullname:de(s),...d},t);if(!c.json?.data?.id||c.json?.errors?.length)throw new Error("failed to crosspost post");return D.getById(`t3_${c.json.data.id}`,t)}static async edit(e,t){let r=u.redditAPIPlugins.LinksAndComments,{id:s}=e,o;if("richtext"in e&&(o=Mi(e.richtext)),(await r.EditUserText({thingId:s,text:"text"in e?e.text:"",richtextJson:o},t)).json?.errors?.length)throw new Error("Failed to edit post");return D.getById(s,t)}static async setSuggestedCommentSort(e,t){if(!(await Q.query("SetSuggestedSort","cf6052acc7fefaa65b710625b81dba8041f258313aafe9730e2a3dc855e5d10d",{input:{subredditId:e.subredditId,postId:e.id,sort:e.suggestedSort}},t)).data?.setSuggestedSort?.ok)throw new Error("Failed to set suggested sort")}static async setCustomPostPreview(e,t){if(!t)throw new Error("Failed to set custom post preview. Metadata not found");let r=u.redditAPIPlugins.LinksAndComments,s=new Bt(e.ui),d=Zp.fromJSON(await s.handle({events:[]},t)).blocks,c=(0,Ja.fromByteArray)(hc.encode(d).finish());await r.SetCustomPostPreview({thingId:e.id,bodyType:Xp.BLOCKS,blocksRenderContent:c},t)}static async setTextFallback(e,t,r){if(!("text"in e)&&!("richtext"in e))throw new Error(`No text fallback provided for post ${t}.`);let s=u.redditAPIPlugins.LinksAndComments,o=Ga(e);if((await s.EditCustomPost({thingId:t,richtextFallback:o},r)).json?.errors?.length)throw new Error("Failed to set post text fallback");return D.getById(t,r)}static async delete(e,t){await u.redditAPIPlugins.LinksAndComments.Del({id:e},t)}static async approve(e,t){await u.redditAPIPlugins.Moderation.Approve({id:e},t)}static async remove(e,t=!1,r){await u.redditAPIPlugins.Moderation.Remove({id:e,spam:t},r)}static async hide(e,t){await u.redditAPIPlugins.LinksAndComments.Hide({id:e},t)}static async unhide(e,t){await u.redditAPIPlugins.LinksAndComments.Unhide({id:e},t)}static async markAsNsfw(e,t){await u.redditAPIPlugins.LinksAndComments.MarkNSFW({id:e},t)}static async unmarkAsNsfw(e,t){await u.redditAPIPlugins.LinksAndComments.UnmarkNSFW({id:e},t)}static async markAsSpoiler(e,t){await u.redditAPIPlugins.LinksAndComments.Spoiler({id:e},t)}static async unmarkAsSpoiler(e,t){await u.redditAPIPlugins.LinksAndComments.Unspoiler({id:e},t)}static async sticky(e,t,r){await u.redditAPIPlugins.LinksAndComments.SetSubredditSticky({id:e,state:!0,num:t},r)}static async unsticky(e,t){await u.redditAPIPlugins.LinksAndComments.SetSubredditSticky({id:e,state:!1},t)}static async lock(e,t){await u.redditAPIPlugins.LinksAndComments.Lock({id:e},t)}static async unlock(e,t){await u.redditAPIPlugins.LinksAndComments.Unlock({id:e},t)}static async distinguish(e,t,r){let d=(await u.redditAPIPlugins.Moderation.Distinguish({id:e,how:t?"admin":"yes",sticky:!1},r)).json?.data?.things?.[0]?.data;return p(d),{distinguishedBy:d.distinguished}}static async undistinguish(e,t){let o=(await u.redditAPIPlugins.Moderation.Distinguish({id:e,how:"no",sticky:!1},t)).json?.data?.things?.[0]?.data;return p(o),{distinguishedBy:o.distinguished}}static async ignoreReports(e,t){await u.redditAPIPlugins.Moderation.IgnoreReports({id:e},t)}static async unignoreReports(e,t){await u.redditAPIPlugins.Moderation.UnignoreReports({id:e},t)}static getControversialPosts(e={},t){return this.getSortedPosts({...e,sort:"controversial"},t)}static getTopPosts(e={},t){return this.getSortedPosts({...e,sort:"top"},t)}static getSortedPosts(e,t){let r=u.redditAPIPlugins.Listings;return new W({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,fetch:async s=>{let o=await r.Sort({show:"all",sort:e.sort,t:e.timeframe,subreddit:e.subredditName,...s},t);return ln(o,t)}})}static getHotPosts(e={location:"GLOBAL"},t){let r=u.redditAPIPlugins.Listings;return new W({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,fetch:async s=>{let o=await r.Hot({g:e.location,show:"all",subreddit:e.subredditName,...s},t);return ln(o,t)}})}static getNewPosts(e,t){let r=u.redditAPIPlugins.Listings;return new W({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,fetch:async s=>{let o=await r.New({show:"all",subreddit:e.subredditName,...s},t);return ln(o,t)}})}static getRisingPosts(e,t){let r=u.redditAPIPlugins.Listings;return new W({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,fetch:async s=>{let o=await r.Rising({show:"all",subreddit:e.subredditName,...s},t);return ln(o,t)}})}static getPostsByUser(e,t){let r=u.redditAPIPlugins.Users;return new W({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,async fetch(s){let o=await r.UserWhere({username:e.username,where:"submitted",...s},t);return ln(o,t)}})}};qi=new WeakMap,un=new WeakMap,$i=new WeakMap,cn=new WeakMap,Ki=new WeakMap,mn=new WeakMap,pn=new WeakMap,gn=new WeakMap,Gt=new WeakMap,hn=new WeakMap,fn=new WeakMap,bn=new WeakMap,yn=new WeakMap,vn=new WeakMap,kn=new WeakMap,dt=new WeakMap,Cn=new WeakMap,Sn=new WeakMap,Jt=new WeakMap,Zi=new WeakMap,lt=new WeakMap,Xi=new WeakMap,Qi=new WeakMap,Yi=new WeakMap,ut=new WeakMap,ct=new WeakMap,mt=new WeakMap,er=new WeakMap,pt=new WeakMap,gt=new WeakMap,ht=new WeakMap,He=new WeakMap,Pn=new WeakMap,wn=new WeakMap,tr=new WeakMap,ir=new WeakMap,M=new WeakMap;var V=D;function ln(i,e){if(!i.data?.children)throw new Error("Listing response is missing children");return{children:i.data.children.map(r=>new V(r.data,e)),before:i.data.before,after:i.data.after}}async function Qp(i,e){let o=(await Q.query("GetThumbnailV2","81580ce4e23d748c5a59a1618489b559bf4518b6a73af41f345d8d074c8b2ce9",{id:i.id},e)).data?.postInfoById?.thumbnailV2;if(o){if(!o.image)return}else throw new Error("Failed to get thumbnail");return{attribution:o.attribution,image:{url:o.image.url,width:o.image.dimensions.width,height:o.image.dimensions.height},isObfuscatedDefault:o.isObfuscatedDefault,...o.obfuscatedImage&&{obfuscatedImage:{url:o.obfuscatedImage.url,width:o.obfuscatedImage.dimensions.width,height:o.obfuscatedImage.dimensions.height}}}}var Yp=(_=>(_.Custom="CUSTOM",_.Reddit="REDDIT",_.Instagram="INSTAGRAM",_.Twitter="TWITTER",_.Tiktok="TIKTOK",_.Twitch="TWITCH",_.Facebook="FACEBOOK",_.Youtube="YOUTUBE",_.Tumblr="TUMBLR",_.Spotify="SPOTIFY",_.Soundcloud="SOUNDCLOUD",_.Beacons="BEACONS",_.Linktree="LINKTREE",_.Discord="DISCORD",_.Venmo="VENMO",_.CashApp="CASH_APP",_.Patreon="PATREON",_.Kofi="KOFI",_.Paypal="PAYPAL",_.Cameo="CAMEO",_.Onlyfans="ONLYFANS",_.Substack="SUBSTACK",_.Kickstarter="KICKSTARTER",_.Indiegogo="INDIEGOGO",_.BuyMeACoffee="BUY_ME_A_COFFEE",_.Shopify="SHOPIFY",_))(Yp||{}),Fn,rr,xn,In,En,An,Tn,ft,Rn,On,Bn,Be,zt=class zt{constructor(e,t){l(this,Fn);l(this,rr);l(this,xn);l(this,In);l(this,En);l(this,An);l(this,Tn);l(this,ft,new Map);l(this,Rn);l(this,On);l(this,Bn);l(this,Be);K(this),p(e.id,"User ID is missing or undefined"),p(e.name,"Username is missing or undefined"),p(e.createdUtc,"User is missing created date"),a(this,Fn,te(Bs(e.id)?e.id:`t2_${e.id}`)),a(this,rr,e.name),a(this,An,e.over18??!1),a(this,Tn,e.isEmployee??!1);let r=new Date(0);if(r.setUTCSeconds(e.createdUtc),a(this,xn,r),a(this,In,e.linkKarma??0),a(this,En,e.commentKarma??0),e.modPermissions)for(let[s,o]of Object.entries(e.modPermissions))n(this,ft).set(s,cc(o));a(this,Rn,new URL(e.subreddit?.url??"","https://www.reddit.com").toString()),a(this,On,e.subreddit?.url??""),a(this,Bn,e.hasVerifiedEmail??!1),a(this,Be,t)}get id(){return n(this,Fn)}get username(){return n(this,rr)}get createdAt(){return n(this,xn)}get linkKarma(){return n(this,In)}get commentKarma(){return n(this,En)}get nsfw(){return n(this,An)}get isAdmin(){return n(this,Tn)}get modPermissions(){return n(this,ft)}get url(){return n(this,Rn)}get permalink(){return n(this,On)}get hasVerifiedEmail(){return n(this,Bn)}toJSON(){return{id:this.id,username:this.username,createdAt:this.createdAt,linkKarma:this.linkKarma,commentKarma:this.commentKarma,nsfw:this.nsfw,modPermissionsBySubreddit:Object.fromEntries(this.modPermissions)}}async getModPermissionsForSubreddit(e){if(n(this,ft).has(e))return n(this,ft).get(e);let t=await zt.getSubredditUsersByType({subredditName:e,type:"moderators",username:this.username},n(this,Be)).all();if(t.length===0)return[];let r=t[0].modPermissions.get(e)??[];return r.length>0&&n(this,ft).set(e,r),r}getComments(e){return X.getCommentsByUser({username:this.username,...e},n(this,Be))}getPosts(e){return V.getPostsByUser({username:this.username,...e},n(this,Be))}async getUserFlairBySubreddit(e){let t=await ve.getUserFlairBySubreddit({subreddit:e,name:n(this,rr)},n(this,Be));return t.users[0]?dn(t.users[0]):void 0}getSnoovatarUrl(){return zt.getSnoovatarUrl(this.username,n(this,Be))}async getSocialLinks(){let r=await Q.query("GetUserSocialLinks","2aca18ef5f4fc75fb91cdaace3e9aeeae2cb3843b5c26ad511e6f01b8521593a",{name:this.username},n(this,Be));return r.data?.user?.profile?.socialLinks?r.data.user.profile.socialLinks.map(s=>({...s,handle:s.handle??void 0})):[]}static async getById(e,t){let r=await fc(e,t);return r==null?void 0:zt.getByUsername(r,t)}static async getByUsername(e,t){let r=u.redditAPIPlugins.Users;try{let s=await r.UserAbout({username:e},t);if(s.data?.id)return new zt(s.data,t)}catch(s){if(s instanceof Error&&s.message.includes("404 Not Found"))return;throw s}}static async getFromMetadata(e,t){p(t);let r=t?.[e]?.values[0];return r?zt.getById(te(r),t):Promise.resolve(void 0)}static getSubredditUsersByType(e,t){let r=u.redditAPIPlugins.Subreddits;return new W({hasMore:!0,pageSize:e.pageSize,limit:e.limit,after:e.after,before:e.before,fetch:async s=>{let o=await r.AboutWhere({where:e.type,user:e.username,subreddit:e.subredditName,show:"all",...s},t);return tg(o,e.subredditName,t)}})}static async createRelationship(e,t){let r=u.redditAPIPlugins.Users,{type:s,subredditName:o,username:d,permissions:c,...m}=e,y=await r.Friend({type:s,subreddit:o,name:d,permissions:c?Ha(c):void 0,...m},t);if(y.json?.errors?.length)throw new Error(y.json.errors.join(`
|
|
4
|
-
`))}static async removeRelationship(e,t){await u.redditAPIPlugins.Users.Unfriend({type:e.type,subreddit:e.subredditName,name:e.username},t)}static async setModeratorPermissions(e,t,r,s){let d=await u.redditAPIPlugins.Users.SetPermissions({subreddit:t,name:e,type:"moderator",permissions:Ha(r)},s);if(d.json?.errors?.length)throw new Error(d.json.errors.join(`
|
|
5
|
-
`))}static async getSnoovatarUrl(e,t){return(await Q.query("GetSnoovatarUrlByName","c47fd42345af268616d2d8904b56856acdc05cf61d3650380f539ad7d596ac0c",{username:e},t)).data?.redditorInfoByName?.snoovatarIcon?.url}static getOverview(e,t){let r=u.redditAPIPlugins.Users;return new W({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,async fetch(s){let o=await r.UserWhere({username:e.username,where:"overview",...s},t);return eg(o,t)}})}};Fn=new WeakMap,rr=new WeakMap,xn=new WeakMap,In=new WeakMap,En=new WeakMap,An=new WeakMap,Tn=new WeakMap,ft=new WeakMap,Rn=new WeakMap,On=new WeakMap,Bn=new WeakMap,Be=new WeakMap;var C=zt;function eg(i,e){if(!i.data?.children)throw new Error("Listing response is missing children");return{children:i.data.children.map(r=>{if(r.kind==="t3")return new V(r.data,e);if(r.kind==="t1")return new X(r.data,e);throw new Error(`Type ${r.kind} is not supported`)}),before:i.data.before,after:i.data.after}}async function tg(i,e,t){let r=u.redditAPIPlugins.Users;if(!i.data?.children)throw new Error("Listing response is missing children");let s=i.data.children.map(v=>(p(v.data?.id,"User id is still from listing data"),v.data.id)),o=100,d=[];for(let v=0;v<s.length;v+=o)d.push(s.slice(v,v+o));let m=(await Promise.all(d.map(v=>r.UserDataByAccountIds({ids:v.join(",")},t)))).reduce((v,f)=>({...v,...f.users}),{});return{children:i.data.children.map(v=>{let f=v.data?.id;p(f,"User id is missing from listing");let S=m[f];return p(S,"User data is missing from response"),new C({id:f,name:S.name,linkKarma:S.linkKarma,commentKarma:S.commentKarma,createdUtc:S.createdUtc,over18:S.profileOver18,snoovatarSize:[],modPermissions:{[e]:v.data?.modPermissions??[]}},t)}),before:i.data.before,after:i.data.after}}async function fc(i,e){return(await u.redditAPIPlugins.Users.UserDataByAccountIds({ids:i},e))?.users?.[i]?.name}async function xd(i){p(i);let e=i?.[P.Username]?.values[0];if(e)return e;let t=i?.[P.User]?.values[0];if(t)return fc(t,i)}var qt,Mn,nr,sr,Un,Dn,or,Nn,Ln,ar,bt,_n,Hn,$t,yt,vt,je,Kt,We,jn,Wn,Vn,Gn,Jn,zn,qn,kt,Z,Me,bo,yo,H=class H{constructor(e,t){l(this,qt);l(this,Mn);l(this,nr);l(this,sr);l(this,Un);l(this,Dn);l(this,or);l(this,Nn);l(this,Ln);l(this,ar);l(this,bt);l(this,_n);l(this,Hn);l(this,$t);l(this,yt);l(this,vt);l(this,je);l(this,Kt);l(this,We);l(this,jn);l(this,Wn);l(this,Vn);l(this,Gn);l(this,Jn);l(this,zn);l(this,qn);l(this,kt);l(this,Z);var s;K(this),p(e.id,"Comment id is null or undefined"),p(e.body,"Comment body is null or undefined"),p(e.createdUtc,"Comment is missing created date"),p(e.author,"Comment author is null or undefined"),p(e.parentId,"Comment parentId is null or undefined"),p(e.linkId,"Comment linkId is null or undefined"),p(e.permalink,"Comment permalink is null or undefined"),p(e.subreddit,"Comment is missing subreddit name"),p(e.subredditId,"Comment is missing subreddit id"),a(this,qt,Yt(`t1_${e.id}`)),a(this,Mn,e.authorFullname?te(e.authorFullname):void 0),a(this,nr,e.author),a(this,sr,e.body),a(this,Nn,$(e.subredditId)),a(this,Ln,e.subreddit),a(this,Dn,Do(e.parentId)?Yt(e.parentId):de(e.parentId)),a(this,or,de(e.linkId)),a(this,$t,e.edited??!1),a(this,yt,e.locked??!1),a(this,vt,e.removed??!1),a(this,je,e.stickied??!1),a(this,bt,e.approved??!1),a(this,_n,e.approvedAtUtc??0),a(this,Hn,e.bannedAtUtc??0),a(this,Kt,e.spam??!1),a(this,We,e.distinguished),a(this,jn,e.numReports??0),a(this,Wn,e.collapsedBecauseCrowdControl??!1),a(this,Vn,e.score??0),a(this,Gn,e.permalink),a(this,qn,new URL(e.permalink??"","https://www.reddit.com/").toString()),a(this,kt,e.ignoreReports??!1),a(this,Jn,(e.modReports??[]).map(([o])=>o)),a(this,zn,(e.userReports??[]).map(([o])=>o));let r=new Date(0);r.setUTCSeconds(e.createdUtc),a(this,Un,r),a(this,ar,h(s=H,Me,bo).call(s,{postId:n(this,or),commentId:n(this,qt)},t)),a(this,Z,t)}get id(){return n(this,qt)}get authorId(){return n(this,Mn)}get authorName(){return n(this,nr)}get subredditId(){return n(this,Nn)}get subredditName(){return n(this,Ln)}get body(){return n(this,sr)}get createdAt(){return n(this,Un)}get parentId(){return n(this,Dn)}get postId(){return n(this,or)}get replies(){return n(this,ar)}get distinguishedBy(){return n(this,We)}get locked(){return n(this,yt)}get stickied(){return n(this,je)}get removed(){return n(this,vt)}get approved(){return n(this,bt)}get approvedAtUtc(){return n(this,_n)}get bannedAtUtc(){return n(this,Hn)}get spam(){return n(this,Kt)}get edited(){return n(this,$t)}get numReports(){return n(this,jn)}get collapsedBecauseCrowdControl(){return n(this,Wn)}get score(){return n(this,Vn)}get permalink(){return n(this,Gn)}get userReportReasons(){return n(this,zn)}get modReportReasons(){return n(this,Jn)}get url(){return n(this,qn)}get ignoringReports(){return n(this,kt)}toJSON(){return{id:this.id,authorName:this.authorName,subredditId:this.subredditId,subredditName:this.subredditName,body:this.body,createdAt:this.createdAt,parentId:this.parentId,postId:this.postId,replies:this.replies,approved:this.approved,locked:this.locked,removed:this.removed,stickied:this.stickied,spam:this.spam,edited:this.edited,distinguishedBy:this.distinguishedBy,numReports:this.numReports,collapsedBecauseCrowdControl:this.collapsedBecauseCrowdControl,score:this.score,permalink:this.permalink,modReportReasons:this.modReportReasons,userReportReasons:this.userReportReasons,url:this.url,ignoringReports:this.ignoringReports}}isLocked(){return n(this,yt)}isApproved(){return n(this,bt)}isRemoved(){return n(this,vt)}isSpam(){return n(this,Kt)}isStickied(){return n(this,je)}isDistinguished(){return!!n(this,We)}isEdited(){return n(this,$t)}isIgnoringReports(){return n(this,kt)}async delete(){return H.delete(this.id,n(this,Z))}async edit(e){let t=await H.edit({id:this.id,...e},n(this,Z));return a(this,sr,t.body),a(this,$t,t.edited),this}async approve(){await H.approve(this.id,n(this,Z)),a(this,bt,!0),a(this,vt,!1)}async remove(e=!1){await H.remove(this.id,e,n(this,Z)),a(this,vt,!0),a(this,Kt,e),a(this,bt,!1)}async lock(){await H.lock(this.id,n(this,Z)),a(this,yt,!0)}async unlock(){await H.unlock(this.id,n(this,Z)),a(this,yt,!1)}async reply(e){return H.submit({id:this.id,...e},n(this,Z))}async getAuthor(){return C.getByUsername(n(this,nr),n(this,Z))}async distinguish(e=!1){let{distinguishedBy:t,stickied:r}=await H.distinguish(this.id,e,!1,n(this,Z));a(this,We,t),a(this,je,r)}async distinguishAsAdmin(e=!1){let{distinguishedBy:t,stickied:r}=await H.distinguish(this.id,e,!0,n(this,Z));a(this,We,t),a(this,je,r)}async undistinguish(){let{distinguishedBy:e,stickied:t}=await H.undistinguish(this.id,n(this,Z));a(this,We,e),a(this,je,t)}async ignoreReports(){await H.ignoreReports(this.id,n(this,Z)),a(this,kt,!0)}async unignoreReports(){await H.unignoreReports(this.id,n(this,Z)),a(this,kt,!1)}addRemovalNote(e){return ye.addRemovalNote({itemIds:[n(this,qt)],...e},n(this,Z))}static async getById(e,t){let r=u.redditAPIPlugins.LinksAndComments,s=Ve(e)?e:`t1_${e}`,o=await r.Info({subreddits:[],thingIds:[s]},t);if(!o.data?.children?.[0]?.data)throw new Error("not found");return new H(o.data.children[0].data,t)}static getComments(e,t){var d;let{postId:r,commentId:s,...o}=e;return h(d=H,Me,bo).call(d,{postId:de(r),commentId:s?Yt(s):void 0,...o},t)}static async edit(e,t){let r=u.redditAPIPlugins.LinksAndComments,{id:s}=e,o;"richtext"in e&&(o=Mi(e.richtext));let d=await r.EditUserText({thingId:s,text:"text"in e?e.text:"",richtextJson:o},t);if(d.json?.errors?.length)throw new Error("Failed to edit comment");let c=d.json?.data?.things?.[0]?.data;return p(c),new H(c,t)}static async delete(e,t){await u.redditAPIPlugins.LinksAndComments.Del({id:e},t)}static async approve(e,t){await u.redditAPIPlugins.Moderation.Approve({id:e},t)}static async remove(e,t=!1,r){await u.redditAPIPlugins.Moderation.Remove({id:e,spam:t},r)}static async lock(e,t){await u.redditAPIPlugins.LinksAndComments.Lock({id:e},t)}static async unlock(e,t){await u.redditAPIPlugins.LinksAndComments.Unlock({id:e},t)}static async submit(e,t){let r=u.redditAPIPlugins.LinksAndComments,{id:s}=e,o;"richtext"in e&&(o=Mi(e.richtext));let d=await r.Comment({thingId:s,text:"text"in e?e.text:"",richtextJson:o},t);if(d.json?.errors?.length)throw new Error("failed to reply to comment");let c=d.json?.data?.things?.[0]?.data;return p(c),new H(c,t)}static async distinguish(e,t,r,s){let c=(await u.redditAPIPlugins.Moderation.Distinguish({id:e,how:r?"admin":"yes",sticky:t},s)).json?.data?.things?.[0]?.data;return p(c),{distinguishedBy:c.distinguished,stickied:!!c.stickied}}static async undistinguish(e,t){let o=(await u.redditAPIPlugins.Moderation.Distinguish({id:e,how:"no",sticky:!1},t)).json?.data?.things?.[0]?.data;return p(o),{distinguishedBy:o.distinguished,stickied:!!o.stickied}}static getCommentsByUser(e,t){let r=u.redditAPIPlugins.Users;return new W({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,async fetch(s){let o=await r.UserWhere({username:e.username,where:"comments",...s},t);return p(o.data,"Failed to get comments for user"),{children:o.data.children?.map(c=>new H(c.data,t))||[],before:o.data.before,after:o.data.after}}})}static async ignoreReports(e,t){await u.redditAPIPlugins.Moderation.IgnoreReports({id:e},t)}static async unignoreReports(e,t){await u.redditAPIPlugins.Moderation.UnignoreReports({id:e},t)}};qt=new WeakMap,Mn=new WeakMap,nr=new WeakMap,sr=new WeakMap,Un=new WeakMap,Dn=new WeakMap,or=new WeakMap,Nn=new WeakMap,Ln=new WeakMap,ar=new WeakMap,bt=new WeakMap,_n=new WeakMap,Hn=new WeakMap,$t=new WeakMap,yt=new WeakMap,vt=new WeakMap,je=new WeakMap,Kt=new WeakMap,We=new WeakMap,jn=new WeakMap,Wn=new WeakMap,Vn=new WeakMap,Gn=new WeakMap,Jn=new WeakMap,zn=new WeakMap,qn=new WeakMap,kt=new WeakMap,Z=new WeakMap,Me=new WeakSet,bo=function(e,t,r=0){return new W({limit:e.limit,pageSize:e.pageSize,fetch:async s=>{var S,b;let o=s.limit,d=u.redditAPIPlugins.Listings,c=u.redditAPIPlugins.LinksAndComments,m=e.commentId;if(s.more)if(s.more.children.length){let O=s.more;(!o||o>100)&&(o=100);let L=O.children.splice(0,o),B=await c.MoreChildren({linkId:e.postId,children:L,sort:e.sort},t);if(!B.json?.data?.things?.length)return{children:[]};let{children:Y}=h(S=H,Me,yo).call(S,B.json.data.things,e.postId,e,t);return{children:Y,more:O.children.length?O:void 0}}else m=s.more.parentId,r=r+s.more.depth;let v=(await d.Comments({article:e.postId.substring(3),comment:m?.substring(3),limit:o,depth:e.depth,sort:e.sort},t)).listings?.[1]?.data?.children??[],f=v[0];return m&&f?.data?.replyList?.data&&(v=f.data.replyList.data.children),h(b=H,Me,yo).call(b,v,m??e.postId,e,t,r)}})},yo=function(e,t,r,s,o=0){var y,v;let d=[],c,m={};for(let f of e){if(!f.data||(f.data.depth!=null&&(f.data.depth=f.data.depth+o),f.data.depth!=null&&r.depth!=null&&f.data.depth>=r.depth))continue;let S=f.data.parentId?m[f.data.parentId]:void 0;if(f.kind==="t1"){if(f.data.name===t)continue;let b=new H(f.data,s);if(m[b.id]=b,a(b,ar,h(y=H,Me,bo).call(y,{...r,postId:b.postId,commentId:b.id},s,o)),"replyList"in f.data&&f.data.replyList?.data){let{children:O,more:L}=h(v=H,Me,yo).call(v,f.data.replyList.data.children,b.id,r,s,o);O.length&&b.replies.children.push(...O),L&&b.replies.setMore(L)}b.replies.preventInitialFetch(),S?S.replies.children.push(b):d.push(b)}else if(f.kind==="more"&&f.data.parentId&&f.data.depth!=null){let b={parentId:Do(f.data.parentId)?Yt(f.data.parentId):de(f.data.parentId),children:f.data.children??[],depth:f.data.depth};S?S.replies.setMore(b):b.parentId===t&&(c=b)}}return{children:d,more:c}},l(H,Me);var X=H;function Ns(i,e){let t=u.redditAPIPlugins.Moderation;return new W({hasMore:!0,after:i.after,before:i.before,limit:i.limit,pageSize:i.pageSize,fetch:async r=>{let s=await t.AboutLog({subreddit:i.subredditName,mod:i.moderatorUsernames?i.moderatorUsernames.join(","):void 0,type:i.type,...r},e);return ig(s)}})}function ig(i){if(!i.data?.children)throw new Error("AboutLogResponse is missing children");return{children:i.data.children.map(t=>{if(!t.data)throw new Error("ModAction from AboutLogResponse is missing or invalid");let{id:r,mod:s,modId36:o,createdUtc:d,subreddit:c,subredditNamePrefixed:m,action:y,srId36:v,description:f,details:S,targetAuthor:b,targetBody:O,targetFullname:L,targetPermalink:B,targetTitle:Y}=t.data;p(r,"ModAction from AboutLogResponse is missing id"),p(s,"ModAction from AboutLogResponse is missing mod"),p(o,"ModAction from AboutLogResponse is missing modId36"),p(d,"ModAction from AboutLogResponse is missing createdUtc"),p(c,"ModAction from AboutLogResponse is missing subreddit"),p(m,"ModAction from AboutLogResponse is missing subredditNamePrefixed"),p(y,"ModAction from AboutLogResponse is missing action"),p(v,"ModAction from AboutLogResponse is missing srId36");let Xt=new Date(0);return Xt.setUTCSeconds(d),{id:r,type:y,moderatorName:s,moderatorId:`t2_${o}`,createdAt:Xt,subredditName:c,subredditId:`t5_${v}`,description:f,details:S,target:L?{id:L,author:b,body:O,permalink:B,title:Y}:void 0}}),after:i.data.after,before:i.data.before}}import"@devvit/protos";var rg=(d=>(d.New="New",d.InProgress="InProgress",d.Archived="Archived",d.Appeals="Appeals",d.JoinRequests="JoinRequests",d.Filtered="Filtered",d))(rg||{}),ng={0:"New",1:"InProgress",2:"Archived",3:"Appeals",4:"JoinRequests",5:"Filtered"},sg=(b=>(b.Highlighted="Highlighted",b.Unhighlighted="Unhighlighted",b.Archived="Archived",b.Unarchived="Unarchived",b.ReportedToAdmins="ReportedToAdmins",b.Muted="Muted",b.Unmuted="Unmuted",b.Banned="Banned",b.Unbanned="Unbanned",b.Approved="Approved",b.Disapproved="Disapproved",b.Filtered="Filtered",b.Unfiltered="Unfiltered",b))(sg||{}),og={0:"Highlighted",1:"Unhighlighted",2:"Archived",3:"Unarchived",4:"ReportedToAdmins",5:"Muted",6:"Unmuted",7:"Banned",8:"Unbanned",9:"Approved",10:"Disapproved",11:"Filtered",12:"Unfiltered"},N,G,re,bc,yc,Ls=class{constructor(e){l(this,G);l(this,N);this.notificationSubjectPrefix="[notification]";a(this,N,e)}async bulkReadConversations(e,t){let r=u.redditAPIPlugins.NewModmail,{conversationIds:s}=await r.BulkReadConversations({entity:e.join(","),state:t},n(this,N));return s}async getConversations(e){let r=await u.redditAPIPlugins.NewModmail.GetConversations({after:e.after,entity:e.subreddits?e.subreddits.join(","):void 0,limit:e.limit,sort:e.sort,state:e.state},n(this,N)),s={};for(let o in r.conversations)s[o]=h(this,G,re).call(this,{protoConversation:r.conversations[o],protoMessages:r.messages,protoModActions:{}});return{conversations:s,viewerId:r.viewerId,conversationIds:r.conversationIds}}async getConversation(e){let r=await u.redditAPIPlugins.NewModmail.GetConversation({...e,markRead:!!e.markRead},n(this,N));return{participantSubreddit:r.participantSubreddit,conversation:h(this,G,re).call(this,{protoConversation:r.conversation,protoMessages:r.messages,protoModActions:r.modActions}),user:r.user}}async getSubreddits(){let e=u.redditAPIPlugins.NewModmail,{subreddits:t}=await e.Subreddits({},n(this,N));return t}async createConversation(e){let r=await u.redditAPIPlugins.NewModmail.CreateConversation({body:e.body,isAuthorHidden:e.isAuthorHidden??!1,srName:e.subredditName,subject:e.subject,to:e.to?e.to:void 0},n(this,N));return{conversation:h(this,G,re).call(this,{protoConversation:r.conversation,protoMessages:r.messages,protoModActions:r.modActions}),user:r.user}}async createModDiscussionConversation(e){return za({subject:e.subject,bodyMarkdown:e.bodyMarkdown,subredditId:$(e.subredditId),isInternal:!0,participantType:"MODERATOR",conversationType:"INTERNAL"},n(this,N))}async createModInboxConversation(e){return za({subject:e.subject,bodyMarkdown:e.bodyMarkdown,subredditId:$(e.subredditId),isInternal:!1,participantType:"PARTICIPANT_USER",conversationType:"SR_USER"},n(this,N))}async createModNotification(e){let t=e.subject;return e.subject.startsWith(this.notificationSubjectPrefix)||(t=`${this.notificationSubjectPrefix} ${e.subject}`),za({subject:t,bodyMarkdown:e.bodyMarkdown,subredditId:$(e.subredditId),isInternal:!1,participantType:"PARTICIPANT_USER",conversationType:"SR_USER"},n(this,N))}async reply(e){let r=await u.redditAPIPlugins.NewModmail.CreateConversationMessage({body:e.body,conversationId:e.conversationId,isAuthorHidden:e.isAuthorHidden??!1,isInternal:e.isInternal??!1},n(this,N));return{conversation:h(this,G,re).call(this,{protoConversation:r.conversation,protoMessages:r.messages,protoModActions:{}}),user:r.user}}async highlightConversation(e){let r=await u.redditAPIPlugins.NewModmail.HighlightConversation({conversationId:e},n(this,N));return{conversation:h(this,G,re).call(this,{protoConversation:r.conversation,protoMessages:r.messages,protoModActions:r.modActions})}}async unhighlightConversation(e){let r=await u.redditAPIPlugins.NewModmail.UnhighlightConversation({conversationId:e},n(this,N));return{conversation:h(this,G,re).call(this,{protoConversation:r.conversation,protoMessages:r.messages,protoModActions:r.modActions})}}async archiveConversation(e){let r=await u.redditAPIPlugins.NewModmail.ArchiveConversation({conversationId:e},n(this,N));return{conversation:h(this,G,re).call(this,{protoConversation:r.conversation,protoMessages:r.messages,protoModActions:r.modActions})}}async unarchiveConversation(e){let r=await u.redditAPIPlugins.NewModmail.UnarchiveConversation({conversationId:e},n(this,N));return{conversation:h(this,G,re).call(this,{protoConversation:r.conversation,protoMessages:r.messages,protoModActions:r.modActions})}}async muteConversation(e){let r=await u.redditAPIPlugins.NewModmail.MuteConversation({conversationId:e.conversationId,numHours:e.numHours},n(this,N));return{conversation:h(this,G,re).call(this,{protoConversation:r.conversations,protoMessages:r.messages,protoModActions:r.modActions}),user:r.user}}async unmuteConversation(e){let r=await u.redditAPIPlugins.NewModmail.UnmuteConversation({conversationId:e},n(this,N));return{conversation:h(this,G,re).call(this,{protoConversation:r.conversations,protoMessages:r.messages,protoModActions:r.modActions}),user:r.user}}async readConversations(e){await u.redditAPIPlugins.NewModmail.Read({conversationIds:e.join(",")},n(this,N))}async unreadConversations(e){await u.redditAPIPlugins.NewModmail.Unread({conversationIds:e.join(",")},n(this,N))}async approveConversation(e){let r=await u.redditAPIPlugins.NewModmail.ApproveConversation({conversationId:e},n(this,N));return{conversation:h(this,G,re).call(this,{protoConversation:r.conversations,protoMessages:r.messages,protoModActions:r.modActions}),user:r.user}}async disapproveConversation(e){let r=await u.redditAPIPlugins.NewModmail.DisapproveConversation({conversationId:e},n(this,N));return{conversation:h(this,G,re).call(this,{protoConversation:r.conversations,protoMessages:r.messages,protoModActions:r.modActions}),user:r.user}}async tempBanConversation(e){let r=await u.redditAPIPlugins.NewModmail.TempBan({...e},n(this,N));return{conversation:h(this,G,re).call(this,{protoConversation:r.conversations,protoMessages:r.messages,protoModActions:r.modActions}),user:r.user}}async unbanConversation(e){let r=await u.redditAPIPlugins.NewModmail.Unban({conversationId:e},n(this,N));return{conversation:h(this,G,re).call(this,{protoConversation:r.conversations,protoMessages:r.messages,protoModActions:r.modActions}),user:r.user}}async getUnreadCount(){return await u.redditAPIPlugins.NewModmail.UnreadCount({},n(this,N))}async getUserConversations(e){return await u.redditAPIPlugins.NewModmail.UserConversations({conversationId:e},n(this,N))}};N=new WeakMap,G=new WeakSet,re=function({protoConversation:e,protoMessages:t,protoModActions:r}){return{...e,state:ng[e.state],messages:h(this,G,bc).call(this,e,t),modActions:h(this,G,yc).call(this,e,r)}},bc=function(e,t){let r={},s=e.objIds.filter(o=>o.key==="messages").map(({id:o})=>o);for(let o of s){let d=t[o];d&&(r[o]=d)}return r},yc=function(e,t){let r={},s=e.objIds.filter(o=>o.key==="modActions").map(({id:o})=>o);for(let o of s){let d=t[o];d&&(r[o]={...d,actionType:og[d.actionTypeId]})}return r};async function za(i,e){let t=e[P.AppUser]?.values[0],o=await Q.query("CreateModmailConversation","5f9ae20b0c7bdffcafb80241728a72e67cd4239bc09f67284b79d4aa706ee0e5",{subject:i.subject,bodyMarkdown:i.bodyMarkdown,subredditId:i.subredditId,authorId:t,isInternal:i.isInternal,participantType:i.participantType,conversationType:i.conversationType},e);if(o.data?.createModmailConversationV2?.ok)return o.data?.createModmailConversationV2?.conversationId;throw new Error("modmail conversation creation failed; ${response.data?.createModmailConversationV2?.errors[0].message}")}var dr,lr,$n,Kn,Zn,Xn,qa=class qa{constructor(e,t){l(this,dr);l(this,lr);l(this,$n);l(this,Kn);l(this,Zn);l(this,Xn);if(K(this),p(e.id,"PrivateMessage: Invalid data, no id"),p(e.name,"PrivateMessage: Invalid data, no name"),p(e.created,"PrivateMessage: Invalid data, no created date"),a(this,dr,he(e.name)),e.author!=null)a(this,lr,{type:"user",username:e.author,id:e.authorFullname?te(e.authorFullname):void 0});else if(e.subreddit!=null)a(this,lr,{type:"subreddit",name:e.subreddit,id:e.subredditId?$(e.subredditId):void 0});else throw new Error("PrivateMessage: Invalid data, no author or subreddit");a(this,$n,e.body??""),a(this,Kn,e.bodyHtml??"");let r=new Date(0);r.setUTCSeconds(e.createdUtc),a(this,Zn,r),a(this,Xn,t)}static async getMessages(e,t){let r=u.redditAPIPlugins.PrivateMessages;return new W({...e,fetch:async s=>{let o=await r.MessageWhere({...s,where:e.type??"inbox"},t);return{after:o.data?.after,before:o.data?.before,children:o.data?.children?.map(d=>new qa(d.data,t)).filter(Boolean)||[]}}})}static async send({to:e,subject:t,text:r},s){await u.redditAPIPlugins.PrivateMessages.Compose({to:e,subject:t,text:r,fromSr:""},s)}static async sendAsSubreddit({to:e,fromSubredditName:t,subject:r,text:s},o){await u.redditAPIPlugins.PrivateMessages.Compose({to:e,fromSr:t,subject:r,text:s},o)}static async markAllAsRead(e){await u.redditAPIPlugins.PrivateMessages.ReadAllMessages({filterTypes:""},e)}get id(){return n(this,dr)}get from(){return n(this,lr)}get body(){return n(this,$n)}get bodyHtml(){return n(this,Kn)}get created(){return n(this,Zn)}async markAsRead(){await u.redditAPIPlugins.PrivateMessages.ReadMessage({id:n(this,dr)},n(this,Xn))}};dr=new WeakMap,lr=new WeakMap,$n=new WeakMap,Kn=new WeakMap,Zn=new WeakMap,Xn=new WeakMap;var wt=qa;var Id=(o=>(o.Reports="reports",o.Spam="spam",o.Modqueue="modqueue",o.Unmoderated="unmoderated",o.Edited="edited",o))(Id||{}),vc=class{},kc=class{},Cc=class{},Sc=class{},ur,F,Qn,Yn,es,ts,is,rs,ns,ss,os,cr,A,Ie=class Ie{constructor(e,t){l(this,ur);l(this,F);l(this,Qn);l(this,Yn);l(this,es);l(this,ts);l(this,is);l(this,rs);l(this,ns);l(this,ss);l(this,os);l(this,cr);l(this,A);K(this),p(e.id,"Subreddit id is missing or undefined"),p(e.displayName,"Subreddit name is missing or undefined"),a(this,ur,$(`t5_${e.id}`)),a(this,F,e.displayName),p(e.createdUtc,"Subreddit is missing created date");let r=new Date(0);r.setUTCSeconds(e.createdUtc),a(this,Qn,r),a(this,Yn,ag(e.subredditType)),a(this,es,e.title),a(this,ts,e.description),p(e.lang,"Subreddit is missing language"),a(this,is,e.lang),a(this,rs,e.subscribers??0),a(this,ns,e.activeUserCount??0),a(this,ss,e.over18??!1),a(this,cr,e.url??""),a(this,os,{acceptFollowers:e.acceptFollowers??!1,allOriginalContent:e.allOriginalContent??!1,allowChatPostCreation:e.allowChatPostCreation??!1,allowDiscovery:e.allowDiscovery??!1,allowGalleries:e.allowGalleries??!1,allowImages:e.allowImages??!1,allowPolls:e.allowPolls??!1,allowPredictionContributors:e.allowPredictionContributors??!1,allowPredictions:e.allowPredictions??!1,allowPredictionsTournament:e.allowPredictionsTournament??!1,allowTalks:e.allowTalks??!1,allowVideoGifs:e.allowVideogifs??!1,allowVideos:e.allowVideos??!1,chatPostEnabled:e.isChatPostFeatureEnabled??!1,collectionsEnabled:e.collectionsEnabled??!1,crosspostable:e.isCrosspostableSubreddit??!1,emojisEnabled:e.emojisEnabled??!1,eventPostsEnabled:e.eventPostsEnabled??!1,linkFlairEnabled:e.linkFlairEnabled??!1,originalContentTagEnabled:e.originalContentTagEnabled??!1,restrictCommenting:e.restrictCommenting??!1,restrictPosting:e.restrictPosting??!1,shouldArchivePosts:e.shouldArchivePosts??!1,spoilersEnabled:e.spoilersEnabled??!1,wikiEnabled:e.wikiEnabled??!1,allowedPostType:dg(e.submissionType),allowedMediaInComments:(e.allowedMediaInComments??[]).map(lg),bannerBackgroundColor:e.bannerBackgroundColor,bannerBackgroundImage:e.bannerBackgroundImage,bannerImage:e.bannerImg,communityIcon:e.communityIcon,headerTitle:e.headerTitle,keyColor:e.keyColor,mobileBannerImage:e.mobileBannerImage,primaryColor:e.primaryColor,userFlairs:{enabled:e.userFlairEnabledInSr??!1,usersCanAssign:e.canAssignUserFlair??!1,userFlairBackgroundColor:e.userFlairBackgroundColor,userFlairTextColor:e.userFlairTextColor},postFlairs:{enabled:e.linkFlairEnabled??!1,usersCanAssign:e.canAssignLinkFlair??!1},url:new URL(n(this,cr),"https://www.reddit.com").toString()}),a(this,A,t)}get id(){return n(this,ur)}get name(){return n(this,F)}get createdAt(){return n(this,Qn)}get type(){return n(this,Yn)}get title(){return n(this,es)}get description(){return n(this,ts)}get language(){return n(this,is)}get numberOfSubscribers(){return n(this,rs)}get numberOfActiveUsers(){return n(this,ns)}get nsfw(){return n(this,ss)}get settings(){return n(this,os)}get userFlairsEnabled(){return this.settings.userFlairs.enabled}get postFlairsEnabled(){return this.settings.postFlairs.enabled}get usersCanAssignUserFlairs(){return this.settings.userFlairs.usersCanAssign}get usersCanAssignPostFlairs(){return this.settings.postFlairs.usersCanAssign}get url(){return this.settings.url}get permalink(){return n(this,cr)}toJSON(){return{id:this.id,name:this.name,createdAt:this.createdAt,type:this.type,title:this.title,description:this.description,language:this.language,nsfw:this.nsfw,numberOfSubscribers:this.numberOfSubscribers,numberOfActiveUsers:this.numberOfActiveUsers,settings:this.settings}}async submitPost(e){let t={...e,subredditName:n(this,F)};return V.submit(t,n(this,A))}getControversialPosts(e={}){if(!n(this,F))throw new Error("subreddit missing displayName - it might not have been fetched");return V.getControversialPosts({...e,subredditName:n(this,F)},n(this,A))}getTopPosts(e={}){if(!n(this,F))throw new Error("subreddit missing displayName - it might not have been fetched");return V.getTopPosts({...e,subredditName:n(this,F)},n(this,A))}getApprovedUsers(e={}){return C.getSubredditUsersByType({type:"contributors",subredditName:n(this,F),...e},n(this,A))}approveUser(e){return C.createRelationship({username:e,subredditName:n(this,F),type:"contributor"},n(this,A))}removeUser(e){return C.removeRelationship({username:e,subredditName:n(this,F),type:"contributor"},n(this,A))}getWikiContributors(e={}){return C.getSubredditUsersByType({type:"wikicontributors",subredditName:n(this,F),...e},n(this,A))}addWikiContributor(e){return C.createRelationship({username:e,subredditName:n(this,F),type:"wikicontributor"},n(this,A))}removeWikiContributor(e){return C.removeRelationship({username:e,subredditName:n(this,F),type:"wikicontributor"},n(this,A))}getBannedUsers(e={}){return C.getSubredditUsersByType({type:"banned",subredditName:n(this,F),...e},n(this,A))}banUser(e){return C.createRelationship({username:e.username,subredditName:n(this,F),type:"banned",banReason:e.reason,banMessage:e.message,note:e.note,duration:e.duration,banContext:e.context},n(this,A))}unbanUser(e){return C.removeRelationship({username:e,subredditName:n(this,F),type:"banned"},n(this,A))}getBannedWikiContributors(e={}){return C.getSubredditUsersByType({type:"wikibanned",subredditName:n(this,F),...e},n(this,A))}banWikiContributor(e){return C.createRelationship({username:e.username,subredditName:n(this,F),type:"wikibanned",banReason:e.reason,note:e.note,duration:e.duration},n(this,A))}unbanWikiContributor(e){return C.removeRelationship({username:e,subredditName:n(this,F),type:"wikibanned"},n(this,A))}getModerators(e={}){return C.getSubredditUsersByType({type:"moderators",subredditName:n(this,F),...e},n(this,A))}inviteModerator(e,t){return C.createRelationship({type:"moderator_invite",subredditName:n(this,F),username:e,permissions:t??[]},n(this,A))}revokeModeratorInvite(e){return C.removeRelationship({username:e,subredditName:n(this,F),type:"moderator_invite"},n(this,A))}removeModerator(e){return C.removeRelationship({type:"moderator",subredditName:n(this,F),username:e},n(this,A))}setModeratorPermissions(e,t){return C.setModeratorPermissions(e,n(this,F),t,n(this,A))}getMutedUsers(e={}){return C.getSubredditUsersByType({type:"muted",subredditName:n(this,F),...e},n(this,A))}muteUser(e,t){return C.createRelationship({username:e,subredditName:n(this,F),type:"muted",note:t},n(this,A))}unmuteUser(e){return C.removeRelationship({username:e,subredditName:n(this,F),type:"muted"},n(this,A))}getModerationLog(e){return Ns({subredditName:n(this,F),...e},n(this,A))}getUserFlairTemplates(){return ne.getUserFlairTemplates(n(this,F),n(this,A))}getPostFlairTemplates(){return ne.getPostFlairTemplates(n(this,F),n(this,A))}createPostFlairTemplate(e){return ne.createPostFlairTemplate({subredditName:n(this,F),...e},n(this,A))}createUserFlairTemplate(e){return ne.createUserFlairTemplate({subredditName:n(this,F),...e},n(this,A))}async getUserFlair(e){if(e?.usernames!==void 0)return{users:await Promise.all(e.usernames.map(async r=>{let s=await ve.getUserFlairBySubreddit({subreddit:n(this,F),name:r},n(this,A));return dn(s.users[0])}))};{let t=await ve.getUserFlairBySubreddit({...e,subreddit:n(this,F)},n(this,A));return{next:t.next,prev:t.prev,users:t.users.map(r=>dn(r))}}}getModQueue(e={type:"all"}){return Ie.aboutLocation({...e,location:"modqueue",subreddit:n(this,F)},n(this,A))}getReports(e={type:"all"}){return Ie.aboutLocation({...e,location:"reports",subreddit:n(this,F)},n(this,A))}getSpam(e={type:"all"}){return Ie.aboutLocation({...e,location:"spam",subreddit:n(this,F)},n(this,A))}getUnmoderated(e={type:"all"}){return Ie.aboutLocation({...e,location:"unmoderated",subreddit:n(this,F)},n(this,A))}getEdited(e={type:"all"}){return Ie.aboutLocation({...e,location:"edited",subreddit:n(this,F)},n(this,A))}static aboutLocation(e,t){let r=u.redditAPIPlugins.Moderation,s;switch(e.type){case"post":s="links";break;case"comment":s="comments";break;default:s=void 0}return new W({...e,fetch:async o=>{let d=await r.AboutLocation({...o,...e,only:s},t);return Pc(d,t)}})}getCommentsAndPostsByIds(e){let t=u.redditAPIPlugins.LinksAndComments;return new W({fetch:async()=>{let r=await t.Info({thingIds:e,subreddits:[n(this,ur)]},n(this,A));return Pc(r,n(this,A))}})}static async addRemovalReason(e,t,r,s){return(await u.redditAPIPlugins.Subreddits.SubredditAddRemovalReason({title:t,message:r,subreddit:e},s)).id}static async getRemovalReasons(e,t){let s=await u.redditAPIPlugins.Subreddits.SubredditGetRemovalReasons({subreddit:e},t);return s.order.map(o=>({...s.data[o]}))}static async getFromMetadata(e){p(e);let t=e?.[P.SubredditName]?.values[0];if(t)return Ie.getByName(t,e);let r=e?.[P.Subreddit]?.values[0];return p(r),Ie.getById($(r),e)}static async getById(e,t){let r=await Vo(e,t);if(r)return Ie.getByName(r,t)}static async getByName(e,t){let s=await u.redditAPIPlugins.Subreddits.SubredditAbout({subreddit:e},t);if(!s?.data)throw new Error("not found");return new Ie(s.data,t)}};ur=new WeakMap,F=new WeakMap,Qn=new WeakMap,Yn=new WeakMap,es=new WeakMap,ts=new WeakMap,is=new WeakMap,rs=new WeakMap,ns=new WeakMap,ss=new WeakMap,os=new WeakMap,cr=new WeakMap,A=new WeakMap;var le=Ie;async function Ed(i,e){let o=(await Q.query("GetSubredditInfoById","315a9b75c22a017d526afdf2d274616946156451aacfd56dfb91e7ad3f7a2fde",{id:i},e)).data?.subredditInfoById;if(!o)throw new Error("subreddit info not found");return o}async function Ad(i,e){let o=(await Q.query("GetSubredditInfoByName","4aa69726c7e3f5d33ab2bee22b3d74fce645824fddd5ea3ec6dfe30bdb4295cb",{name:i},e)).data?.subredditInfoByName;if(!o)throw new Error("subreddit info not found");return o}async function Td(i,e){let o=(await Q.query("GetSubredditLeaderboard","18ead70c46b6446d45ecd8b679b16d9a929a933d6ef25d8262a459cb18b72848",{id:i},e)).data?.subredditInfoById?.leaderboard;if(!o)throw new Error("subreddit leaderboard not found");if(!o.summary)throw new Error("subreddit leaderboard summary not found");return{id:o.id,summary:o.summary}}async function Rd(i,e){let o=(await Q.query("GetSubredditStyles","d491d17ea8858f563ea578b26b9595d64adecf4bf34557d567c7e53c470f5f22",{id:i},e)).data?.subredditInfoById?.styles;if(!o)throw new Error("subreddit styles not found");return o}function ag(i){if(i==="public"||i==="private"||i==="restricted"||i==="employees_only"||i==="gold_only"||i==="gold_restricted"||i==="archived"||i==="user")return i;throw new Error(`invalid subreddit type: ${i}`)}function dg(i){if(i==="any"||i==="link"||i==="self")return i;throw new Error(`invalid allowed post type: ${i}`)}function lg(i){if(i==="animated"||i==="giphy"||i==="static"||i==="expression")return i;throw new Error(`invalid comment media type: ${i}`)}function Pc(i,e){let r=(i.data?.children??[]).map(d=>{let c=s(d);if(c!=null)return c;let m=o(d);return m??null}).filter(Boolean);return{after:i.data?.after,before:i.data?.before,children:r};function s(d){try{return new V(d.data,e)}catch{return null}}function o(d){try{return new X(d.data,e)}catch{return null}}}async function Vo(i,e){return(await u.redditAPIPlugins.LinksAndComments.Info({thingIds:[i],subreddits:[]},e)).data?.children[0]?.data?.displayName}async function Od(i,e){return wc("GetVaultContactByAddress","3e2f7966a5c120e64fd2795d06a46595c52d988185be98d3ed71c3f81ae80d2e",{provider:"ethereum",address:i},e)}async function Bd(i,e){return wc("GetVaultContactByUserId","a854ddc19d0e22c4f36ed917fdbd568f299f3571427e393aee5e2972080fffe9",{provider:"ethereum",userId:i},e)}async function wc(i,e,t,r){let o=(await Q.query(i,e,t,r))?.data?.vault?.contact;return{provider:o?.provider,userId:te(o?.userId),address:o?.address,createdAt:o?.createdAt,isActive:o?.isActive}}import{CommunityListWidget_CommunityData as ug,GetWidgetsResponse_WidgetItem as ae}from"@devvit/protos";var as,ds,ls,us,Ka=class Ka{constructor(e,t,r){l(this,as);l(this,ds);l(this,ls);l(this,us);K(this),a(this,as,e.id),a(this,ds,e.shortName),a(this,ls,t),a(this,us,r)}get id(){return n(this,as)}get name(){return n(this,ds)}get subredditName(){return n(this,ls)}toJSON(){return{id:this.id,name:this.name,subredditName:this.subredditName}}delete(){return Ka.delete(this.subredditName,this.id,n(this,us))}static async getWidgets(e,t){let s=await u.redditAPIPlugins.Widgets.GetWidgets({subreddit:e},t);p(s.layout,"Failed to load widgets for subreddit");let o=s.items,d=[];for(let c of s.layout.sidebar?.order??[]){let m=o[c];switch(m?.kind){case"image":d.push(new vo(m,e,t));break;case"calendar":d.push(new ko(m,e,t));break;case"textarea":d.push(new Co(m,e,t));break;case"button":d.push(new So(m,e,t));break;case"community-list":d.push(new Po(m,e,t));break;case"post-flair":d.push(new wo(m,e,t));break;case"custom":d.push(new Fo(m,e,t));break;case"subreddit-rules":{let y=await u.redditAPIPlugins.Subreddits.SubredditAboutRules({subreddit:e},t);d.push(new $a(y,m,e,t));break}default:throw new Error(`Unknown widget type: ${m.kind}`)}}return d}static async delete(e,t,r){await u.redditAPIPlugins.Widgets.DeleteWidget({subreddit:e,id:t},r)}static async reorder(e,t,r){await u.redditAPIPlugins.Widgets.OrderWidgets({subreddit:e,order:t},r)}static async add(e,t){switch(e?.type){case"image":return vo.create(e,t);case"calendar":return ko.create(e,t);case"textarea":return Co.create(e,t);case"button":return So.create(e,t);case"community-list":return Po.create(e,t);case"post-flair":return wo.create(e,t);case"custom":return Fo.create(e,t);default:throw new Error("Unknown widget type")}}};as=new WeakMap,ds=new WeakMap,ls=new WeakMap,us=new WeakMap;var ie=Ka,cs,xo=class xo extends ie{constructor(t,r,s){super(t,r,s);l(this,cs);a(this,cs,t.data.map(o=>(p(o.url,"Image widget data is missing url"),p(o.height,"Image widget data is missing height"),p(o.width,"Image widget data is missing width"),p(o.linkUrl,"Image widget data is missing linkUrl"),{url:o.url,height:o.height,width:o.width,linkUrl:o.linkUrl})))}get images(){return n(this,cs)}toJSON(){return{...super.toJSON(),images:this.images}}static async create(t,r){let o=await u.redditAPIPlugins.Widgets.AddImageWidget(t,r);return new xo(ae.fromJSON(o),t.subreddit,r)}static async update(t,r){let o=await u.redditAPIPlugins.Widgets.UpdateImageWidget(t,r);return new xo(ae.fromJSON(o),t.subreddit,r)}};cs=new WeakMap;var vo=xo,ms,ps,gs,Io=class Io extends ie{constructor(t,r,s){super(t,r,s);l(this,ms);l(this,ps);l(this,gs);p(t.googleCalendarId,"Calendar widget data is missing googleCalendarId"),p(t.configuration,"Calendar widget data is missing configuration"),p(t.styles,"Calendar widget data is missing styles"),a(this,ms,t.googleCalendarId),a(this,ps,t.configuration),a(this,gs,t.styles)}get googleCalendarId(){return n(this,ms)}get configuration(){return n(this,ps)}get styles(){return n(this,gs)}toJSON(){return{...super.toJSON(),googleCalendarId:this.googleCalendarId,configuration:this.configuration,styles:this.styles}}static async create(t,r){let o=await u.redditAPIPlugins.Widgets.AddCalendarWidget(t,r);return new Io(ae.fromJSON(o),t.subreddit,r)}static async update(t,r){let o=await u.redditAPIPlugins.Widgets.UpdateCalendarWidget(t,r);return new Io(ae.fromJSON(o),t.subreddit,r)}};ms=new WeakMap,ps=new WeakMap,gs=new WeakMap;var ko=Io,hs,fs,Eo=class Eo extends ie{constructor(t,r,s){super(t,r,s);l(this,hs);l(this,fs);p(t.text,"Textarea widget data is missing text"),p(t.styles,"Textarea widget data is missing styles"),a(this,hs,t.text),a(this,fs,t.styles)}get text(){return n(this,hs)}get styles(){return n(this,fs)}toJSON(){return{...super.toJSON(),text:this.text,styles:this.styles}}static async create(t,r){let o=await u.redditAPIPlugins.Widgets.AddTextAreaWidget(t,r);return new Eo(ae.fromJSON(o),t.subreddit,r)}static async update(t,r){let o=await u.redditAPIPlugins.Widgets.UpdateTextAreaWidget(t,r);return new Eo(ae.fromJSON(o),t.subreddit,r)}};hs=new WeakMap,fs=new WeakMap;var Co=Eo,bs,ys,vs,Ao=class Ao extends ie{constructor(t,r,s){super(t,r,s);l(this,bs);l(this,ys);l(this,vs);p(t.styles,"Button widget data is missing styles"),a(this,bs,t.buttons),a(this,ys,t.description??""),a(this,vs,t.styles)}get buttons(){return n(this,bs)}get description(){return n(this,ys)}get styles(){return n(this,vs)}toJSON(){return{...super.toJSON(),buttons:this.buttons,description:this.description,styles:this.styles}}static async create(t,r){let o=await u.redditAPIPlugins.Widgets.AddButtonWidget(t,r);return new Ao(ae.fromJSON(o),t.subreddit,r)}static async update(t,r){let o=await u.redditAPIPlugins.Widgets.UpdateButtonWidget(t,r);return new Ao(ae.fromJSON(o),t.subreddit,r)}};bs=new WeakMap,ys=new WeakMap,vs=new WeakMap;var So=Ao,ks,Cs,To=class To extends ie{constructor(t,r,s){super(t,r,s);l(this,ks);l(this,Cs);a(this,ks,t.data.map(o=>ug.fromJSON(o))),p(t.styles,"Community list widget data is missing styles"),a(this,Cs,t.styles)}get communities(){return n(this,ks)}get styles(){return n(this,Cs)}toJSON(){return{...super.toJSON(),communities:this.communities,styles:this.styles}}static async create(t,r){let o=await u.redditAPIPlugins.Widgets.AddCommunityListWidget(t,r);return new To(ae.fromJSON(o),t.subreddit,r)}static async update(t,r){let o=await u.redditAPIPlugins.Widgets.UpdateCommunityListWidget(t,r);return new To(ae.fromJSON(o),t.subreddit,r)}};ks=new WeakMap,Cs=new WeakMap;var Po=To,Ss,Ps,ws,Ro=class Ro extends ie{constructor(t,r,s){super(t,r,s);l(this,Ss);l(this,Ps);l(this,ws);if(p(t.styles,"Post flair widget data is missing styles"),a(this,Ss,t.styles),a(this,Ps,t.order.map(o=>t.templates[o])),!(t.display&&t.display==="list"||t.display==="cloud"))throw new Error("Post flair widget data is missing display type");a(this,ws,t.display)}get styles(){return n(this,Ss)}get templates(){return n(this,Ps)}get display(){return n(this,ws)}toJSON(){return{...super.toJSON(),styles:this.styles,templates:this.templates,display:this.display}}static async create(t,r){let o=await u.redditAPIPlugins.Widgets.AddPostFlairWidget(t,r);return new Ro(ae.fromJSON(o),t.subreddit,r)}static async update(t,r){let o=await u.redditAPIPlugins.Widgets.UpdatePostFlairWidget(t,r);return new Ro(ae.fromJSON(o),t.subreddit,r)}};Ss=new WeakMap,Ps=new WeakMap,ws=new WeakMap;var wo=Ro,Fs,xs,Is,Es,As,Oo=class Oo extends ie{constructor(t,r,s){super(t,r,s);l(this,Fs);l(this,xs);l(this,Is);l(this,Es);l(this,As);p(t.stylesheetUrl,"Custom widget data is missing stylesheetUrl"),p(t.height,"Custom widget data is missing height"),p(t.css,"Custom widget data is missing css"),a(this,Fs,t.imageData??[]),a(this,xs,t.text??""),a(this,Is,t.stylesheetUrl),a(this,Es,t.height),a(this,As,t.css)}get images(){return n(this,Fs)}get text(){return n(this,xs)}get stylesheetUrl(){return n(this,Is)}get height(){return n(this,Es)}get css(){return n(this,As)}toJSON(){return{...super.toJSON(),images:this.images,text:this.text,stylesheetUrl:this.stylesheetUrl,height:this.height,css:this.css}}static async create(t,r){let o=await u.redditAPIPlugins.Widgets.AddCustomWidget(t,r);return new Oo(ae.fromJSON(o),t.subreddit,r)}static async update(t,r){let o=await u.redditAPIPlugins.Widgets.UpdateCustomWidget(t,r);return new Oo(ae.fromJSON(o),t.subreddit,r)}};Fs=new WeakMap,xs=new WeakMap,Is=new WeakMap,Es=new WeakMap,As=new WeakMap;var Fo=Oo,Ts,$a=class extends ie{constructor(t,r,s,o){super(r,s,o);l(this,Ts);let d=t.rules.map(({description:c,priority:m,shortName:y,violationReason:v})=>(p(c,"Subreddit rule is missing description"),p(m,"Subreddit rule is missing priority"),p(y,"Subreddit rule is missing shortName"),p(v,"Subreddit rule is missing violationReason"),{description:c,priority:m,shortName:y,violationReason:v}));a(this,Ts,d)}get rules(){return n(this,Ts)}toJSON(){return{...super.toJSON(),rules:this.rules}}};Ts=new WeakMap;var cg=(r=>(r[r.SUBREDDIT_PERMISSIONS=0]="SUBREDDIT_PERMISSIONS",r[r.APPROVED_CONTRIBUTORS_ONLY=1]="APPROVED_CONTRIBUTORS_ONLY",r[r.MODS_ONLY=2]="MODS_ONLY",r))(cg||{}),pe,ge,mr,pr,gr,hr,fr,br,Ee,we=class we{constructor(e,t,r,s){l(this,pe);l(this,ge);l(this,mr);l(this,pr);l(this,gr);l(this,hr);l(this,fr);l(this,br);l(this,Ee);K(this),a(this,pe,e),a(this,ge,t),a(this,mr,r.contentMd),a(this,pr,r.contentHtml),a(this,gr,r.revisionId),a(this,hr,new Date(r.revisionDate*1e3)),a(this,fr,r.reason??""),a(this,br,r.revisionBy?.data?new C(r.revisionBy.data,s):void 0),a(this,Ee,s)}get name(){return n(this,pe)}get subredditName(){return n(this,ge)}get content(){return n(this,mr)}get contentHtml(){return n(this,pr)}get revisionId(){return n(this,gr)}get revisionDate(){return n(this,hr)}get revisionReason(){return n(this,fr)}get revisionAuthor(){return n(this,br)}toJSON(){return{name:n(this,pe),subredditName:n(this,ge),content:n(this,mr),contentHtml:n(this,pr),revisionId:n(this,gr),revisionDate:n(this,hr),revisionReason:n(this,fr),revisionAuthor:n(this,br)?.toJSON()}}async update(e,t){return we.updatePage({subredditName:n(this,ge),page:n(this,pe),content:e,reason:t},n(this,Ee))}async getRevisions(e){return we.getPageRevisions({subredditName:n(this,ge),page:n(this,pe),...e},n(this,Ee))}async revertTo(e){return we.revertPage(n(this,ge),n(this,pe),e,n(this,Ee))}async getSettings(){return we.getPageSettings(n(this,ge),n(this,pe),n(this,Ee))}async updateSettings(e){return we.updatePageSettings({subredditName:n(this,ge),page:n(this,pe),listed:e.listed,permLevel:e.permLevel},n(this,Ee))}async addEditor(e){return we.addEditor(n(this,ge),n(this,pe),e,n(this,Ee))}async removeEditor(e){return we.removeEditor(n(this,ge),n(this,pe),e,n(this,Ee))}static async getPage(e,t,r){let o=await u.redditAPIPlugins.Wiki.GetWikiPage({subreddit:e,page:t},r);return p(o.data,"Failed to get wiki page"),new we(t,e,o.data,r)}static async getPages(e,t){return(await u.redditAPIPlugins.Wiki.GetWikiPages({subreddit:e},t)).data||[]}static async createPage(e,t){return we.updatePage(e,t)}static async updatePage(e,t){return await u.redditAPIPlugins.Wiki.EditWikiPage({subreddit:e.subredditName,page:e.page,content:e.content,reason:e.reason??""},t),we.getPage(e.subredditName,e.page,t)}static getPageRevisions(e,t){let r=u.redditAPIPlugins.Wiki;return new W({hasMore:!0,after:e.after,limit:e.limit,pageSize:e.pageSize,async fetch(s){let o=await r.GetWikiPageRevisions({subreddit:e.subredditName,page:e.page,limit:s.limit,after:s.after,before:s.before},t);return mg(o,t)}})}static async revertPage(e,t,r,s){await u.redditAPIPlugins.Wiki.RevertWikiPage({subreddit:e,page:t,revision:r},s)}static async getPageSettings(e,t,r){let o=await u.redditAPIPlugins.Wiki.GetWikiPageSettings({subreddit:e,page:t},r);return p(o.data,"Failed to get wiki page settings"),new Bo(o.data,r)}static async updatePageSettings(e,t){let s=await u.redditAPIPlugins.Wiki.UpdateWikiPageSettings({subreddit:e.subredditName,page:e.page,listed:e.listed?"on":"",permlevel:e.permLevel},t);return p(s.data,"Failed to update wiki page settings"),new Bo(s.data,t)}static async addEditor(e,t,r,s){await u.redditAPIPlugins.Wiki.AllowEditor({act:"add",subreddit:e,page:t,username:r},s)}static async removeEditor(e,t,r,s){await u.redditAPIPlugins.Wiki.AllowEditor({act:"del",subreddit:e,page:t,username:r},s)}};pe=new WeakMap,ge=new WeakMap,mr=new WeakMap,pr=new WeakMap,gr=new WeakMap,hr=new WeakMap,fr=new WeakMap,br=new WeakMap,Ee=new WeakMap;var ue=we,yr,vr,kr,Cr,Sr,Pr,Za=class{constructor(e,t){l(this,yr);l(this,vr);l(this,kr);l(this,Cr);l(this,Sr);l(this,Pr);a(this,yr,e.id),a(this,vr,e.page),a(this,kr,new Date(e.timestamp)),p(e.author?.data,"Wiki page revision author details are missing"),a(this,Cr,new C(e.author.data,t)),a(this,Sr,e.reason??""),a(this,Pr,e.revisionHidden??!1)}get id(){return n(this,yr)}get page(){return n(this,vr)}get date(){return n(this,kr)}get author(){return n(this,Cr)}get reason(){return n(this,Sr)}get hidden(){return n(this,Pr)}toJSON(){return{id:n(this,yr),page:n(this,vr),date:n(this,kr),author:n(this,Cr).toJSON(),reason:n(this,Sr),hidden:n(this,Pr)}}};yr=new WeakMap,vr=new WeakMap,kr=new WeakMap,Cr=new WeakMap,Sr=new WeakMap,Pr=new WeakMap;var wr,Fr,xr,Bo=class{constructor(e,t){l(this,wr);l(this,Fr);l(this,xr);a(this,wr,e.listed),a(this,Fr,e.permLevel),a(this,xr,e.editors.map(r=>(p(r.data,"Wiki page editor details are missing"),new C(r.data,t))))}get listed(){return n(this,wr)}get permLevel(){return n(this,Fr)}get editors(){return n(this,xr)}toJSON(){return{listed:n(this,wr),permLevel:n(this,Fr),editors:n(this,xr).map(e=>e.toJSON())}}};wr=new WeakMap,Fr=new WeakMap,xr=new WeakMap;function mg(i,e){return p(i.data?.children,"Wiki page revision listing is missing children"),{children:i.data.children.map(r=>new Za(r,e)),before:i.data.before,after:i.data.after}}var pg=["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"],gg=["border-image","border-image-source","behavior","expression","list-style-image","cursor","content"],hg=["onload","onerror","onclick","onmouseover"];function fg(i){return/xmlns=["']http:\/\/www\.w3\.org\/2000\/svg["']/.test(i)?i:i.replace(/<svg\b/,'<svg xmlns="http://www.w3.org/2000/svg"')}function Fc(i){if(i){if(!i.trim().startsWith("<svg")){console.log("The provided string is not a valid SVG.");return}try{let e=new RegExp(`<\\s*(${pg.join("|")})\\b`,"gi"),t=new RegExp(`(${gg.join("|")})\\s*:\\s*url\\s*\\((['"]?)(.*?)\\2\\)`,"gi"),r=new RegExp(`(${hg.join("|")})\\s*(=\\s*(['"]?)(.*?)\\3)?`,"gi");i=i.trim().replace(/\s+/g," "),i=fg(i);let s=i.match(e)||[],o=i.match(t)||[],d=i.match(r)||[],c=!1;return s.length>0&&(c=!0,console.warn(`Disallowed elements detected in SVG: ${s.map(m=>m.replace("<","")).join(", ")}`)),o.length>0&&(c=!0,console.warn(`Disallowed styles detected in SVG: ${o.map(m=>m.split(":")[0]).join(", ")}`)),d.length>0&&(c=!0,console.warn(`Disallowed attributes detected in SVG: ${d.map(m=>m.split("=")[0]).join(", ")}`)),c?void 0:i}catch{return}}}function BS(i,...e){let t="";return i.forEach((r,s)=>{t+=r;let o=e[s];o!==void 0&&(t+=`${o}`)}),t=Fc(t),t===void 0?"":`data:image/svg+xml;charset=UTF-8,${encodeURIComponent(t)}`}import{EffectType as xc}from"@devvit/protos";import{WebViewVisibility as bg}from"@devvit/protos";var Ir,Rs,Os,Er,Zt,Xa=class{constructor(e,t){this.state={messageCount:0};l(this,Ir);l(this,Rs);l(this,Os);l(this,Er);l(this,Zt);this.postMessage=e=>{n(this,Zt).emitEffect(`postMessage${this.state.messageCount++}`,{type:xc.EFFECT_WEB_VIEW,webView:{postMessage:{webViewId:n(this,Ir),app:{message:e}}}})};this.mount=()=>{let t=(n(this,Zt)?.devvitContext?.assets).getURL(n(this,Rs),{webView:!0});if(!t)throw Error("useWebView fullscreen request failed; web view asset could not be found");n(this,Zt).emitEffect("fullscreen",{type:xc.EFFECT_WEB_VIEW,webView:{fullscreen:{id:n(this,Ir),show:!0,url:t}}})};a(this,Rs,t.url??"index.html"),a(this,Ir,e.hookId),a(this,Os,t.onMessage),a(this,Er,t.onUnmount),a(this,Zt,e.context)}async onUIEvent(e){if(e.webView?.fullScreen)!(e.webView.fullScreen.visibility===bg.WEBVIEW_VISIBLE)&&n(this,Er)&&await n(this,Er).call(this,this);else if(e.webView?.postMessage){let{message:t}=e.webView.postMessage;await n(this,Os).call(this,t,this)}}};Ir=new WeakMap,Rs=new WeakMap,Os=new WeakMap,Er=new WeakMap,Zt=new WeakMap;function yg(i){let e=ce({namespace:"useWebView",initializer:t=>new Xa(t,i)});return{postMessage:e.postMessage,mount:e.mount}}export{Ag as ALL_ICON_NAMES,Id as AboutLocations,Cc as AuthorFlairSettings,So as ButtonWidget,ko as CalendarWidget,X as Comment,Po as CommunityListWidget,Fo as CustomWidget,u as Devvit,ve as Flair,ne as FlairTemplate,Lp as FlairType,Ge as Hook,vo as ImageWidget,W as Listing,sg as ModMailActionType,rg as ModMailConversationState,Ls as ModMailService,ye as ModNote,V as Post,Sc as PostFlairSettings,wo as PostFlairWidget,wt as PrivateMessage,Lt as RichTextBuilder,No as SettingScope,Yp as SocialLinkType,le as Subreddit,vc as SubredditDescription,$a as SubredditRulesWidget,kc as SubredditWikiSettings,Co as TextAreaWidget,C as User,ie as Widget,ue as WikiPage,cg as WikiPagePermissionLevel,Za as WikiPageRevision,Bo as WikiPageSettings,dn as convertUserFlairProtoToAPI,xd as getCurrentUsernameFromMetadata,Ns as getModerationLog,Ed as getSubredditInfoById,Ad as getSubredditInfoByName,Td as getSubredditLeaderboard,Vo as getSubredditNameById,Rd as getSubredditStyles,Od as getVaultByAddress,Bd as getVaultByUserId,BS as svg,wp as useAsync,Pa as useChannel,ka as useForm,xa as useInterval,Ta as useState,yg as useWebView};
|
|
1
|
+
var Ec=Object.create;var Qa=Object.defineProperty;var Ac=Object.getOwnPropertyDescriptor;var Tc=Object.getOwnPropertyNames;var Rc=Object.getPrototypeOf,Oc=Object.prototype.hasOwnProperty;var Ya=r=>{throw TypeError(r)};var Qt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Bc=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Tc(e))!Oc.call(r,s)&&s!==t&&Qa(r,s,{get:()=>e[s],enumerable:!(i=Ac(e,s))||i.enumerable});return r};var ed=(r,e,t)=>(t=r!=null?Ec(Rc(r)):{},Bc(e||!r||!r.__esModule?Qa(t,"default",{value:r,enumerable:!0}):t,r));var Uo=(r,e,t)=>e.has(r)||Ya("Cannot "+t);var n=(r,e,t)=>(Uo(r,e,"read from private field"),t?t.call(r):e.get(r)),l=(r,e,t)=>e.has(r)?Ya("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),a=(r,e,t,i)=>(Uo(r,e,"write to private field"),i?i.call(r,t):e.set(r,t),t),h=(r,e,t)=>(Uo(r,e,"access private method"),t);var td=(r,e,t,i)=>({set _(s){a(r,e,s,t)},get _(){return n(r,e,i)}});var ca=Qt((Yb,gl)=>{var $m=Object.prototype.toString;gl.exports=function(e){if(e===void 0)return"undefined";if(e===null)return"null";var t=typeof e;if(t==="boolean")return"boolean";if(t==="string")return"string";if(t==="number")return"number";if(t==="symbol")return"symbol";if(t==="function")return Ym(e)?"generatorfunction":"function";if(Km(e))return"array";if(ip(e))return"buffer";if(tp(e))return"arguments";if(Xm(e))return"date";if(Zm(e))return"error";if(Qm(e))return"regexp";switch(pl(e)){case"Symbol":return"symbol";case"Promise":return"promise";case"WeakMap":return"weakmap";case"WeakSet":return"weakset";case"Map":return"map";case"Set":return"set";case"Int8Array":return"int8array";case"Uint8Array":return"uint8array";case"Uint8ClampedArray":return"uint8clampedarray";case"Int16Array":return"int16array";case"Uint16Array":return"uint16array";case"Int32Array":return"int32array";case"Uint32Array":return"uint32array";case"Float32Array":return"float32array";case"Float64Array":return"float64array"}if(ep(e))return"generator";switch(t=$m.call(e),t){case"[object Object]":return"object";case"[object Map Iterator]":return"mapiterator";case"[object Set Iterator]":return"setiterator";case"[object String Iterator]":return"stringiterator";case"[object Array Iterator]":return"arrayiterator"}return t.slice(8,-1).toLowerCase().replace(/\s/g,"")};function pl(r){return typeof r.constructor=="function"?r.constructor.name:null}function Km(r){return Array.isArray?Array.isArray(r):r instanceof Array}function Zm(r){return r instanceof Error||typeof r.message=="string"&&r.constructor&&typeof r.constructor.stackTraceLimit=="number"}function Xm(r){return r instanceof Date?!0:typeof r.toDateString=="function"&&typeof r.getDate=="function"&&typeof r.setDate=="function"}function Qm(r){return r instanceof RegExp?!0:typeof r.flags=="string"&&typeof r.ignoreCase=="boolean"&&typeof r.multiline=="boolean"&&typeof r.global=="boolean"}function Ym(r,e){return pl(r)==="GeneratorFunction"}function ep(r){return typeof r.throw=="function"&&typeof r.return=="function"&&typeof r.next=="function"}function tp(r){try{if(typeof r.length=="number"&&typeof r.callee=="function")return!0}catch(e){if(e.message.indexOf("callee")!==-1)return!0}return!1}function ip(r){return r.constructor&&typeof r.constructor.isBuffer=="function"?r.constructor.isBuffer(r):!1}});var bl=Qt((ey,fl)=>{"use strict";var hl=Symbol.prototype.valueOf,rp=ca();function np(r,e){switch(rp(r)){case"array":return r.slice();case"object":return Object.assign({},r);case"date":return new r.constructor(Number(r));case"map":return new Map(r);case"set":return new Set(r);case"buffer":return dp(r);case"symbol":return lp(r);case"arraybuffer":return op(r);case"float32array":case"float64array":case"int16array":case"int32array":case"int8array":case"uint16array":case"uint32array":case"uint8clampedarray":case"uint8array":return ap(r);case"regexp":return sp(r);case"error":return Object.create(r);default:return r}}function sp(r){let e=r.flags!==void 0?r.flags:/\w+$/.exec(r)||void 0,t=new r.constructor(r.source,e);return t.lastIndex=r.lastIndex,t}function op(r){let e=new r.constructor(r.byteLength);return new Uint8Array(e).set(new Uint8Array(r)),e}function ap(r,e){return new r.constructor(r.buffer,r.byteOffset,r.length)}function dp(r){let e=r.length,t=Buffer.allocUnsafe?Buffer.allocUnsafe(e):Buffer.from(e);return r.copy(t),t}function lp(r){return hl?Object(hl.call(r)):{}}fl.exports=np});var vl=Qt((ty,yl)=>{"use strict";yl.exports=function(e){return e!=null&&typeof e=="object"&&Array.isArray(e)===!1}});var Sl=Qt((iy,Cl)=>{"use strict";var up=vl();function kl(r){return up(r)===!0&&Object.prototype.toString.call(r)==="[object Object]"}Cl.exports=function(e){var t,i;return!(kl(e)===!1||(t=e.constructor,typeof t!="function")||(i=t.prototype,kl(i)===!1)||i.hasOwnProperty("isPrototypeOf")===!1)}});var wl=Qt((ry,Pl)=>{"use strict";var cp=bl(),mp=ca(),pp=Sl();function ma(r,e){switch(mp(r)){case"object":return gp(r,e);case"array":return hp(r,e);default:return cp(r)}}function gp(r,e){if(typeof e=="function")return e(r);if(e||pp(r)){let t=new r.constructor;for(let i in r)t[i]=ma(r[i],e);return t}return r}function hp(r,e){let t=new r.constructor(r.length);for(let i=0;i<r.length;i++)t[i]=ma(r[i],e);return t}Pl.exports=ma});var hc=Qt(fo=>{"use strict";fo.byteLength=Gp;fo.toByteArray=zp;fo.fromByteArray=Kp;var Be=[],Pe=[],Vp=typeof Uint8Array<"u"?Uint8Array:Array,Va="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Vt=0,pc=Va.length;Vt<pc;++Vt)Be[Vt]=Va[Vt],Pe[Va.charCodeAt(Vt)]=Vt;var Vt,pc;Pe[45]=62;Pe[95]=63;function gc(r){var e=r.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var t=r.indexOf("=");t===-1&&(t=e);var i=t===e?0:4-t%4;return[t,i]}function Gp(r){var e=gc(r),t=e[0],i=e[1];return(t+i)*3/4-i}function Jp(r,e,t){return(e+t)*3/4-t}function zp(r){var e,t=gc(r),i=t[0],s=t[1],o=new Vp(Jp(r,i,s)),d=0,c=s>0?i-4:i,m;for(m=0;m<c;m+=4)e=Pe[r.charCodeAt(m)]<<18|Pe[r.charCodeAt(m+1)]<<12|Pe[r.charCodeAt(m+2)]<<6|Pe[r.charCodeAt(m+3)],o[d++]=e>>16&255,o[d++]=e>>8&255,o[d++]=e&255;return s===2&&(e=Pe[r.charCodeAt(m)]<<2|Pe[r.charCodeAt(m+1)]>>4,o[d++]=e&255),s===1&&(e=Pe[r.charCodeAt(m)]<<10|Pe[r.charCodeAt(m+1)]<<4|Pe[r.charCodeAt(m+2)]>>2,o[d++]=e>>8&255,o[d++]=e&255),o}function qp(r){return Be[r>>18&63]+Be[r>>12&63]+Be[r>>6&63]+Be[r&63]}function $p(r,e,t){for(var i,s=[],o=e;o<t;o+=3)i=(r[o]<<16&16711680)+(r[o+1]<<8&65280)+(r[o+2]&255),s.push(qp(i));return s.join("")}function Kp(r){for(var e,t=r.length,i=t%3,s=[],o=16383,d=0,c=t-i;d<c;d+=o)s.push($p(r,d,d+o>c?c:d+o));return i===1?(e=r[t-1],s.push(Be[e>>2]+Be[e<<4&63]+"==")):i===2&&(e=(r[t-2]<<8)+r[t-1],s.push(Be[e>>10]+Be[e>>4&63]+Be[e<<2&63]+"=")),s.join("")}});function p(r,e){if(r==null)throw Error(e??"Expected nonnullish value.")}function St(r,e){if(!r)throw Error(e)}var ee;(function(r){r.COMMENT="t1_",r.ACCOUNT="t2_",r.LINK="t3_",r.MESSAGE="t4_",r.SUBREDDIT="t5_",r.AWARD="t6_"})(ee||(ee={}));function Ge(r){return r.startsWith(ee.COMMENT)}function Bs(r){return r.startsWith(ee.ACCOUNT)}function Pt(r){return r.startsWith(ee.LINK)}function id(r){return r.startsWith(ee.MESSAGE)}function rd(r){return r.startsWith(ee.SUBREDDIT)}function nd(r){return r.startsWith(ee.AWARD)}function Mc(r){St(Ge(r),`Expected comment id to start with ${ee.COMMENT}, got ${r}}`)}function Uc(r){St(Bs(r),`Expected account id to start with ${ee.ACCOUNT}, got ${r}}`)}function Dc(r){St(Pt(r),`Expected link id to start with ${ee.LINK}, got ${r}}`)}function Nc(r){St(id(r),`Expected message id to start with ${ee.MESSAGE}, got ${r}}`)}function Lc(r){St(rd(r),`Expected subreddit id to start with ${ee.SUBREDDIT}, got ${r}}`)}function _c(r){St(nd(r),`Expected award id to start with ${ee.AWARD}, got ${r}}`)}function Yt(r){return Mc(r),r}function te(r){return Uc(r),r}function de(r){return Dc(r),r}function Hc(r){return Nc(r),r}function $(r){return Lc(r),r}function jc(r){return _c(r),r}function fe(r){if(Ge(r))return Yt(r);if(Bs(r))return te(r);if(Pt(r))return de(r);if(id(r))return Hc(r);if(rd(r))return $(r);if(nd(r))return jc(r);throw new Error(`Expected thing id to start with ${Object.values(ee).join(", ")} got ${r}}`)}function Do(r){return Ge(r)}import*as k from"@devvit/protos";var Ms=class{constructor(e){}};var No=(t=>(t.Installation="installation",t.App="app",t))(No||{});function wt(r,e=new Set){for(let t of r){if(t.type==="group"){wt(t.fields,e);continue}let i=t.name;if(e.has(i))throw new Error(`Duplicate field name: ${i}`);e.add(i)}Wc(r)}function Wc(r){for(let e of r)if(e.type==="string"&&e.isSecret&&e.scope!=="app")throw`Invalid setting: only app settings can be secrets. Add "scope: SettingScope.App" to field "${e.name}"`}var Je=Object.freeze({INTERVAL:0,FORM:1,STATE:2,CHANNEL:3,WEB_VIEW:4});var Tg=["3rd-party","activity","add-emoji","add","add-media","add-to-feed","admin","ads","ai","align-center","align-left","align-right","all","ama","appearance","approve","archived","aspect-ratio","aspect-rectangle","attach","audience","audio","author","automod","avatar-style","award","back","backup","ban","best","block","blockchain","bold","boost","bot","bounce","brand-awareness","browse","browser","cake","calendar","camera","campaign","caret-down","caret-left","caret-right","caret-up","chat","chat-group","chat-new","chat-private","checkbox-dismiss","checkbox","checkmark","chrome","clear","client-list","close","closed-captioning","code-block","code-inline","coins-color-old","coins","collapse-left","collapse-right","collectible-expressions","collection","comment","comments","communities","community","confidence","contest","controversial","conversion","copy-clipboard","crop","crosspost","crowd-control","custom-feed","customize","dashboard","day","delete-column","delete","delete-row","devvit","discover","dismiss-all","distinguish","down-arrow","down","download","downvote","downvotes","drag","drugs","duplicate","edit","effect","embed","emoji","end-live-chat","error","expand-left","expand-right","external","feed-video","filter","format","forward","funnel","gif-post","gold","hashtag","heart","help","hide","history","home","hot","ignore-reports","image-post","inbox","info","insert-column-left","insert-column-right","insert-row-above","insert-row-below","internet","invite","italic","join","joined","jump-down","jump-up","karma","keyboard","kick","language","leave","left","link","link-post","list-bulleted","list-numbered","live-chat","live","load","location","lock","logout","loop","macro","mark-read","marketplace","mask","media-gallery","meme","menu","message","mic","mic-mute","mod","mod-mail","mod-mode","mod-mute","mod-overflow","mod-queue","mod-unmute","music","mute","new","night","no-internet","notification","notification-frequent","notification-off","nsfw","nsfw-language","nsfw-violence","official","original","overflow-caret","overflow-horizontal","overflow-vertical","pause","payment","peace","pending-posts","phone","pin","play","poll-post","popular","posts","powerup","predictions","premium","privacy","profile","qa","qr-code","quarantined","quote","r-slash","radar","radio-button","raise-hand","random","ratings-everyone","ratings-mature","ratings-nsfw","ratings-violence","recovery-phrase","refresh","removal-reasons","remove","reply","report","reverse","rich-text","right","rising","rotate","rotate-image","rpan","rules","safari","save","save-view","saved","saved-response","search","self","send","settings","severity","share","share-new","show","side-menu","skipback10","skipforward10","sort-az","sort","sort-price","sort-za","spam","spoiler","sponsored","spreadsheet","star","statistics","status-live","sticker","strikethrough","subtract","superscript","swap-camera","swipe-back","swipe-down","swipe","swipe-up","table","tag","tap","text","text-post","text-size","toggle","tools","top","topic-activism","topic-addictionsupport","topic-advice","topic-animals","topic-anime","topic-art","topic-beauty","topic-business","topic-careers","topic-cars","topic-celebrity","topic-craftsdiy","topic-crypto","topic-culture","topic-diy","topic-entertainment","topic-ethics","topic-family","topic-fashion","topic","topic-fitness","topic-food","topic-funny","topic-gender","topic-health","topic-help","topic-history","topic-hobbies","topic-homegarden","topic-internet","topic-law","topic-learning","topic-lifestyle","topic-marketplace","topic-mature","topic-mensfashion","topic-menshealth","topic-meta","topic-military","topic-movies","topic-music","topic-news","topic-other","topic-outdoors","topic-pets","topic-photography","topic-places","topic-podcasts","topic-politics","topic-programming","topic-reading","topic-religion","topic-science","topic-sexorientation","topic-sports","topic-style","topic-tabletop","topic-technology","topic-television","topic-traumasupport","topic-travel","topic-videogaming","topic-womensfashion","topic-womenshealth","translate","translation-off","trim","u-slash","unban","undo","unheart","unlock","unmod","unpin","unstar","unverified","up-arrow","up","upload","upvote","upvotes","user","user-note","users","vault","verified","video-camera","video-feed","video-post","video-thread","video-transcription","view-card","view-classic","view-compact","view-grid","view-sort","views","volume","wallet","warning","webhook","whale","wiki-ban","wiki","wiki-unban","world","coins-color","powerup-color","powerup-fill-color","share-android","share-ios","video-live-1","video-live-fill-1","video-live","volume-mute","binoculars","caret-updown","planet","telescope"];import{AppSettingsDefinition as nm,GetFieldsResponse as sm}from"@devvit/protos";import{FormFieldType as be}from"@devvit/protos";function De(r){return r.map(e=>{switch(e.type){case"string":return Vc(e);case"image":return Gc(e);case"paragraph":return Jc(e);case"number":return zc(e);case"select":return qc(e);case"boolean":return $c(e);case"group":return Kc(e);default:throw new Error("Unknown field type.")}})}function Vc(r){return{defaultValue:{fieldType:be.STRING,stringValue:r.defaultValue},disabled:r.disabled,fieldConfig:{stringConfig:{placeholder:r.placeholder}},fieldId:r.name,fieldType:be.STRING,helpText:r.helpText,label:r.label,required:r.required,isSecret:r.isSecret}}function Gc(r){return{disabled:r.disabled,fieldId:r.name,fieldType:be.IMAGE,helpText:r.helpText,label:r.label,required:r.required}}function Jc(r){return{defaultValue:{fieldType:be.PARAGRAPH,stringValue:r.defaultValue},disabled:r.disabled,fieldConfig:{paragraphConfig:{lineHeight:r.lineHeight,placeholder:r.placeholder}},fieldId:r.name,fieldType:be.PARAGRAPH,helpText:r.helpText,label:r.label,required:r.required}}function zc(r){return{defaultValue:{fieldType:be.NUMBER,numberValue:r.defaultValue},disabled:r.disabled,fieldConfig:{numberConfig:{}},fieldId:r.name,fieldType:be.NUMBER,helpText:r.helpText,label:r.label,required:r.required}}function qc(r){return{defaultValue:{fieldType:be.SELECTION,selectionValue:{values:r.defaultValue??[]}},disabled:r.disabled,fieldConfig:{selectionConfig:{choices:r.options,multiSelect:r.multiSelect}},fieldId:r.name,fieldType:be.SELECTION,helpText:r.helpText,label:r.label,required:r.required}}function $c(r){return{defaultValue:{fieldType:be.BOOLEAN,boolValue:r.defaultValue},disabled:r.disabled,fieldId:r.name,fieldType:be.BOOLEAN,helpText:r.helpText,label:r.label}}function Kc(r){return{fieldId:"",fieldType:be.GROUP,fieldConfig:{groupConfig:{fields:De(r.fields)}},label:r.label,helpText:r.helpText}}function R(r,e){u.prototype[r]=e}import{ValidateFormResponse as rm}from"@devvit/protos";import{RealtimeSubscriptionStatus as od}from"@devvit/protos";var P=Object.freeze({Actor:"devvit-actor",App:"devvit-app",AppUser:"devvit-app-user",AppViewerAuthToken:"devvit-app-viewer-authorization",Caller:"devvit-caller",CallerPortID:"devvit-caller-port-id",Canary:"devvit-canary",Debug:"devvit-debug",GQLHost:"devvit-gql-host",Installation:"devvit-installation",ModPermissions:"devvit-mod-permissions",Post:"devvit-post",PostAuthor:"devvit-post-author",R2Auth:"devvit-sec-authorization",R2Host:"devvit-r2-host",RemoteHostname:"devvit-remote-hostname",SettingsUri:"devvit-sec-settings-uri",StreamID:"devvit-stream-id",Subreddit:"devvit-subreddit",SubredditName:"devvit-subreddit-name",TraceID:"devvit-trace-id",User:"devvit-user",Username:"devvit-user-name",UserAgent:"devvit-user-agent",Version:"devvit-version",Language:"devvit-accept-language",Timezone:"devvit-accept-timezone",Traceparent:"traceparent",AppDependencies:"devvit-app-dependencies"}),sd;(function(r){r.Blocks="blocks",r.EmitSnapshots="emitSnapshots",r.EmitState="emitState",r.Realtime="realtime",r.Runtime="runtime",r.Surface="surface",r.UseAsync="useAsync",r.Payments="payments",r.Bootstrap="bootstrap",r.WebView="webView"})(sd||(sd={}));function ad(r){function e(t){let s=r.currentHookIndex,o=r.getCurrentComponentState(),d=r.getPreviousComponentState(),c=r.metadata[P.App]?.values[0];p(c,"useChannel - app is missing from Context");let m=r.metadata[P.Installation]?.values[0];p(m,"useChannel - installation is missing from Context");async function b(B){let Y=o[s].channel;if(o[s].active)if(o[s].connected)await r.realtime.send(Y,B);else throw Error(`Failed to send to channel '${Y}'; it is active but not yet connected`);else throw Error(`Cannot send a message over inactive channel: ${Y}`)}function y(){if(!o[s].active){let B=o[s].channel;o[s].active=!0,r.addRealtimeChannel(B)}}function f(){if(o[s].active){let B=o[s].channel;o[s].active=!1,r.removeRealtimeChannel(B)}}function S(B){return async()=>{let Y;switch(B.status){case od.REALTIME_SUBSCRIBED:o[s].connected=!0,Y=t.onSubscribed?.();break;case od.REALTIME_UNSUBSCRIBED:o[s].connected=!1,Y=t.onUnsubscribed?.();break;default:Y=t.onMessage(B.event?.data?.msg);break}await Y}}let v={channel:`${c}:${m}:${t.name}`,active:!1,connected:!1,preventCallback:!1,type:Je.CHANNEL};s in o?v=o[s]:s in d&&(v=d[s]);let O=r.realtimeEvent;r.isInitialRender?v.active=!1:O&&v.active&&O.event.channel===v.channel&&(v.preventCallback||r.runHook(S(O)),r.rerenderIn(0)),o[s]=v,r.currentHookIndex++;let L=0;return v.active&&v.connected?L=2:v.active&&!v.connected?L=1:!v.active&&v.connected?L=3:!v.active&&!v.connected&&(L=4),{subscribe:y,unsubscribe:f,send:b,status:L}}return e}import{FormFieldType as ei}from"@devvit/protos";function Lo(r){switch(r.fieldType){case ei.STRING:return r.stringValue;case ei.IMAGE:return r.stringValue;case ei.PARAGRAPH:return r.stringValue;case ei.NUMBER:return r.numberValue;case ei.BOOLEAN:return r.boolValue;case ei.SELECTION:return r.selectionValue?.values??[];default:return}}function ze(r){return Object.keys(r).reduce((e,t)=>{let i=Lo(r[t]);return i!==void 0&&(e[t]=i),e},{})}function dd(r){function e(t,i){let s=r.currentHookIndex,o=r.getCurrentComponentKey(),d=r.getCurrentComponentState(),c=r.getPreviousComponentState(),m=`form.hook.${o}.${s}`,b={formKey:m,preventSubmit:!1,type:Je.FORM};s in d?b=d[s]:s in c&&(b=c[s]),d[s]=b,r.forms.set(m,t);let y=r.formSubmittedEvent;return y&&!b.preventSubmit&&y.formId===m&&r.runHook(async()=>{let f=i(ze(y.results));f&&f instanceof Promise&&await f,r.rerenderIn(0)}),d[s].preventSubmit=!1,r.currentHookIndex++,m}return e}function ld(r){function e(t,i){let s=r.currentHookIndex,o=r.getCurrentComponentState(),d=r.getPreviousComponentState(),c=100,m=Math.max(c,i),b={lastRun:void 0,running:!1,preventCallback:!1,type:Je.INTERVAL};s in o?b=o[s]:s in d&&(b=d[s]);function y(){i<c&&console.error(`useInterval delay must be at least ${c}ms. Your interval of ${i}ms was automatically extended.`);for(let[S,v]of Object.entries(o))if(S!==s.toString()&&v?.type===Je.INTERVAL&&v?.running)throw new Error("Only one useInterval hook may be running at a time");o[s]={running:!0,lastRun:o[s]?.lastRun??Date.now(),preventCallback:!1,type:Je.INTERVAL},r.rerenderIn(m)}function f(){o[s].running=!1,o[s].lastRun=void 0,o[s].preventCallback=!1}return r.isEffectRender&&b.running&&(b.preventCallback||(b.lastRun===void 0||b.lastRun+m<Date.now())&&r.runHook(async()=>{let S=t();S&&S instanceof Promise&&await S,b.lastRun=Date.now()}),r.rerenderIn(m)),b.preventCallback=!1,o[s]=b,r.currentHookIndex++,{start:y,stop:f}}return e}function ud(r){function e(t){let i=r.currentHookIndex,s=r.getCurrentComponentState(),o=r.getPreviousComponentState();if(i in s)return r.currentHookIndex++,[s[i],d];if(r.isInitialRender||!(i in o)){let c=t instanceof Function?t():t;if(c instanceof Promise)throw(async()=>{s[i]=await c,r.currentHookIndex=0})();s[i]=c}else s[i]=o[i];function d(c){if(r.isRendering)throw new Error("Cannot call setState while rendering.");s[i]=c instanceof Function?c(s[i]):c}return r.currentHookIndex++,[s[i],d]}return e}var Wo={now(){return new Date}};function cd(r){return`__autocache__${r}`}function md(r){return`__lock__${r}`}var Xc=300,Qc=1e3,Us=5e3,_o=3,pd=.1,gd=1e3,Yc=3e4;function hd(r){if(r.error)throw new Error(r.error);return r.value}var qe,$e,ye,ti,J,fd,bd,yd,Ho,vd,kd,jo,Cd,Ds=class{constructor(e,t,i=Wo){l(this,J);l(this,qe);l(this,$e,{});l(this,ye);l(this,ti);a(this,qe,e),a(this,ti,t),a(this,ye,i)}async cache(e,t){a(this,$e,n(this,ti).__cache=n(this,ti).__cache??{}),h(this,J,Cd).call(this,t);let i=h(this,J,fd).call(this,t.key);if(i!==void 0)return i;let s=await h(this,J,jo).call(this,t.key),o=await h(this,J,bd).call(this,t,s,e);return hd(o)}};qe=new WeakMap,$e=new WeakMap,ye=new WeakMap,ti=new WeakMap,J=new WeakSet,fd=function(e){let t=n(this,$e)[e];if(t){let i=n(this,ye).now().getTime(),s=t?.error&&t?.errorTime&&t.errorCount<_o&&Math.random()<pd&&t.errorTime+gd<i;if(t?.expires&&t.expires<i&&t.checkedAt+gd<i||s){delete n(this,$e)[e];return}else return hd(t)}},bd=async function(e,t,i){let s=t?.expires,o=s?h(this,J,kd).call(this,s):1;return!t||t?.error&&t.errorCount<_o&&pd>Math.random()||o>Math.random()?h(this,J,yd).call(this,e,t,i):t},yd=async function(e,t,i){let s=md(e.key),o=n(this,ye).now().getTime(),d=new Date(o+e.ttl/2);if(await n(this,qe).set(s,"1",{expiration:d,nx:!0}))return h(this,J,vd).call(this,e.key,t,i,e.ttl);if(t)return t;{let m=n(this,ye).now();return h(this,J,Ho).call(this,m,e.key,e.ttl)}},Ho=async function(e,t,i){let s=Math.min(i,Qc),o=await h(this,J,jo).call(this,t);if(o)return o;if(n(this,ye).now().getTime()-e.getTime()>=s)throw new Error(`Cache request timed out trying to get data at key: ${t}`);return await new Promise(d=>setTimeout(d,Xc)),h(this,J,Ho).call(this,e,t,i)},vd=async function(e,t,i,s){let o=n(this,ye).now().getTime()+s;t=t??{value:null,expires:o,errorCount:0,error:null,errorTime:null,checkedAt:0};try{t.value=await i(),t.error=null,t.errorCount=0,t.errorTime=null}catch(d){t.value=null,t.error=d.message??"Unknown error",t.errorTime=n(this,ye).now().getTime(),t.errorCount++}return n(this,$e)[e]=t,await n(this,qe).set(cd(e),JSON.stringify(t),{expiration:new Date(o+Yc)}),t.error&&t.errorCount<_o&&await n(this,qe).del(md(e)),t},kd=function(e){let t=n(this,ye).now().getTime(),i=e-t;return i<0?1:i<1e3?.1:i<2e3?.01:i<3e3?.001:0},jo=async function(e){let t=await n(this,qe).get(cd(e));if(t){let i=JSON.parse(t);return i.checkedAt=n(this,ye).now().getTime(),n(this,$e)[e]=i,i}},Cd=function(e){e.ttl<Us&&(console.warn(`Cache TTL cannot be less than ${Us} milliseconds! Updating ttl value of ${e.ttl} to ${Us}.`),e.ttl=Us)};function Sd(r,e,t=Wo){let i=new Ds(r,e,t);return i.cache.bind(i)}function Pd(r){new URL(r.slice(0,r.indexOf(",")))}var ii,ri,si,wd,Fd,ni=class{constructor(){l(this,si);l(this,ii,{});l(this,ri,{});a(this,ii,u.assets),a(this,ri,u.webViewAssets)}getURL(e,t){return typeof e=="string"?h(this,si,wd).call(this,e,t??{webView:!1}):h(this,si,Fd).call(this,e,t??{webView:!1})}};ii=new WeakMap,ri=new WeakMap,si=new WeakSet,wd=function(e,t){let i=t.webView?n(this,ri)[e]:n(this,ii)[e];if(i)return i;try{return Pd(e),e}catch{return""}},Fd=function(e,t){let i={},s=[],o=t.webView?n(this,ri):n(this,ii);if(o)for(let d of e)if(o[d])i[d]=o[d];else try{Pd(d),i[d]=d}catch{s.push(d)}else s=e;if(s.length>0)throw new Error(`The following assets were missing from the assets list: ${s.join(", ")}`);return i};var Ke,oi=class{constructor(e){l(this,Ke);a(this,Ke,e)}async get(e){let{messages:t}=await u.kvStorePlugin.Get({keys:[e]},n(this,Ke));try{if(t[e])return JSON.parse(t[e])}catch{return}}async put(e,t){let i={};i[e]=JSON.stringify(t),await u.kvStorePlugin.Put({messages:i},n(this,Ke))}async delete(e){await u.kvStorePlugin.Del({keys:[e]},n(this,Ke))}async list(){let{keys:e}=await u.kvStorePlugin.List({filter:"*"},n(this,Ke));return e}};Ke=new WeakMap;var Ar,ai=class{constructor(e){l(this,Ar);a(this,Ar,e)}async upload(e){let t=await u.mediaPlugin.Upload(e,n(this,Ar));if(!t.mediaId)throw new Error("unable to get mediaId via uploads");return Promise.resolve({mediaId:t.mediaId,mediaUrl:t.mediaUrl})}};Ar=new WeakMap;var Tr,di=class{constructor(e){l(this,Tr);a(this,Tr,e)}async add(e){await u.modLogPlugin.Add(e,n(this,Tr))}};Tr=new WeakMap;var Rr,li=class{constructor(e){l(this,Rr);a(this,Rr,e)}async send(e,t){await u.realtimePlugin.Send({channel:e,data:{msg:t}},n(this,Rr))}};Rr=new WeakMap;import"@devvit/protos";var g,Or,Br,Mr,ui=class{constructor(e){l(this,g);l(this,Or);l(this,Br);l(this,Mr);a(this,g,e),a(this,Or,new Ls(e))}get modMail(){return n(this,Or)}getSubredditById(e){return le.getById(fe(e),n(this,g))}getSubredditInfoById(e){return Ed(e,n(this,g))}getSubredditByName(e){return le.getByName(e,n(this,g))}getSubredditInfoByName(e){return Ad(e,n(this,g))}addSubredditRemovalReason(e,t){return le.addRemovalReason(e,t.title,t.message,n(this,g))}getSubredditRemovalReasons(e){return le.getRemovalReasons(e,n(this,g))}async getCurrentSubredditName(){let e=n(this,g)?.[P.SubredditName]?.values[0];if(e)return e;let t=n(this,g)?.[P.Subreddit]?.values[0],i=await Vo($(t),n(this,g));if(!i)throw new Error("Couldn't get current subreddit's name");return i}async getCurrentSubreddit(){let e=await le.getFromMetadata(n(this,g));if(!e)throw new Error("Couldn't get current subreddit");return e}getPostById(e){return V.getById(fe(e),n(this,g))}submitPost(e){return V.submit(e,n(this,g))}crosspost(e){return V.crosspost(e,n(this,g))}getUserById(e){return C.getById(fe(e),n(this,g))}getUserByUsername(e){return C.getByUsername(e,n(this,g))}async getCurrentUsername(){return n(this,Mr)??a(this,Mr,xd(n(this,g))),n(this,Mr)}async getCurrentUser(){return n(this,Br)??a(this,Br,this.getCurrentUsername().then(e=>e?C.getByUsername(e,n(this,g)):void 0)),n(this,Br)}getAppUser(){return C.getFromMetadata(P.AppUser,n(this,g))}getSnoovatarUrl(e){return C.getSnoovatarUrl(e,n(this,g))}getCommentById(e){return X.getById(fe(e),n(this,g))}getComments(e){return X.getComments(e,n(this,g))}getCommentsByUser(e){return X.getCommentsByUser(e,n(this,g))}submitComment(e){return X.submit({...e,id:fe(e.id)},n(this,g))}getControversialPosts(e){return V.getControversialPosts(e,n(this,g))}getTopPosts(e){return V.getTopPosts(e,n(this,g))}getHotPosts(e){return V.getHotPosts(e,n(this,g))}getNewPosts(e){return V.getNewPosts(e,n(this,g))}getRisingPosts(e){return V.getRisingPosts(e,n(this,g))}getPostsByUser(e){return V.getPostsByUser(e,n(this,g))}getCommentsAndPostsByUser(e){return C.getOverview(e,n(this,g))}getModerationLog(e){return Ns(e,n(this,g))}getApprovedUsers(e){return C.getSubredditUsersByType({type:"contributors",...e},n(this,g))}approveUser(e,t){return C.createRelationship({username:e,subredditName:t,type:"contributor"},n(this,g))}removeUser(e,t){return C.removeRelationship({username:e,subredditName:t,type:"contributor"},n(this,g))}getWikiContributors(e){return C.getSubredditUsersByType({type:"wikicontributors",...e},n(this,g))}addWikiContributor(e,t){return C.createRelationship({username:e,subredditName:t,type:"wikicontributor"},n(this,g))}removeWikiContributor(e,t){return C.removeRelationship({username:e,subredditName:t,type:"wikicontributor"},n(this,g))}getBannedUsers(e){return C.getSubredditUsersByType({type:"banned",...e},n(this,g))}banUser(e){return C.createRelationship({username:e.username,subredditName:e.subredditName,type:"banned",banReason:e.reason,banMessage:e.message,note:e.note,duration:e.duration,banContext:e.context},n(this,g))}unbanUser(e,t){return C.removeRelationship({username:e,subredditName:t,type:"banned"},n(this,g))}getBannedWikiContributors(e){return C.getSubredditUsersByType({type:"wikibanned",...e},n(this,g))}banWikiContributor(e){return C.createRelationship({...e,type:"wikibanned"},n(this,g))}unbanWikiContributor(e,t){return C.removeRelationship({username:e,subredditName:t,type:"wikibanned"},n(this,g))}getModerators(e){return C.getSubredditUsersByType({type:"moderators",...e},n(this,g))}inviteModerator(e){return C.createRelationship({type:"moderator_invite",subredditName:e.subredditName,username:e.username,permissions:e.permissions??[]},n(this,g))}revokeModeratorInvite(e,t){return C.removeRelationship({username:e,subredditName:t,type:"moderator_invite"},n(this,g))}removeModerator(e,t){return C.removeRelationship({type:"moderator",subredditName:t,username:e},n(this,g))}setModeratorPermissions(e,t,i){return C.setModeratorPermissions(e,t,i,n(this,g))}getMutedUsers(e){return C.getSubredditUsersByType({type:"muted",...e},n(this,g))}muteUser(e){return C.createRelationship({...e,type:"muted"},n(this,g))}unmuteUser(e,t){return C.removeRelationship({username:e,subredditName:t,type:"muted"},n(this,g))}getModNotes(e){return ve.get(e,n(this,g))}deleteModNote(e){return ve.delete(e,n(this,g))}addModNote(e){let t={...e,redditId:e.redditId?fe(e.redditId):void 0};return ve.add(t,n(this,g))}addRemovalNote(e){return ve.addRemovalNote(e,n(this,g))}async sendPrivateMessage(e){return Ft.send(e,n(this,g))}async sendPrivateMessageAsSubreddit(e){return Ft.sendAsSubreddit(e,n(this,g))}async approve(e){if(Ge(e))return X.approve(e,n(this,g));if(Pt(e))return V.approve(e,n(this,g));throw new Error("id must start with either t1_ or t3_")}async remove(e,t){if(Ge(e))return X.remove(e,t,n(this,g));if(Pt(e))return V.remove(e,t,n(this,g));throw new Error("id must start with either t1_ or t3_")}async getPostFlairTemplates(e){return ne.getPostFlairTemplates(e,n(this,g))}async getUserFlairTemplates(e){return ne.getUserFlairTemplates(e,n(this,g))}async createPostFlairTemplate(e){return ne.createPostFlairTemplate(e,n(this,g))}async createUserFlairTemplate(e){return ne.createUserFlairTemplate(e,n(this,g))}async editFlairTemplate(e){return ne.editFlairTemplate(e,n(this,g))}async deleteFlairTemplate(e,t){return ne.deleteFlairTemplate(e,t,n(this,g))}async setUserFlair(e){return ce.setUserFlair(e,n(this,g))}async setUserFlairBatch(e,t){return ce.setUserFlairBatch(e,t,n(this,g))}async removeUserFlair(e,t){return ce.removeUserFlair(e,t,n(this,g))}async setPostFlair(e){return ce.setPostFlair(e,n(this,g))}async removePostFlair(e,t){return ce.removePostFlair(e,de(t),n(this,g))}async getWidgets(e){return ie.getWidgets(e,n(this,g))}async deleteWidget(e,t){return ie.delete(e,t,n(this,g))}async addWidget(e){return ie.add(e,n(this,g))}async reorderWidgets(e,t){return ie.reorder(e,t,n(this,g))}async getWikiPage(e,t){return ue.getPage(e,t,n(this,g))}async getWikiPages(e){return ue.getPages(e,n(this,g))}async createWikiPage(e){return ue.createPage(e,n(this,g))}async updateWikiPage(e){return ue.updatePage(e,n(this,g))}getWikiPageRevisions(e){return ue.getPageRevisions(e,n(this,g))}async revertWikiPage(e,t,i){return ue.revertPage(e,t,i,n(this,g))}async getWikiPageSettings(e,t){return ue.getPageSettings(e,t,n(this,g))}async updateWikiPageSettings(e){return ue.updatePageSettings(e,n(this,g))}async addEditorToWikiPage(e,t,i){return ue.addEditor(e,t,i,n(this,g))}async removeEditorFromWikiPage(e,t,i){return ue.removeEditor(e,t,i,n(this,g))}getMessages(e){return Ft.getMessages(e,n(this,g))}markAllMessagesAsRead(){return Ft.markAllAsRead(n(this,g))}report(e,t){return u.redditAPIPlugins.LinksAndComments.Report({reason:t.reason,thingId:e.id,srName:e.subredditName,usernames:e.authorName},n(this,g))}getModQueue(e){return le.aboutLocation({...e,location:"modqueue"},n(this,g))}getReports(e){return le.aboutLocation({...e,location:"reports"},n(this,g))}getSpam(e){return le.aboutLocation({...e,location:"spam"},n(this,g))}getUnmoderated(e){return le.aboutLocation({...e,location:"unmoderated"},n(this,g))}getEdited(e){return le.aboutLocation({...e,location:"edited"},n(this,g))}getVaultByAddress(e){return Od(e,n(this,g))}getVaultByUserId(e){return Bd(fe(e),n(this,g))}getSubredditLeaderboard(e){return Td(e,n(this,g))}getSubredditStyles(e){return Rd(e,n(this,g))}async subscribeToCurrentSubreddit(){let e=await this.getCurrentSubreddit();await u.redditAPIPlugins.Subreddits.Subscribe({action:"sub",actionSource:"",srName:e.name,sr:"",skipInitialDefaults:!0},n(this,g))}async unsubscribeFromCurrentSubreddit(){let e=await this.getCurrentSubreddit();await u.redditAPIPlugins.Subreddits.Subscribe({action:"unsub",actionSource:"",srName:e.name,sr:"",skipInitialDefaults:!1},n(this,g))}};g=new WeakMap,Or=new WeakMap,Br=new WeakMap,Mr=new WeakMap;import{BitfieldOverflowBehavior as Go,RedisKeyScope as Jo}from"@devvit/protos";function _s(r){return r&&typeof r=="object"&&"message"in r&&r.message!==void 0&&typeof r.message=="string"?r.message.includes("redis: nil"):!1}var x,I,E,zo=class{constructor(e,t,i){l(this,x);l(this,I);l(this,E);a(this,x,e),a(this,I,t),a(this,E,i)}async get(e){return await n(this,x).Get({key:e,transactionId:n(this,I)},n(this,E)),this}async multi(){await n(this,x).Multi(n(this,I),n(this,E))}async set(e,t,i){let s;return i?.expiration&&(s=Math.floor((i.expiration.getTime()-Date.now())/1e3),s<1&&(s=1)),await n(this,x).Set({key:e,value:t,nx:i?.nx===!0,xx:i?.xx===!0,expiration:s||0,transactionId:n(this,I)},n(this,E)),this}async del(...e){return await n(this,x).Del({keys:e,transactionId:n(this,I)},n(this,E)),this}async type(e){return await n(this,x).Type({key:e,transactionId:n(this,I)},n(this,E)),this}async exec(){let e=await n(this,x).Exec(n(this,I),n(this,E)),t=[];for(let i of e.response)i.members?t.push(i.members):i.nil!==void 0?t.push(null):i.num!==void 0?t.push(i.num):i.values!==void 0?t.push(i.values.values):i.str!==void 0?t.push(i.str):i.dbl!==void 0&&t.push(i.dbl);return t}async discard(){await n(this,x).Discard(n(this,I),n(this,E))}async watch(...e){return await n(this,x).Watch({keys:e,transactionId:n(this,I)},n(this,E)),this}async unwatch(){return await n(this,x).Unwatch(n(this,I),n(this,E)),this}async getRange(e,t,i){return await n(this,x).GetRange({key:e,start:t,end:i,transactionId:n(this,I)},n(this,E)),this}async setRange(e,t,i){return await n(this,x).SetRange({key:e,offset:t,value:i,transactionId:n(this,I)},n(this,E)),this}async strlen(e){return this.strLen(e)}async strLen(e){return await n(this,x).Strlen({key:e,transactionId:n(this,I)},n(this,E)),this}async mget(e){return this.mGet(e)}async mGet(e){return await n(this,x).MGet({keys:e,transactionId:n(this,I)},n(this,E)),this}async mset(e){return this.mSet(e)}async mSet(e){let t=Object.entries(e).map(([i,s])=>({key:i,value:s}));return await n(this,x).MSet({kv:t,transactionId:n(this,I)},n(this,E)),this}async incrBy(e,t){return await n(this,x).IncrBy({key:e,value:t,transactionId:n(this,I)},n(this,E)),this}async expire(e,t){return await n(this,x).Expire({key:e,seconds:t,transactionId:n(this,I)},n(this,E)),this}async expireTime(e){return await n(this,x).ExpireTime({key:e,transactionId:n(this,I)},n(this,E)),this}async zAdd(e,...t){return await n(this,x).ZAdd({key:e,members:t,transactionId:n(this,I)},n(this,E)),this}async zScore(e,t){return await n(this,x).ZScore({key:{key:e,transactionId:n(this,I)},member:t},n(this,E)),this}async zRank(e,t){return await n(this,x).ZRank({key:{key:e,transactionId:n(this,I)},member:t},n(this,E)),this}async zIncrBy(e,t,i){return await n(this,x).ZIncrBy({key:e,member:t,value:i,transactionId:n(this,I)},n(this,E)),this}async zScan(e,t,i,s){let o={key:e,cursor:t,pattern:i,count:s,transactionId:n(this,I)};return await n(this,x).ZScan(o,n(this,E)),this}async zCard(e){return await n(this,x).ZCard({key:e,transactionId:n(this,I)},n(this,E)),this}async zRange(e,t,i,s){let o={rev:!1,byLex:!1,byScore:!1,offset:0,count:1e3};return s?.reverse&&(o.rev=s.reverse),s?.by==="lex"?o.byLex=!0:s?.by==="score"&&(o.byScore=!0),await n(this,x).ZRange({key:{key:e,transactionId:n(this,I)},start:t+"",stop:i+"",...o},n(this,E)),this}async zRem(e,t){return await n(this,x).ZRem({key:{key:e,transactionId:n(this,I)},members:t},n(this,E)),this}async zRemRangeByLex(e,t,i){return await n(this,x).ZRemRangeByLex({key:{key:e,transactionId:n(this,I)},min:t,max:i},n(this,E)),this}async zRemRangeByRank(e,t,i){return await n(this,x).ZRemRangeByRank({key:{key:e,transactionId:n(this,I)},start:t,stop:i},n(this,E)),this}async zRemRangeByScore(e,t,i){return await n(this,x).ZRemRangeByScore({key:{key:e,transactionId:n(this,I)},min:t,max:i},n(this,E)),this}async hgetall(e){return this.hGetAll(e)}async hGetAll(e){return await n(this,x).HGetAll({key:e,transactionId:n(this,I)},n(this,E)),this}async hget(e,t){return this.hGet(e,t)}async hGet(e,t){return await n(this,x).HGet({key:e,field:t,transactionId:n(this,I)},n(this,E)),this}async hMGet(e,t){return await n(this,x).HMGet({key:e,fields:t,transactionId:n(this,I)},n(this,E)),this}async hset(e,t){return this.hSet(e,t)}async hSet(e,t){let i=Object.entries(t).map(([s,o])=>({field:s,value:o}));return await n(this,x).HSet({key:e,fv:i,transactionId:n(this,I)},n(this,E)),this}async hincrby(e,t,i){return this.hIncrBy(e,t,i)}async hIncrBy(e,t,i){return await n(this,x).HIncrBy({key:e,field:t,value:i,transactionId:n(this,I)},n(this,E)),this}async hdel(e,t){return this.hDel(e,t)}async hDel(e,t){return await n(this,x).HDel({key:e,fields:t,transactionId:n(this,I)},n(this,E)),this}async hscan(e,t,i,s){return this.hScan(e,t,i,s)}async hScan(e,t,i,s){let o={key:e,cursor:t,pattern:i,count:s,transactionId:n(this,I)};return await n(this,x).HScan(o,n(this,E)),this}async hkeys(e){return this.hKeys(e)}async hKeys(e){return await n(this,x).HKeys({key:e,transactionId:n(this,I)},n(this,E)),this}async hlen(e){return this.hLen(e)}async hLen(e){return await n(this,x).HLen({key:e,transactionId:n(this,I)},n(this,E)),this}};x=new WeakMap,I=new WeakMap,E=new WeakMap;var T,ci,qo=class qo{constructor(e,t=void 0,i=Jo.INSTALLATION){l(this,T);l(this,ci);a(this,T,e),a(this,ci,t),this.scope=i,this.global=i===Jo.INSTALLATION?new qo(n(this,T),n(this,ci),Jo.GLOBAL):this}get storage(){return n(this,ci)||u.redisPlugin}async watch(...e){let t=await this.storage.Watch({keys:e},n(this,T));return new zo(this.storage,t,n(this,T))}async get(e){try{let t=await this.storage.Get({key:e,scope:this.scope},{...n(this,T),"throw-redis-nil":{values:["true"]}});return t!==null?t.value??void 0:t}catch(t){if(_s(t))return;throw t}}async set(e,t,i){let s;return i?.expiration&&(s=Math.floor((i.expiration.getTime()-Date.now())/1e3),s<1&&(s=1)),(await this.storage.Set({key:e,value:t,nx:i?.nx===!0&&!i.xx,xx:i?.xx===!0&&!i.nx,expiration:s||0,scope:this.scope},n(this,T))).value}async del(...e){await this.storage.Del({keys:e,scope:this.scope},n(this,T))}async incrBy(e,t){return(await this.storage.IncrBy({key:e,value:t,scope:this.scope},n(this,T))).value}async getRange(e,t,i){let s=await this.storage.GetRange({key:e,start:t,end:i,scope:this.scope},n(this,T));return s!==null?s.value:s}async setRange(e,t,i){return(await this.storage.SetRange({key:e,offset:t,value:i,scope:this.scope},n(this,T))).value}async strlen(e){return this.strLen(e)}async strLen(e){return(await this.storage.Strlen({key:e,scope:this.scope},n(this,T))).value}async expire(e,t){await this.storage.Expire({key:e,seconds:t,scope:this.scope},n(this,T))}async expireTime(e){return(await this.storage.ExpireTime({key:e,scope:this.scope},n(this,T))).value}async zAdd(e,...t){return(await this.storage.ZAdd({key:e,members:t,scope:this.scope},n(this,T))).value}async zRange(e,t,i,s){let o={rev:!1,byLex:!1,byScore:!1,offset:0,count:1e3};return s?.reverse&&(o.rev=s.reverse),s?.by==="lex"?o.byLex=!0:s?.by==="score"?o.byScore=!0:(o.offset=0,o.count=0),(await this.storage.ZRange({key:{key:e},start:t+"",stop:i+"",...o,scope:this.scope},n(this,T))).members}async zRem(e,t){return(await this.storage.ZRem({key:{key:e},members:t,scope:this.scope},n(this,T))).value}async zRemRangeByLex(e,t,i){return(await this.storage.ZRemRangeByLex({key:{key:e},min:t,max:i,scope:this.scope},n(this,T))).value}async zRemRangeByRank(e,t,i){return(await this.storage.ZRemRangeByRank({key:{key:e},start:t,stop:i,scope:this.scope},n(this,T))).value}async zRemRangeByScore(e,t,i){return(await this.storage.ZRemRangeByScore({key:{key:e},min:t,max:i,scope:this.scope},n(this,T))).value}async zScore(e,t){try{let i=await this.storage.ZScore({key:{key:e},member:t,scope:this.scope},{...n(this,T),"throw-redis-nil":{values:["true"]}});return i!==null?i.value:i}catch(i){if(_s(i))return;throw i}}async zRank(e,t){try{let i=await this.storage.ZRank({key:{key:e},member:t,scope:this.scope},{...n(this,T),"throw-redis-nil":{values:["true"]}});return i!==null?i.value:i}catch(i){if(_s(i))return;throw i}}async zIncrBy(e,t,i){let s=await this.storage.ZIncrBy({key:e,member:t,value:i,scope:this.scope},n(this,T));return s!==null?s.value:s}async mget(e){return this.mGet(e)}async mGet(e){let t=await this.storage.MGet({keys:e,scope:this.scope},n(this,T));return t!==null?t.values.map(i=>i||null):t}async mset(e){return this.mSet(e)}async mSet(e){let t=Object.entries(e).map(([i,s])=>({key:i,value:s}));await this.storage.MSet({kv:t,scope:this.scope},n(this,T))}async zCard(e){let t=await this.storage.ZCard({key:e,scope:this.scope},n(this,T));return t!==null?t.value:t}async zScan(e,t,i,s){let o={key:e,cursor:t,pattern:i,count:s,scope:this.scope};return await this.storage.ZScan(o,n(this,T))}async type(e){let t=await this.storage.Type({key:e,scope:this.scope},n(this,T));return t!==null?t.value:t}async hget(e,t){return this.hGet(e,t)}async hGet(e,t){try{let i=await this.storage.HGet({key:e,field:t,scope:this.scope},{...n(this,T),"throw-redis-nil":{values:["true"]}});return i!==null?i.value??void 0:i}catch(i){if(_s(i))return;throw i}}async hMGet(e,t){let i=await this.storage.HMGet({key:e,fields:t,scope:this.scope},n(this,T));return i!==null?i.values.map(s=>s||null):i}async hset(e,t){return this.hSet(e,t)}async hSet(e,t){let i=Object.entries(t).map(([o,d])=>({field:o,value:d}));return(await this.storage.HSet({key:e,fv:i,scope:this.scope},n(this,T))).value}async hgetall(e){return this.hGetAll(e)}async hGetAll(e){let t=await this.storage.HGetAll({key:e,scope:this.scope},n(this,T));return t!==null?t.fieldValues:t}async hdel(e,t){return this.hDel(e,t)}async hDel(e,t){return(await this.storage.HDel({key:e,fields:t,scope:this.scope},n(this,T))).value}async hscan(e,t,i,s){return this.hScan(e,t,i,s)}async hScan(e,t,i,s){let o={key:e,cursor:t,pattern:i,count:s,scope:this.scope};return await this.storage.HScan(o,n(this,T))}async hkeys(e){return this.hKeys(e)}async hKeys(e){let t=await this.storage.HKeys({key:e,scope:this.scope},n(this,T));return t!==null?t.keys:t}async hincrby(e,t,i){return this.hIncrBy(e,t,i)}async hIncrBy(e,t,i){return(await this.storage.HIncrBy({key:e,field:t,value:i,scope:this.scope},n(this,T))).value}async hlen(e){return this.hLen(e)}async hLen(e){return(await this.storage.HLen({key:e,scope:this.scope})).value}async bitfield(e,...t){let i=[];for(let o=0;o<t.length;){let d=t[o],c={};switch(d){case"get":{if(o+2>=t.length)throw Error("bitfield command parse failed; not enough arguments for 'get' command");c.get={encoding:t[o+1],offset:t[o+2].toString()},o+=3;break}case"set":{if(o+3>=t.length)throw Error("bitfield command parse failed; not enough arguments for 'set' command");c.set={encoding:t[o+1],offset:t[o+2].toString(),value:t[o+3].toString()},o+=4;break}case"incrBy":{if(o+3>=t.length)throw Error("bitfield command parse failed; not enough arguments for 'incrBy' command");c.incrBy={encoding:t[o+1],offset:t[o+2].toString(),increment:t[o+3].toString()},o+=4;break}case"overflow":{if(o+1>=t.length)throw Error("bitfield command parse failed; not enough arguments for 'overflow' command");let m=t[o+1].toString();c.overflow={behavior:em(m)},o+=2;break}default:throw Error(`bitfield command parse failed; ${d} unrecognized (must be 'get', 'set', 'incrBy', or 'overflow')`)}i.push(c)}return(await this.storage.Bitfield({key:e,commands:i})).results}};T=new WeakMap,ci=new WeakMap;var mi=qo;function em(r){let e=r.toLowerCase();switch(e){case"wrap":return Go.BITFIELD_OVERFLOW_BEHAVIOR_WRAP;case"sat":return Go.BITFIELD_OVERFLOW_BEHAVIOR_SAT;case"fail":return Go.BITFIELD_OVERFLOW_BEHAVIOR_FAIL;default:throw Error(`unknown bitfield overflow behavior: ${e}`)}}var xt,pi=class{constructor(e){l(this,xt);a(this,xt,e)}async runJob(e){return(await u.schedulerPlugin.Schedule({action:{type:e.name,data:e.data},cron:"cron"in e?e.cron:void 0,when:"runAt"in e?e.runAt:void 0},n(this,xt))).id}async cancelJob(e){await u.schedulerPlugin.Cancel({id:e},n(this,xt))}async listJobs(){return(await u.schedulerPlugin.List({after:new Date(0),before:new Date(Date.now()+31536e7)},n(this,xt))).actions.map(t=>(p(t.request?.action,"Scheduled job is malformed"),"when"in t.request&&t.request.when!=null?{id:t.id,name:t.request.action.type,runAt:t.request.when,data:t.request.action.data}:{id:t.id,name:t.request.action.type,cron:t.request.cron??"",data:t.request.action}))}};xt=new WeakMap;var Ur,gi=class{constructor(e){l(this,Ur);a(this,Ur,e)}async get(e){return(await this.getAll())[e]}async getAll(){let t=await u.settingsPlugin.GetSettings({},n(this,Ur));if(!t.installationSettings)throw new Error("Could not get installation settings");if(!t.appSettings)throw new Error("Could not get app settings");return{...Md(t.installationSettings.settings,u.installationSettings),...Md(t.appSettings.settings,u.appSettings)}}};Ur=new WeakMap;function Md(r,e){let t=Object.keys(r).reduce((i,s)=>(i[s]=Lo(r[s]),i),{});return e&&Ud(t,e),t}function Ud(r,e){for(let t of e)t.type==="group"?Ud(r,t.fields):!(t.name in r)&&"defaultValue"in t&&(r[t.name]=t.defaultValue)}import{EffectType as Hs,ToastAppearance as Dd}from"@devvit/protos";var Ze,hi,Dr,Ws,js=class{constructor(e){l(this,Ze,[]);l(this,hi);l(this,Dr);l(this,Ws,(e,t)=>{let i=t!==void 0?e:"",s=t!==void 0?t:e;n(this,Ze).push({type:Hs.EFFECT_WEB_VIEW,webView:{postMessage:{webViewId:i,app:{message:s}}}})});a(this,hi,e),a(this,Dr,{postMessage:n(this,Ws)})}get webView(){return n(this,Dr)}showForm(e,t){let i=u.formDefinitions.get(e);if(!i&&n(this,hi)){let d=n(this,hi).forms.get(e);d&&(i={form:d,onSubmit:()=>{}})}if(!i)throw new Error("Form does not exist. Make sure you have added it using Devvit.createForm at the root of your app.");let s=i.form instanceof Function?i.form(t??{}):i.form,o={fields:[],id:e,title:s.title,acceptLabel:s.acceptLabel,cancelLabel:s.cancelLabel,shortDescription:s.description};wt(s.fields),o.fields=De(s.fields),n(this,Ze).push({type:Hs.EFFECT_SHOW_FORM,showForm:{form:o}})}showToast(e){let t;e instanceof Object?t={text:e.text,appearance:e.appearance==="success"?Dd.SUCCESS:Dd.NEUTRAL}:t={text:e},n(this,Ze).push({type:Hs.EFFECT_SHOW_TOAST,showToast:{toast:t}})}navigateTo(e){let t;typeof e=="string"?t=new URL(e).toString():t=new URL(e.permalink,"https://www.reddit.com").toString(),n(this,Ze).push({type:Hs.EFFECT_NAVIGATE_TO_URL,navigateToUrl:{url:t}})}get __effects(){return n(this,Ze)}};Ze=new WeakMap,hi=new WeakMap,Dr=new WeakMap,Ws=new WeakMap;function ke({metadata:r,ui:e,hooks:t,reconciler:i}){let s=new di(r),o=new oi(r),d=new mi(r),c=Sd(d,i?i.state:{}),m=new ui(r),b=new pi(r),y=new gi(r),f=e?new js(i):void 0,S=new ai(r),v=new ni,O=new li(r),L=t&&i?ud(i):void 0,B=t&&i?ld(i):void 0,Y=t&&i?dd(i):void 0,Xt=t&&i?ad(i):void 0;return{modLog:s,kvStore:o,redis:d,reddit:m,scheduler:b,settings:y,media:S,assets:v,realtime:O,get useForm(){return Y??(()=>{throw new Error("useForm() is unavailable")})},get cache(){return c??(()=>{throw new Error("cache() is unavailable")})},get useState(){return L??(()=>{throw new Error("useState() is unavailable")})},get useInterval(){return B??(()=>{throw new Error("useInterval() is unavailable")})},get useChannel(){return Xt??(()=>{throw new Error("useChannel() is unavailable")})},get ui(){if(!f)throw new Error("ui client is not available");return f}}}var Nd={name:"@devvit/public-api",version:"0.11.8-dev",license:"BSD-3-Clause",repository:{type:"git",url:"https://developers.reddit.com/"},type:"module",exports:{".":"./dist/index.js","./package.json":"./package.json","./*":"./dist/*"},main:"./dist/index.js",files:["dist/**"],scripts:{build:"yarn build:icon-types && yarn build:semantic-colors && tsc && cp -af devvit.tsconfig.json dist/ && yarn build:types && yarn build:min && yarn build:unmin","build:icon-types":"make-icons src/types/icons.ts","build:min":"esbuild --bundle --sourcemap=linked --target=es2020 --format=esm --metafile=dist/meta.min.json --outfile=dist/public-api.min.js --external:@devvit/protos --minify src/index.ts","build:semantic-colors":"node scripts/make-semantic-colors.js","build:types":"api-extractor run && sed -ne '/declare global {/,$ p' src/devvit/Devvit.ts >> dist/public-api.d.ts","build:unmin":"esbuild --bundle --sourcemap=inline --target=es2020 --format=iife --metafile=dist/meta.json --outfile=dist/public-api.iife.js --global-name=devvitPublicAPI src/index.ts",clean:"rm -rf .turbo api-extractor coverage dist src/devvit/internals/semanticColors.ts src/types/icons.ts || :",clobber:"yarn clean && rm -rf node_modules",dev:"tsc -w","dev:build":"chokidar ./src ../shared-types/dist --command 'yarn build' --ignore './src/types/icons.ts' --ignore './src/devvit/internals/semanticColors.ts'",lint:"redlint .","lint:fix":"yarn lint --fix",prepublishOnly:"publish-package-json",test:"yarn test:unit && yarn test:types && yarn test:size","test:size":"filesize","test:types":"tsc --noEmit","test:unit":"vitest run","test:unit-with-coverage":"vitest run --coverage"},types:"./dist/index.d.ts",dependencies:{"@devvit/protos":"0.11.8-dev","@devvit/shared-types":"0.11.8-dev","base64-js":"1.5.1","clone-deep":"4.0.1",moderndash:"4.0.0"},devDependencies:{"@ampproject/filesize":"4.3.0","@devvit/repo-tools":"0.11.8-dev","@devvit/tsconfig":"0.11.8-dev","@microsoft/api-extractor":"7.41.0","@reddit/faceplate-ui":"18.0.1","@types/clone-deep":"4.0.1","@vitest/coverage-c8":"0.32.0","chokidar-cli":"3.0.0",esbuild:"0.23.0",eslint:"9.11.1",typescript:"5.3.2",vitest:"1.6.0"},publishConfig:{directory:"dist"},filesize:{"dist/public-api.min.js":{gzip:"60 KB",none:"213 KB"}},source:"./src/index.ts"};function se(r,e,t){let i=r[P.Subreddit]?.values[0];p(i,"subreddit is missing from Context");let s=r[P.SubredditName]?.values[0],o=r[P.AppUser]?.values[0],d=r[P.App]?.values[0],c=r[P.Version]?.values[0],m=r[P.User]?.values[0],b=im(r);return{get appAccountId(){return p(o,"appAccountId is missing from Context"),o},subredditId:i,subredditName:s,userId:m,postId:e,commentId:t,appName:d,appVersion:c,debug:b,toJSON(){return{appAccountId:o,appName:d,appVersion:c,subredditId:i,subredditName:s,userId:m,postId:e,commentId:t,debug:b}}}}function im(r){let e={blocks:void 0,emitSnapshots:void 0,emitState:void 0,realtime:void 0,runtime:void 0,surface:void 0,useAsync:void 0,payments:void 0,bootstrap:void 0,webView:void 0},t={};for(let s in e)t[s.toLowerCase()]=s;let i={};for(let s of(r[P.Debug]?.values??[]).join().split(",")){let[o,d]=s.split("=");o&&(o=o.trim(),d=d?.trim(),o.toLowerCase()in t&&(o=t[o.toLowerCase()]),i[o]??(i[o]=d||"true"))}return r[P.Debug]&&console.info(`[api] @devvit/public-api v${Nd.version} ${Object.entries(i).map(([s,o])=>`${s}=${o}`).join(" ")}`),{...i,metadata:r}}function Ld(r){return r.flatMap(e=>e.type==="group"?Ld(e.fields):e)}async function Vs(r,e,t){if(!e)throw new Error("Settings were not defined.");let i={success:!0,errors:{}},s=ze(r.fieldValues),o=Ld(e);return await Promise.all(o.map(async d=>{let c=d.name;if(c&&d.onValidate){let m=s[c],b=d.onValidate,y=Object.assign(ke({metadata:t}),se(t)),f=await b({value:m,isEditing:r.editing},y);f&&(i.success=!1,i.errors[c]=f)}})),rm.fromJSON(i)}async function om(){if(!u.appSettings)throw new Error("App settings were not defined.");return sm.fromJSON({fields:{fields:De(u.appSettings)}})}async function am(r,e){return Vs(r,u.appSettings,e)}function _d(r){r.provides(nm),R("GetAppSettingsFields",om),R("ValidateAppForm",am)}import{CustomPostDefinition as gm,RenderPostResponse as hm}from"@devvit/protos";import{BlockRenderEventType as aa,EffectType as el}from"@devvit/protos";function fi(r){return r.__effects}function Hd(){let r=new Set;return e=>{let t=e,i=1;for(;r.has(t);)t=`${e}.${i++}`;return r.add(t),t}}import{BlockActionType as oa,BlockAvatarBackground as Zd,BlockAvatarFacing as Xd,BlockAvatarSize as Xe,BlockBorderWidth as qs,BlockButtonAppearance as Qe,BlockButtonSize as Qo,BlockGap as $s,BlockHorizontalAlignment as Yo,BlockIconSize as Ks,BlockImageResizeMode as Nr,BlockPadding as Lr,BlockRadius as _r,BlockSpacerShape as ea,BlockSpacerSize as Zs,BlockStackDirection as ta,BlockTextOutline as ia,BlockTextOverflow as ra,BlockTextSize as yi,BlockTextStyle as na,BlockTextWeight as Qd,BlockType as Ae,BlockVerticalAlignment as sa}from"@devvit/protos";var $o={"alienblue-100":"#DCE2FB","alienblue-200":"#B8C5FC","alienblue-25":"#F7F8FD","alienblue-300":"#90A9FD","alienblue-400":"#648EFC","alienblue-50":"#EEF0FB","alienblue-500":"#1870F4","alienblue-600":"#115BCA","alienblue-700":"#0A449B","alienblue-75":"#E6E9FB","alienblue-800":"#0A2F6C","alienblue-900":"#0A1A3F","alienblue-950":"#07102B","berrypurple-100":"#F3DAFB","berrypurple-200":"#EAB3FD","berrypurple-25":"#FBF6FD","berrypurple-300":"#DE8BFF","berrypurple-400":"#CF5FFF","berrypurple-50":"#F8EDFC","berrypurple-500":"#BC0EFF","berrypurple-600":"#9B00D4","berrypurple-700":"#7600A3","berrypurple-75":"#F6E4FB","berrypurple-800":"#520472","berrypurple-900":"#300643","berrypurple-950":"#20042A",black:"#000000","black-opacity-0":"#00000000","black-opacity-10":"#00000019","black-opacity-15":"#00000026","black-opacity-20":"#00000033","black-opacity-25":"#0000003F","black-opacity-33":"#00000054","black-opacity-5":"#0000000C","black-opacity-50":"#0000007F","black-opacity-60":"#00000099","black-opacity-67":"#000000AA","black-opacity-80":"#000000CC","black-opacity-90":"#000000E5","brown-100":"#F1DFCF","brown-200":"#E9BE95","brown-25":"#FBF7F4","brown-300":"#DC9D5D","brown-400":"#BA854E","brown-50":"#F7EFE9","brown-500":"#9A6D3F","brown-600":"#7B5631","brown-700":"#5D4023","brown-75":"#F4E7DC","brown-800":"#3F2C19","brown-900":"#221A11","brown-950":"#15100A","coolgray-100":"#DBE4E9","coolgray-150":"#C9D7DE","coolgray-200":"#B7CAD4","coolgray-25":"#F6F8F9","coolgray-250":"#A4BDCA","coolgray-300":"#97AFBC","coolgray-350":"#8BA2AD","coolgray-400":"#7F949F","coolgray-450":"#748791","coolgray-50":"#EEF1F3","coolgray-500":"#667780","coolgray-525":"#576F76","coolgray-550":"#5C6C74","coolgray-600":"#536168","coolgray-650":"#48545B","coolgray-700":"#3D494E","coolgray-75":"#E5EBEE","coolgray-750":"#333D42","coolgray-800":"#2A3236","coolgray-850":"#21272A","coolgray-900":"#181C1F","coolgray-950":"#0E1113","global-black":{light:"#000000",dark:"#000000"},"global-brand-orangered":{light:"#FF4500",dark:"#FF4500"},"global-white":{light:"#FFFFFF",dark:"#FFFFFF"},"kiwigreen-100":"#A8F5A0","kiwigreen-200":"#58E15B","kiwigreen-25":"#EBFDE7","kiwigreen-300":"#00C61C","kiwigreen-400":"#01A816","kiwigreen-50":"#DDF8D7","kiwigreen-500":"#008A10","kiwigreen-600":"#016E0B","kiwigreen-700":"#005306","kiwigreen-75":"#CAF5C2","kiwigreen-800":"#033902","kiwigreen-900":"#0D2005","kiwigreen-950":"#081404","lightblue-100":"#CAE7FB","lightblue-200":"#87D0FD","lightblue-25":"#F3F9FD","lightblue-300":"#02B9FB","lightblue-400":"#029DD5","lightblue-50":"#E6F3FC","lightblue-500":"#007FAE","lightblue-600":"#01668D","lightblue-700":"#014D6B","lightblue-75":"#D9EDFB","lightblue-800":"#03354B","lightblue-900":"#051E2B","lightblue-950":"#04131A","lime-100":"#B7F28E","lime-200":"#90DA58","lime-25":"#EEFDDC","lime-300":"#6DBF01","lime-400":"#5BA200","lime-50":"#E0F8C8","lime-500":"#4A8500","lime-600":"#3A6A00","lime-700":"#2A5000","lime-75":"#CEF5AD","lime-800":"#1E3702","lime-900":"#151E05","lime-950":"#0D1304","mintgreen-100":"#9BF5D9","mintgreen-200":"#00E2B7","mintgreen-25":"#E7FDF5","mintgreen-300":"#00C29D","mintgreen-400":"#01A484","mintgreen-50":"#D7F8EC","mintgreen-500":"#01876D","mintgreen-600":"#006C56","mintgreen-700":"#015140","mintgreen-75":"#C0F5E3","mintgreen-800":"#00382B","mintgreen-900":"#032019","mintgreen-950":"#03140F","orangered-100":"#FCDBCF","orangered-200":"#FDB498","orangered-25":"#FDF6F4","orangered-300":"#FF895D","orangered-400":"#FF4500","orangered-50":"#FCEEE8","orangered-500":"#D93900","orangered-600":"#AE2C00","orangered-700":"#842100","orangered-75":"#FBE5DC","orangered-800":"#591B02","orangered-900":"#2F1405","orangered-950":"#1C0D04","periwinkle-100":"#E6DFFB","periwinkle-200":"#CDBEFD","periwinkle-25":"#F9F7FD","periwinkle-300":"#B29FFF","periwinkle-400":"#9580FF","periwinkle-50":"#F2EFFC","periwinkle-500":"#6A5CFF","periwinkle-600":"#523DFF","periwinkle-700":"#4001EA","periwinkle-75":"#ECE7FB","periwinkle-800":"#250AA6","periwinkle-900":"#160E5B","periwinkle-950":"#0C083F","poopbrown-100":"#FEEEDD","poopbrown-200":"#F6DDC3","poopbrown-300":"#EECCAA","poopbrown-400":"#CAA075","poopbrown-50":"#FEF7EE","poopbrown-500":"#9A6D3F","poopbrown-600":"#6E4924","poopbrown-700":"#54371A","poopbrown-800":"#3B2510","poopbrown-900":"#29190A","poopbrown-950":"#110B04","puregray-100":"#F2F2F2","puregray-150":"#EBEBEB","puregray-200":"#E4E4E4","puregray-250":"#DDDDDD","puregray-300":"#D6D6D6","puregray-350":"#C3C3C3","puregray-400":"#ACACAC","puregray-450":"#919191","puregray-50":"#F8F8F8","puregray-500":"#767676","puregray-550":"#5C5C5C","puregray-600":"#434343","puregray-650":"#393939","puregray-700":"#303030","puregray-750":"#272727","puregray-800":"#1E1E1E","puregray-850":"#181818","puregray-900":"#131313","puregray-950":"#080808","red-100":"#FBDBD4","red-200":"#FDB3A4","red-25":"#FDF6F5","red-300":"#FF8773","red-400":"#FF4F40","red-50":"#FCEEEA","red-500":"#EB001F","red-600":"#BC0117","red-700":"#90000F","red-75":"#FBE4DF","red-800":"#650405","red-900":"#340F05","red-950":"#1F0B04","sakurapink-100":"#FBD9EB","sakurapink-200":"#FDAEDA","sakurapink-25":"#FDF6F9","sakurapink-300":"#FF7ECA","sakurapink-400":"#FF38BB","sakurapink-50":"#FCEDF4","sakurapink-500":"#DE019F","sakurapink-600":"#B2007F","sakurapink-700":"#880060","sakurapink-75":"#FBE3EF","sakurapink-800":"#5F0443","sakurapink-900":"#380626","sakurapink-950":"#250419",transparent:"transparent",white:"#ffffff","white-opacity-0":"#FFFFFF00","white-opacity-10":"#FFFFFF19","white-opacity-15":"#FFFFFF26","white-opacity-20":"#FFFFFF33","white-opacity-25":"#FFFFFF3F","white-opacity-5":"#FFFFFF0C","white-opacity-50":"#FFFFFF7F","yellow-100":"#FFE284","yellow-200":"#FFBF0B","yellow-25":"#FFF9E0","yellow-300":"#D8A100","yellow-400":"#B78800","yellow-50":"#FFF3C0","yellow-500":"#977000","yellow-600":"#785800","yellow-700":"#5B4200","yellow-75":"#FFEAA2","yellow-800":"#3F2D00","yellow-900":"#231A03","yellow-950":"#161003","yelloworange-100":"#FCDCC8","yelloworange-200":"#FDB586","yelloworange-25":"#FDF7F3","yelloworange-300":"#FF8A35","yelloworange-400":"#E46C00","yelloworange-50":"#FCEEE6","yelloworange-500":"#BD5800","yelloworange-600":"#974500","yelloworange-700":"#733300","yelloworange-75":"#FBE5D7","yelloworange-800":"#4E2402","yelloworange-900":"#2A1705","yelloworange-950":"#1A0E04","action-downvote":{light:"#6A5CFF",dark:"#6A5CFF"},"action-upvote":{light:"#D93900",dark:"#D93900"},"ai-background-weaker":{light:"#E7FDF5",dark:"#00382B"},"ai-plain":{light:"#006C56",dark:"#01A484"},"ai-plain-hover":{light:"#015140",dark:"#00C29D"},"alert-caution":{light:"#977000",dark:"#977000"},"avatar-gradient":{light:"",dark:""},"brand-background":{light:"#D93900",dark:"#D93900"},"brand-background-hover":{light:"#AE2C00",dark:"#AE2C00"},"brand-gradient-active":{light:"",dark:""},"brand-gradient-active-highlight":{light:"",dark:""},"brand-gradient-default":{light:"",dark:""},"brand-gradient-default-highlight":{light:"",dark:""},"brand-gradient-hover":{light:"",dark:""},"brand-gradient-hover-highlight":{light:"",dark:""},"brand-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"category-live":{light:"#D93900",dark:"#D93900"},"category-nsfw":{light:"#DE019F",dark:"#DE019F"},"category-spoiler":{light:"#131313",dark:"#F2F2F2"},"caution-background":{light:"#FFBF0B",dark:"#D8A100"},"caution-background-hover":{light:"#D8A100",dark:"#FFBF0B"},"caution-onBackground":{light:"#000000",dark:"#000000"},"caution-plain":{light:"#785800",dark:"#FFBF0B"},"caution-plain-hover":{light:"#5B4200",dark:"#FFE284"},"danger-background":{light:"#EB001F",dark:"#BC0117"},"danger-background-disabled":{light:"#FDB3A4",dark:"#340F05"},"danger-background-hover":{light:"#BC0117",dark:"#EB001F"},"danger-background-weaker":{light:"#FBDBD4",dark:"#650405"},"danger-content":{light:"#BC0117",dark:"#FF4F40"},"danger-content-default":{light:"#ffffff",dark:"#ffffff"},"danger-content-hover":{light:"#90000F",dark:"#FF8773"},"danger-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"danger-plain":{light:"#BC0117",dark:"#FF8773"},"danger-plain-hover":{light:"#90000F",dark:"#FDB3A4"},"downvote-background":{light:"#6A5CFF",dark:"#6A5CFF"},"downvote-background-disabled":{light:"#6a5cff4d",dark:"#6a5cff4d"},"downvote-background-hover":{light:"#523DFF",dark:"#523DFF"},"downvote-content":{light:"#523DFF",dark:"#9580FF"},"downvote-content-weak":{light:"#6A5CFF",dark:"#6A5CFF"},"downvote-disabled":{light:"#523DFF4c",dark:"#9580FF4c"},"downvote-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"downvote-onStrongScrim":{light:"#B29FFF",dark:"#B29FFF"},"downvote-onStrongScrim-disabled":{light:"#b29fff4d",dark:"#b29fff4d"},"downvote-onStrongScrim-weaker":{light:"#9580FF",dark:"#9580FF"},"downvote-plain":{light:"#523DFF",dark:"#9580FF"},"downvote-plain-disabled":{light:"#523dff4d",dark:"#9580ff4d"},"downvote-plain-weaker":{light:"#6A5CFF",dark:"#6A5CFF"},"elevation-large1":{light:"#0000003F",dark:"#0000007F"},"elevation-large2":{light:"#00000026",dark:"#00000033"},"elevation-medium1":{light:"#0000003F",dark:"#0000007F"},"elevation-medium2":{light:"#00000019",dark:"#00000033"},"elevation-small":{light:"#00000026",dark:"#00000054"},"elevation-xsmall":{light:"#0000003F",dark:"#000000AA"},favorite:{light:"#977000",dark:"#B78800"},"global-admin":{light:"#D93900",dark:"#D93900"},"global-alienblue":{light:"#1870F4",dark:"#1870F4"},"global-darkblue":{light:"#2A3236",dark:"#2A3236"},"global-focus":{light:"#029DD5",dark:"#007FAE"},"global-gold":{light:"#B78800",dark:"#D8A100"},"global-moderator":{light:"#008A10",dark:"#008A10"},"global-nsfw":{light:"#DE019F",dark:"#DE019F"},"global-offline":{light:"#667780",dark:"#667780"},"global-online":{light:"#00C61C",dark:"#00C61C"},"global-orangered":{light:"#FF4500",dark:"#FF4500"},"global-stars":{light:"#977000",dark:"#D8A100"},"gradient-media":{light:"",dark:""},"gradient-media-strong":{light:"",dark:""},"identity-admin":{light:"#D93900",dark:"#D93900"},"identity-coins":{light:"#B78800",dark:"#B78800"},"identity-moderator":{light:"#008A10",dark:"#008A10"},"identity-self":{light:"#01876D",dark:"#01876D"},"interactive-background-disabled":{light:"#0000000C",dark:"#FFFFFF0C"},"interactive-content-disabled":{light:"#0000003F",dark:"#FFFFFF3F"},"interactive-focused":{light:"#007FAE",dark:"#007FAE"},"interactive-pressed":{light:"#00000026",dark:"#FFFFFF26"},"inverted-interactive-background-disabled":{light:"#FFFFFF0C",dark:"#0000000C"},"inverted-interactive-content-disabled":{light:"#FFFFFF3F",dark:"#0000003F"},"inverted-interactive-pressed":{light:"#FFFFFF26",dark:"#00000026"},"inverted-neutral-background":{light:"#0E1113",dark:"#FFFFFF"},"inverted-neutral-background-hover":{light:"#181C1F",dark:"#F6F8F9"},"inverted-neutral-border":{light:"#FFFFFF33",dark:"#00000033"},"inverted-neutral-content":{light:"#B7CAD4",dark:"#333D42"},"inverted-neutral-content-strong":{light:"#EEF1F3",dark:"#181C1F"},"inverted-secondary-background":{light:"#2A3236",dark:"#E5EBEE"},"inverted-secondary-background-hover":{light:"#333D42",dark:"#DBE4E9"},"inverted-secondary-background-selected":{light:"#3D494E",dark:"#C9D7DE"},"inverted-secondary-onBackground":{light:"#FFFFFF",dark:"#000000"},"inverted-secondary-plain":{light:"#DBE4E9",dark:"#181C1F"},"inverted-secondary-plain-hover":{light:"#FFFFFF",dark:"#000000"},"media-background":{light:"#00000099",dark:"#00000099"},"media-background-hover":{light:"#000000cc",dark:"#000000cc"},"media-background-selected":{light:"#000000cc",dark:"#000000cc"},"media-border-selected":{light:"#FFFFFF",dark:"#FFFFFF"},"media-border-weak":{light:"#FFFFFF19",dark:"#FFFFFF19"},"media-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"media-onBackground-disabled":{light:"#FFFFFF3F",dark:"#FFFFFF3F"},"media-onBackground-weak":{light:"#E5EBEE",dark:"#E5EBEE"},"media-onbackground":{light:"#ffffff",dark:"#ffffff"},"media-onbackground-disabled":{light:"#ffffff3f",dark:"#ffffff3f"},"media-onbackground-weak":{light:"#B7CAD4",dark:"#B7CAD4"},"neutral-background":{light:"#FFFFFF",dark:"#0E1113"},"neutral-background-container":{light:"#F6F8F9",dark:"#181C1F"},"neutral-background-container-hover":{light:"#EEF1F3",dark:"#21272A"},"neutral-background-container-strong":{light:"#EEF1F3",dark:"#21272A"},"neutral-background-container-strong-hover":{light:"#E5EBEE",dark:"#2A3236"},"neutral-background-gilded":{light:"#FFF9E0",dark:"#181C1F"},"neutral-background-gilded-hover":{light:"#FFF3C0",dark:"#21272A"},"neutral-background-hover":{light:"#F6F8F9",dark:"#181C1F"},"neutral-background-medium":{light:"#F8F8F8",dark:"#131313"},"neutral-background-pinned":{light:"#FFFFFF",dark:"#0E1113"},"neutral-background-selected":{light:"#E5EBEE",dark:"#2A3236"},"neutral-background-strong":{light:"#FFFFFF",dark:"#181C1F"},"neutral-background-strong-hover":{light:"#F6F8F9",dark:"#21272A"},"neutral-background-weak":{light:"#F6F8F9",dark:"#000000"},"neutral-background-weak-hover":{light:"#EEF1F3",dark:"#0E1113"},"neutral-border":{light:"#00000033",dark:"#FFFFFF33"},"neutral-border-medium":{light:"#0000007F",dark:"#FFFFFF7F"},"neutral-border-strong":{light:"#181C1F",dark:"#F6F8F9"},"neutral-border-weak":{light:"#00000019",dark:"#FFFFFF19"},"neutral-content":{light:"#333D42",dark:"#B7CAD4"},"neutral-content-disabled":{light:"#D6D6D6",dark:"#303030"},"neutral-content-strong":{light:"#181C1F",dark:"#EEF1F3"},"neutral-content-weak":{light:"#5C6C74",dark:"#8BA2AD"},offline:{light:"#767676",dark:"#767676"},online:{light:"#01A816",dark:"#01A816"},"opacity-08":{light:"#13131314",dark:"#13131314"},"opacity-50":{light:"#0000007f",dark:"#F2F2F27f"},"opacity-highlight":{light:"",dark:""},pizzaRed:{light:"#ef5350",dark:"#c62828"},primary:{light:"#115BCA",dark:"#648EFC"},"primary-background":{light:"#0A449B",dark:"#115BCA"},"primary-background-hover":{light:"#0A2F6C",dark:"#1870F4"},"primary-background-selected":{light:"#0A1A3F",dark:"#648EFC"},"primary-border":{light:"#0A449B",dark:"#648EFC"},"primary-border-hover":{light:"#0A2F6C",dark:"#90A9FD"},"primary-hover":{light:"#0A449B",dark:"#90A9FD"},"primary-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"primary-onBackground-selected":{light:"#FFFFFF",dark:"#000000"},"primary-plain":{light:"#0A449B",dark:"#648EFC"},"primary-plain-hover":{light:"#0A2F6C",dark:"#90A9FD"},"primary-plain-visited":{light:"#7600A3",dark:"#CF5FFF"},"primary-visited":{light:"#9B00D4",dark:"#CF5FFF"},scrim:{light:"#00000099",dark:"#00000099"},"scrim-background":{light:"#00000099",dark:"#00000099"},"scrim-background-strong":{light:"#000000CC",dark:"#000000CC"},"scrim-gradient":{light:"",dark:""},"scrim-strong":{light:"#000000cc",dark:"#000000cc"},secondary:{light:"#21272A",dark:"#DBE4E9"},"secondary-background":{light:"#E5EBEE",dark:"#2A3236"},"secondary-background-hover":{light:"#DBE4E9",dark:"#333D42"},"secondary-background-selected":{light:"#C9D7DE",dark:"#3D494E"},"secondary-hover":{light:"#000000",dark:"#ffffff"},"secondary-onBackground":{light:"#000000",dark:"#FFFFFF"},"secondary-plain":{light:"#181C1F",dark:"#DBE4E9"},"secondary-plain-hover":{light:"#000000",dark:"#FFFFFF"},"secondary-plain-weak":{light:"#5C6C74",dark:"#8BA2AD"},"secondary-weak":{light:"#576F76",dark:"#748791"},"success-background":{light:"#008A10",dark:"#016E0B"},"success-background-hover":{light:"#016E0B",dark:"#008A10"},"success-content":{light:"#016E0B",dark:"#01A816"},"success-hover":{light:"#005306",dark:"#00C61C"},"success-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"success-plain":{light:"#016E0B",dark:"#00C61C"},"success-plain-hover":{light:"#005306",dark:"#58E15B"},"tone-1":{light:"#131313",dark:"#F2F2F2"},"tone-2":{light:"#434343",dark:"#ACACAC"},"tone-3":{light:"#ACACAC",dark:"#434343"},"tone-4":{light:"#E4E4E4",dark:"#303030"},"tone-5":{light:"#F2F2F2",dark:"#1E1E1E"},"tone-6":{light:"#F8F8F8",dark:"#131313"},"tone-7":{light:"#ffffff",dark:"#080808"},"transparent-background-hover":{light:"#74879119",dark:"#66778019"},"ui-canvas":{light:"#F2F2F2",dark:"#080808"},"ui-modalbackground":{light:"#FFFFFF",dark:"#181C1F"},"upvote-background":{light:"#D93900",dark:"#D93900"},"upvote-background-disabled":{light:"#d939004d",dark:"#d939004d"},"upvote-background-hover":{light:"#AE2C00",dark:"#AE2C00"},"upvote-content":{light:"#AE2C00",dark:"#FF4500"},"upvote-content-weak":{light:"#FF4500",dark:"#FF4500"},"upvote-disabled":{light:"#AE2C004c",dark:"#FF45004c"},"upvote-onBackground":{light:"#FFFFFF",dark:"#FFFFFF"},"upvote-onStrongScrim":{light:"#FF895D",dark:"#FF895D"},"upvote-onStrongScrim-disabled":{light:"#ff895d4d",dark:"#ff895d4d"},"upvote-onStrongScrim-weaker":{light:"#FF4500",dark:"#FF4500"},"upvote-plain":{light:"#AE2C00",dark:"#FF895D"},"upvote-plain-disabled":{light:"#ae2c004d",dark:"#ff895d4d"},"upvote-plain-weaker":{light:"#FF4500",dark:"#FF4500"},"warning-background":{light:"#B78800",dark:"#B78800"},"warning-background-hover":{light:"#977000",dark:"#D8A100"},"warning-content":{light:"#785800",dark:"#B78800"},"warning-content-hover":{light:"#5B4200",dark:"#D8A100"},"warning-onBackground":{light:"#000000",dark:"#000000"}};var jd={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",rebeccapurple:"#663399",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",transparent:"#FFFFFF00",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"},Wd=r=>!!r.match(/^(#[0-9a-fA-F]{3,8}).*/),Vd=r=>r in $o,Ko=r=>r in jd,Gd=r=>!!r.match(/^rgba?\(.*/),Jd=r=>!!r.match(/^hsla?\(.*/),zd=(r,e="light")=>{if(Ko(r))return Gs(r);let i=$o[r];return typeof i=="string"?i:i[e]},Gs=r=>jd[r]??r,qd=r=>{let[e,t,i,s]=r.replace(/^rgba?\(|\s+|\)$/g,"").split(",");if(!e||!t||!i)return r;let d=[...[e,t,i].map(m=>parseFloat(m))];if(s){let m=parseFloat(s),b=Math.round(m*255);d.push(b)}return`#${d.map(m=>m.toString(16).padStart(2,"0")).join("")}`};import{BlockStackDirection as Js}from"@devvit/protos";var Zo={stackParentLayout:{hasHeight:!0,hasWidth:!0,direction:Js.UNRECOGNIZED,alignment:void 0}};function Kd(r,e,t){if(!e)return{hasHeight:!1,hasWidth:!1};let{growDirection:i,stretchDirection:s}=dm(r?.grow,e.direction,e.alignment),o=t?.height?.value?.value||t?.height?.min?.value||$d(2,i,s,e.hasHeight),d=t?.width?.value?.value||t?.width?.min?.value||$d(1,i,s,e.hasWidth);return{hasHeight:!!o,hasWidth:!!d}}function $d(r,e,t,i){return e===r&&i||t===r&&i}function dm(r,e,t){let i=e===Js.STACK_VERTICAL||e===Js.UNRECOGNIZED,s=e===Js.STACK_HORIZONTAL,o=0;s&&r?o=1:i&&r&&(o=2);let d=t===void 0||t.horizontal===void 0,c=t===void 0||t.vertical===void 0,m=s?!!c:i?!!d:!1,b=0;return s&&m?b=2:i&&m&&(b=1),{growDirection:o,stretchDirection:b}}import{BlockSizeUnit as It,BlockStackDirection as zs}from"@devvit/protos";function bi(r){if(r==null)return;if(typeof r=="number")return{value:r,unit:It.SIZE_UNIT_PERCENT};let e=r.match(/^(\d+(?:\.\d+)?)(px|%)?$/);if(e==null)return;let t=It.SIZE_UNIT_PERCENT;return e.at(2)==="px"&&(t=It.SIZE_UNIT_PIXELS),{value:Number.parseFloat(e[1]),unit:t}}function lm(r,e){return(r.width?.value?.unit===It.SIZE_UNIT_PERCENT||r.width?.min?.unit===It.SIZE_UNIT_PERCENT)&&(e.direction===zs.STACK_HORIZONTAL||e.direction===zs.STACK_DEPTH)&&(e.hasWidth||(r.width=void 0)),(r.height?.value?.unit===It.SIZE_UNIT_PERCENT||r.height?.min?.unit===It.SIZE_UNIT_PERCENT)&&(e.direction===zs.STACK_VERTICAL||e.direction===zs.STACK_DEPTH)&&(e.hasHeight||(r.height=void 0)),r}function Xo(r,e){if(r){let t=r.width!=null||r.minWidth!=null||r.maxWidth!=null,i=r.height!=null||r.minHeight!=null||r.maxHeight!=null;if(t||i||r.grow!=null){let s={width:t?{value:bi(r.width),min:bi(r.minWidth),max:bi(r.maxWidth)}:void 0,height:i?{value:bi(r.height),min:bi(r.minHeight),max:bi(r.maxHeight)}:void 0,grow:r.grow};return e.stackParentLayout&&(s=lm(s,e.stackParentLayout)),s}}}var Yd="data-",um=new Set(["onPress","onMessage"]),cm=new Map([["onPress",oa.ACTION_CLICK],["onMessage",oa.ACTION_WEBVIEW]]),Hr,vi=class{constructor(e=()=>{}){l(this,Hr);a(this,Hr,e)}createBlocksElementOrThrow({type:e,props:t,children:i}){let s=this.createBlocksElement({type:e,props:t,children:i},Zo);if(!s)throw new Error(`Could not create block of type ${e}`);return s}createBlocksElement({type:e,props:t,children:i},s){switch(e){case"blocks":return this.makeRoot(t,...i);case"hstack":return this.makeHStack(t,s,...i);case"vstack":return this.makeVStack(t,s,...i);case"zstack":return this.makeZStack(t,s,...i);case"text":return this.makeText(t,s,...i);case"button":return this.makeButton(t,s,...i);case"image":return this.makeImage(t,s);case"spacer":return this.makeSpacer(t,s);case"icon":return this.makeIcon(t,s);case"avatar":return this.makeAvatar(t,s);case"webview":return this.makeWebView(t,s);case"__fragment":throw new Error("root fragment is not supported - use 'blocks' instead")}}makeRootHeight(e){switch(e){case"regular":return 320;case"tall":return 512}}makeBlockPadding(e){switch(e){case"none":return Lr.PADDING_NONE;case"xsmall":return Lr.PADDING_XSMALL;case"small":return Lr.PADDING_SMALL;case"medium":return Lr.PADDING_MEDIUM;case"large":return Lr.PADDING_LARGE}}makeBlockRadius(e){switch(e){case"none":return _r.RADIUS_NONE;case"small":return _r.RADIUS_SMALL;case"medium":return _r.RADIUS_MEDIUM;case"large":return _r.RADIUS_LARGE;case"full":return _r.RADIUS_FULL}}makeBlockGap(e){switch(e){case"none":return $s.GAP_NONE;case"small":return $s.GAP_SMALL;case"medium":return $s.GAP_MEDIUM;case"large":return $s.GAP_LARGE}}makeBlockAlignment(e){if(e===void 0)return;let t,i;if(e.includes("top")?t=sa.ALIGN_TOP:e.includes("middle")?t=sa.ALIGN_MIDDLE:e.includes("bottom")&&(t=sa.ALIGN_BOTTOM),e.includes("start")?i=Yo.ALIGN_START:e.includes("center")?i=Yo.ALIGN_CENTER:e.includes("end")&&(i=Yo.ALIGN_END),t!==void 0||i!==void 0)return{vertical:t,horizontal:i}}makeBlockBorder(e,t,i,s){if(!e&&!t)return;let o;switch(e){case"none":o=qs.BORDER_WIDTH_NONE;break;case"thin":o=qs.BORDER_WIDTH_THIN;break;case"thick":o=qs.BORDER_WIDTH_THICK;break;default:o=qs.BORDER_WIDTH_THIN;break}let d=t??"neutral-border-weak",c=this.getThemedColors(d,i,s);return{width:o,color:c?.light,colors:c}}makeBlockTextSize(e){switch(e){case"xsmall":return yi.TEXT_SIZE_XSMALL;case"small":return yi.TEXT_SIZE_SMALL;case"medium":return yi.TEXT_SIZE_MEDIUM;case"large":return yi.TEXT_SIZE_LARGE;case"xlarge":return yi.TEXT_SIZE_XLARGE;case"xxlarge":return yi.TEXT_SIZE_XXLARGE}}makeBlockTextStyle(e){switch(e){case"body":return na.TEXT_STYLE_BODY;case"metadata":return na.TEXT_STYLE_METADATA;case"heading":return na.TEXT_STYLE_HEADING}}makeBlockTextOutline(e){switch(e){case"none":return ia.TEXT_OUTLINE_NONE;case"thin":return ia.TEXT_OUTLINE_THIN;case"thick":return ia.TEXT_OUTLINE_THICK}}makeBlockTextWeight(e){switch(e){case"regular":return Qd.TEXT_WEIGHT_REGULAR;case"bold":return Qd.TEXT_WEIGHT_BOLD}}makeBlockTextOverflow(e){switch(e){case"clip":return ra.TEXT_OVERFLOW_CLIP;case"ellipsis":return ra.TEXT_OVERFLOW_ELLIPSE}return ra.TEXT_OVERFLOW_ELLIPSE}makeBlockButtonAppearance(e){switch(e){case"secondary":return Qe.BUTTON_APPEARANCE_SECONDARY;case"primary":return Qe.BUTTON_APPEARANCE_PRIMARY;case"plain":return Qe.BUTTON_APPEARANCE_PLAIN;case"bordered":return Qe.BUTTON_APPEARANCE_BORDERED;case"media":return Qe.BUTTON_APPEARANCE_MEDIA;case"destructive":return Qe.BUTTON_APPEARANCE_DESTRUCTIVE;case"caution":return Qe.BUTTON_APPEARANCE_CAUTION;case"success":return Qe.BUTTON_APPEARANCE_SUCCESS}}makeBlockButtonSize(e){switch(e){case"small":return Qo.BUTTON_SIZE_SMALL;case"medium":return Qo.BUTTON_SIZE_MEDIUM;case"large":return Qo.BUTTON_SIZE_LARGE}}makeBlockImageResizeMode(e){switch(e){case"none":return Nr.IMAGE_RESIZE_NONE;case"fit":return Nr.IMAGE_RESIZE_FIT;case"fill":return Nr.IMAGE_RESIZE_FILL;case"cover":return Nr.IMAGE_RESIZE_COVER;case"scale-down":return Nr.IMAGE_RESIZE_SCALE_DOWN}}makeBlockSpacerSize(e){switch(e){case"xsmall":return Zs.SPACER_XSMALL;case"small":return Zs.SPACER_SMALL;case"medium":return Zs.SPACER_MEDIUM;case"large":return Zs.SPACER_LARGE}}makeBlockSpacerShape(e){switch(e){case"invisible":return ea.SPACER_INVISIBLE;case"thin":return ea.SPACER_THIN;case"square":return ea.SPACER_SQUARE}}makeBlockIconSize(e){switch(e){case"xsmall":return Ks.ICON_SIZE_XSMALL;case"small":return Ks.ICON_SIZE_SMALL;case"medium":return Ks.ICON_SIZE_MEDIUM;case"large":return Ks.ICON_SIZE_LARGE}}makeBlockAvatarSize(e){switch(e){case"xxsmall":return Xe.AVATAR_SIZE_XXSMALL;case"xsmall":return Xe.AVATAR_SIZE_XSMALL;case"small":return Xe.AVATAR_SIZE_SMALL;case"medium":return Xe.AVATAR_SIZE_MEDIUM;case"large":return Xe.AVATAR_SIZE_LARGE;case"xlarge":return Xe.AVATAR_SIZE_XXLARGE;case"xxlarge":return Xe.AVATAR_SIZE_XXLARGE;case"xxxlarge":return Xe.AVATAR_SIZE_XXXLARGE}}makeBlockAvatarFacing(e){switch(e){case"left":return Xd.AVATAR_FACING_LEFT;case"right":return Xd.AVATAR_FACING_RIGHT}}makeBlockAvatarBackground(e){switch(e){case"dark":return Zd.AVATAR_BG_DARK;case"light":return Zd.AVATAR_BG_LIGHT}}getDataSet(e){return Object.keys(e).filter(t=>t.startsWith(Yd)).reduce((t,i)=>(t[i.substring(Yd.length)]=e[i],t),{})}makeActions(e,t){let i=[],s=this.getDataSet(t);return um.forEach(o=>{if(o in t){let d=t[o];i.push({type:cm.get(o)??oa.UNRECOGNIZED,id:d.toString(),data:s})}}),i}blockColorToHex(e,t="light"){if(e)return e=e.toLowerCase(),Wd(e)?e:Vd(e)?zd(e,t):Ko(e)?Gs(e):Gd(e)?qd(e):Jd(e)?e:(console.warn(`Could not parse color: ${e}.`),Gs("red"))}childrenToBlocks(e,t){return e.flatMap(i=>(typeof i!="string"?this.createBlocksElement(i,t):void 0)??[])}getThemedColors(e,t,i){let s=this.blockColorToHex(t,"light"),o=this.blockColorToHex(i,"dark"),d=[];if(e&&(!s||!o)){let c=Array.from(e?.matchAll(/[\w#-]+(?:\([\w\t ,.#-]+\))?/g)??[]);d.push(...c.map(m=>m[0]))}return s||(s=this.blockColorToHex(d?.at(0),"light")),o||(o=this.blockColorToHex(d?.at(1)??d?.at(0),"dark")),s||o?{light:s,dark:o}:void 0}parsePixels(e){return typeof e=="string"?Number(e.slice(0,-2)):e}resolveAssetUrl(e,t){return n(this,Hr).call(this)?.getURL(e,t)??e}childrenToString(e){return e.map(t=>t.toString()).join("")}makeRoot(e,...t){return this.wrapRoot(e,this.childrenToBlocks(t,Zo))}wrapRoot(e,t){return this.makeBlock(Ae.BLOCK_ROOT,{},{},{rootConfig:{children:t,height:this.makeRootHeight(u.customPostType?.height??e?.height??"regular")}})}makeStackBlock(e,t,i,s){let o=this.getThemedColors(t?.backgroundColor,t?.lightBackgroundColor,t?.darkBackgroundColor),d=this.makeBlockAlignment(t?.alignment),c=Xo(t,i),m=Kd(t,i.stackParentLayout,c);return this.makeBlock(Ae.BLOCK_STACK,t,i,{stackConfig:{alignment:d,backgroundColor:o?.light,backgroundColors:o,border:this.makeBlockBorder(t?.border,t?.borderColor,t?.lightBorderColor,t?.darkBorderColor),children:this.childrenToBlocks(s,{stackParentLayout:{...m,direction:e,alignment:d}}),cornerRadius:this.makeBlockRadius(t?.cornerRadius),direction:e,gap:this.makeBlockGap(t?.gap),padding:this.makeBlockPadding(t?.padding),reverse:t?.reverse}})}makeHStack(e,t,...i){return this.makeStackBlock(ta.STACK_HORIZONTAL,e,t,i)}makeVStack(e,t,...i){return this.makeStackBlock(ta.STACK_VERTICAL,e,t,i)}makeZStack(e,t,...i){return this.makeStackBlock(ta.STACK_DEPTH,e,t,i)}makeText(e,t,...i){let s=this.getThemedColors(e?.color,e?.lightColor,e?.darkColor);return this.makeBlock(Ae.BLOCK_TEXT,e,t,{textConfig:{alignment:this.makeBlockAlignment(e?.alignment),color:s?.light,colors:s,outline:this.makeBlockTextOutline(e?.outline),size:this.makeBlockTextSize(e?.size),style:this.makeBlockTextStyle(e?.style),text:this.childrenToString(i),weight:this.makeBlockTextWeight(e?.weight),selectable:e?.selectable,wrap:e?.wrap,overflow:this.makeBlockTextOverflow(e?.overflow)}})}makeButton(e,t,...i){let s=this.getThemedColors(e?.textColor,e?.lightTextColor,e?.darkTextColor);return this.makeBlock(Ae.BLOCK_BUTTON,e,t,{buttonConfig:{buttonAppearance:this.makeBlockButtonAppearance(e?.appearance),icon:e?.icon,buttonSize:this.makeBlockButtonSize(e?.size),text:this.childrenToString(i),textColor:s?.light,textColors:s,disabled:e?.disabled}})}makeImage(e,t){return e&&this.makeBlock(Ae.BLOCK_IMAGE,e,t,{imageConfig:{description:e?.description,resizeMode:this.makeBlockImageResizeMode(e.resizeMode),url:this.resolveAssetUrl(e.url),width:this.parsePixels(e.imageWidth),height:this.parsePixels(e.imageHeight)}})}makeSpacer(e,t){return this.makeBlock(Ae.BLOCK_SPACER,e,t,{spacerConfig:{size:this.makeBlockSpacerSize(e?.size),shape:this.makeBlockSpacerShape(e?.shape)}})}makeIcon(e,t){let i=this.getThemedColors(e?.color,e?.lightColor,e?.darkColor);return e&&this.makeBlock(Ae.BLOCK_ICON,e,t,{iconConfig:{icon:e.name,color:i?.light,colors:i,size:this.makeBlockIconSize(e.size)}})}makeAvatar(e,t){return e&&this.makeBlock(Ae.BLOCK_AVATAR,e,t,{avatarConfig:{thingId:e.thingId,size:this.makeBlockAvatarSize(e.size),facing:this.makeBlockAvatarFacing(e.facing),background:this.makeBlockAvatarBackground(e.background)}})}makeWebView(e,t){return e&&this.makeBlock(Ae.BLOCK_WEBVIEW,e,t,{webviewConfig:{url:this.resolveAssetUrl(e.url,{webView:!0}),state:e.state}})}makeBlock(e,t,i,s){return{type:e,sizes:Xo(t,i),config:s,actions:(t&&this.makeActions(e,t))??[],id:t?.id,key:t?.key}}ensureRootBlock(e){let t;if(e.type===Ae.BLOCK_ROOT?(e.config?.rootConfig&&u.customPostType?.height&&(e.config.rootConfig.height=this.makeRootHeight(u.customPostType?.height)),t=e):t=this.wrapRoot(void 0,[e]),!t)throw new Error("Could not create root block");return t}};Hr=new WeakMap;function tl(r){if(typeof r=="string")throw new Error("Root element cannot be a string")}var il=r=>{let e="",t=r.props?Object.keys(r.props).map(i=>i==="onPress"?"":`${i}="${r.props[i]}"`).join(" "):"";e+=`<${r.type}${t?" "+t:""}>`;for(let i of r.children)typeof i=="string"?e+=i:e+=il(i);return e+=`</${r.type}>`,e};function mm(r){return" ".repeat(r)}function pm(r){let e="",t=0,i=r.split(/>\s*</);for(let s=0;s<i.length;s++){let o=i[s];s===0&&(o=o.trim()),s===i.length-1&&(o=o.trim());let d=o.charAt(0)==="/";d&&t--,e+=mm(t),s!==0&&(e+="<"),e+=o,s!==i.length-1&&(e+=`>
|
|
2
|
+
`),!d&&o.indexOf("</")===-1&&o.charAt(o.length-1)!=="/"&&t++}return e}var Ce,rl,jr,da,Wr,Ne=class{constructor(e,t,i,s,o){l(this,Ce);this.renderState={};this.currentComponentKey=[];this.currentHookIndex=0;this.actions=new Map;this.forms=new Map;this.realtimeChannels=[];this.realtimeUpdated=!1;this.pendingHooks=[];this.isRendering=!1;this.transformer=new vi(()=>this.assets);this.effects=[];l(this,Wr,!1);this.component=e,this.event=t,this.state={__renderState:{},...i},this.metadata=s,this.state.__realtimeChannels&&(this.realtimeChannels=this.state.__realtimeChannels);let d=ke({reconciler:this,hooks:!0,ui:!0,metadata:s});this.cache=d.cache,this.modLog=d.modLog,this.reddit=d.reddit,this.kvStore=d.kvStore,this.redis=d.redis,this.settings=d.settings,this.scheduler=d.scheduler,this.media=d.media,this.assets=d.assets,this.realtime=d.realtime,this.dimensions=o,this.ui=d.ui,this.hooks={useState:d.useState,useInterval:d.useInterval,useForm:d.useForm,useChannel:d.useChannel}}emitEffect(e,t){this.effects.push(t)}async render(){await this.reconcile(),this.isRendering=!0;let e=await this.buildBlocksUI();return this.isRendering=!1,e}makeUniqueActionID(e){let t=e,i=1;for(;this.actions.has(t);)t=`${e}.${i++}`;return t}async reconcile(){let e=h(this,Ce,jr).call(this),t={type:this.component,props:e,children:[]},i=await this.processBlock(t);if(tl(i),this.transformer.createBlocksElementOrThrow(i),this.isUserActionRender&&this.blockRenderEventId){let s=this.actions.get(this.blockRenderEventId);s&&await s(this.event.data)}for(let s of this.pendingHooks)await s();this.buildNextState(),h(this,Ce,rl).call(this)}async buildBlocksUI(){let e=h(this,Ce,jr).call(this),t={type:this.component,props:e,children:[]},i=await this.renderElement(e,t);return this.transformer.ensureRootBlock(i)}async renderElement(e,t){let i=await this.processBlock(t);return tl(i),(u.debug.emitSnapshots||e.debug.emitSnapshots)&&console.debug(pm(il(i))),(u.debug.emitState||e.debug.emitState)&&console.debug(JSON.stringify(this.state,void 0,2)),this.transformer.createBlocksElementOrThrow(i)}async processProps(e){let t=e.props??{},i=["onPress","onMessage"];for(let s of i)if(s in t){let o=t[s],d=o?.name,c=this.makeUniqueActionID(`${e.type}.${d??s}`);this.actions.set(c,o),t[s]=c}}async processBlock(e,t=Hd(),i=[]){let s=e;if(typeof s.type=="string"){let c=[];for(let f=0;f<s.children.length;f++){let S=s.children[f];S!=null&&c.push(await this.processBlock(S,t,[...i,`${s.type}.${f}`]))}let m=c.flat(),b=h(this,Ce,da).call(this,m);return await this.processProps(s),{type:s.type,props:s.props,children:b}}if(typeof s.type=="function"){let c=t(`${i.length?i.join("."):"root"}.${s.type.name.length?s.type.name:"anonymous"}`);this.currentComponentKey.push(c),this.renderState[c]||(this.renderState[c]={});let m=s.children.flatMap(f=>f),b={...h(this,Ce,jr).call(this),...s.props,children:m},y;for(;y===void 0;)try{y=await s.type(b,h(this,Ce,jr).call(this))}catch(f){if(f instanceof Promise)y=await f;else throw f}if(!this.isInitialRender){let f=this.getPreviousComponentState();if(Object.keys(f).length!==this.currentHookIndex)throw new Error("Invalid hook call. Hooks can only be called at the top-level of a function component. Make sure that you are not calling hooks inside loops, conditions, or nested functions.")}if(this.currentComponentKey.pop(),this.currentHookIndex=0,typeof y=="object")return this.processBlock(y,t,[...i,s.type.name])}if(typeof s=="string")return s;if(typeof s=="number")return`${s}`;let o=[],d="";return Array.isArray(s)?o=s:typeof s.type>"u"&&s.children&&(o=s.children,d="fragmentChild."),{type:"__fragment",props:void 0,children:await Promise.all(o.flatMap(async(c,m)=>await this.processBlock(c,t,[...i,`${d}${m}`])))}}getCurrentComponentKey(){if(!this.currentComponentKey.at(-1))throw new Error("Current component key is missing");return this.currentComponentKey}getCurrentComponentState(){let e=this.currentComponentKey.at(-1);if(!e)throw new Error("Current component key is missing");return this.renderState[e]}getPreviousComponentState(){let e=this.currentComponentKey.at(-1);if(!e)throw new Error("Current component key is missing");return this.state.__renderState[e]||(this.state.__renderState[e]={}),this.state.__renderState[e]}get isInitialRender(){return this.event?this.event.type===aa.RENDER_INITIAL:!1}get isUserActionRender(){return this.event?this.event.type===aa.RENDER_USER_ACTION:!1}get isEffectRender(){return this.event?this.event.type===aa.RENDER_EFFECT_EVENT:!1}get formSubmittedEvent(){return this.event?this.event.formSubmitted:!1}get blockRenderEventId(){return this.event?this.event.id:!1}get realtimeEvent(){if(!this.event)return!1;let e=this.event.realtimeEvent;return e?.event?.channel?e:!1}runHook(e){this.pendingHooks.push(e)}rerenderIn(e){n(this,Wr)||(a(this,Wr,!0),this.effects.push({type:el.EFFECT_RERENDER_UI,rerenderUi:{delaySeconds:e/1e3}}))}addRealtimeChannel(e){this.realtimeChannels.push(e),this.realtimeUpdated=!0}removeRealtimeChannel(e){this.realtimeChannels=this.realtimeChannels.filter(t=>t!==e),this.realtimeUpdated=!0}get realtimeEffect(){return this.realtimeUpdated&&this.realtimeChannels.length>0?[{type:el.EFFECT_REALTIME_SUB,realtimeSubscriptions:{subscriptionIds:this.realtimeChannels}}]:[]}getEffects(){return[...fi(this.ui),...this.effects,...this.realtimeEffect]}buildNextState(){for(let e of Object.keys(this.renderState))this.renderState[e]=Object.values(this.renderState[e]);this.state={__postData:this.state.__postData,__renderState:this.renderState,__cache:this.state.__cache,...this.realtimeChannels.length>0?{__realtimeChannels:this.realtimeChannels}:{}}}};Ce=new WeakSet,rl=function(){this.actions.clear(),this.currentComponentKey=[],this.currentHookIndex=0,this.pendingHooks=[],this.realtimeChannels=[],this.realtimeUpdated=!1},jr=function(){let e={...se(this.metadata,this.state.__postData?.thingId),modLog:this.modLog,reddit:this.reddit,cache:this.cache,kvStore:this.kvStore,redis:this.redis,settings:this.settings,scheduler:this.scheduler,media:this.media,assets:this.assets,realtime:this.realtime,ui:this.ui,dimensions:this.dimensions,uiEnvironment:{timezone:this.metadata[P.Timezone]?.values[0],locale:this.metadata[P.Language]?.values[0],dimensions:this.dimensions},...this.hooks};return e.debug.effects=this,e},da=function(e){let t=[];for(let i of e)typeof i=="string"?t.push(i):i.type==="__fragment"?t.push(...h(this,Ce,da).call(this,i.children)):t.push(i);return t},Wr=new WeakMap;async function fm(r,e){let t=u.customPostType;if(!t)throw new Error("Custom post type not registered");let i=new Ne((o,d)=>t.render(d),r.blocks,r.state,e,r.dimensions),s=await i.render();return hm.fromJSON({state:i.state,blocks:{ui:s},effects:i.getEffects()})}function nl(r){r.provides(gm),R("RenderPost",fm)}import{GetFieldsResponse as bm,InstallationSettingsDefinition as ym}from"@devvit/protos";async function vm(){if(!u.installationSettings)throw new Error("Installation settings were not defined.");return bm.fromJSON({fields:{fields:De(u.installationSettings)}})}async function km(r,e){return Vs(r,u.installationSettings,e)}function sl(r){r.provides(ym),R("GetSettingsFields",vm),R("ValidateForm",km)}import{ContextActionDefinition as Cm,ContextActionList as Sm,ContextActionResponse as Pm}from"@devvit/protos";function la(r){let e=r.debug.metadata[P.User].values[0];if(!e)throw new Error("User missing from context");return e}function ua(r){let e=r.debug.metadata[P.Subreddit].values[0];if(!e)throw new Error("Subreddit missing from context");return e}async function ol(r,e){let t=la(r),i=ua(r);if(!t||!i)throw new Error("User or subreddit missing from context");let s=e.comment?.id&&`t1_${e.comment.id}`,o=e.post?.id&&`t3_${e.post.id}`,d=e.subreddit?.id&&`t5_${e.subreddit.id}`,c=s||o||d;if(!c)throw new Error("targetId is missing from ContextActionRequest");if(s){let f=await r.reddit.getCommentById(s);if(!f)throw new Error(`Comment ${s} not found`);if(f.subredditId!==i)throw new Error("Comment does not belong to the subreddit")}if(o){let f=await r.reddit.getPostById(o);if(!f)throw new Error(`Post ${o} not found`);if(f.subredditId!==i)throw new Error("Post does not belong to the subreddit")}if(d&&d!==i)throw new Error(`Subreddit ${d} ${i} not found`);let m=Vr(e.actionId);if(!m)throw new Error("Action not found");let b=!!m.forUserType?.includes("moderator");if(b&&!al(r))throw new Error("User is not a moderator");let y={needsModCheck:b};await r.redis.set(`${t}${i}${c}${e.actionId}`,JSON.stringify(y)),await r.redis.expire(`${t}${i}${c}${e.actionId}`,600),console.debug("CSRF token added: "+JSON.stringify(y))}async function al(r){let e=la(r),t=ua(r),i=await r.reddit.getSubredditInfoById(t);return!!(await r.reddit.getModerators({subredditName:i.name}).all()).find(o=>o.id===e)}async function dl(r,e){let t=la(r),i=ua(r),{actionId:s,thingId:o}=e.state?.__contextAction??{},d=await r.redis.get(`${t}${i}${o}${s}`);if(!d)throw new Error("CSRF token not found");if(JSON.parse(d).needsModCheck&&!await al(r))throw new Error("User is not a moderator: "+t+"; "+i);console.debug("CSRF token validated: "+d)}var ll=r=>`menuItem.${r}`;function Vr(r){return u.menuItems.find((e,t)=>ll(t)===r)}async function wm(r,e){let t=u.menuItems;if(!t.length)throw new Error("No menu items registered.");let i=t.map((s,o)=>({actionId:ll(o),name:s.label,description:s.description,contexts:{subreddit:s.location.includes("subreddit"),post:s.location.includes("post"),comment:s.location.includes("comment")},users:{loggedOut:s.forUserType?.includes("loggedOut"),moderator:s.forUserType?.includes("moderator")},postFilters:s.postFilter==="currentApp"?{currentApp:!0}:void 0}));return Sm.fromJSON({actions:i})}async function Fm(r,e){let t=Vr(r.actionId);if(!t)throw new Error(`MenuItem ${r.actionId} not found`);let i=r.comment?.id&&`t1_${r.comment.id}`,s=r.post?.id&&`t3_${r.post.id}`,o=r.subreddit?.id&&`t5_${r.subreddit.id}`,d=i||s||o;p(d,"targetId is missing from ContextActionRequest");let c={targetId:d,location:r.comment?"comment":r.post?"post":"subreddit"},m=Object.assign(ke({ui:!0,metadata:e}),se(e,s,i),{uiEnvironment:{timezone:e[P.Timezone]?.values[0],locale:e[P.Language]?.values[0]}});return await ol(m,r),await t.onPress(c,m),Pm.fromJSON({effects:fi(m.ui)})}function ul(r){r.provides(Cm),R("GetActions",wm),R("OnAction",Fm)}function Le(r){return r?r===!0?!0:r.enabled:!1}import{SchedulerHandlerDefinition as xm}from"@devvit/protos";async function Im(r,e){let t=r.type,i=u.scheduledJobHandlers.get(t);if(!i)throw new Error(`Job ${t} not found`);let s={name:t,data:r.data},o=Object.assign(ke({metadata:e}),se(e));await i(s,o)}function cl(r){r.provides(xm),R("HandleScheduledAction",Im)}import{OnAppInstallDefinition as Em,OnAppUpgradeDefinition as Am,OnAutomoderatorFilterCommentDefinition as Tm,OnAutomoderatorFilterPostDefinition as Rm,OnCommentCreateDefinition as Om,OnCommentDeleteDefinition as Bm,OnCommentReportDefinition as Mm,OnCommentSubmitDefinition as Um,OnCommentUpdateDefinition as Dm,OnModActionDefinition as Nm,OnModMailDefinition as Lm,OnPostCreateDefinition as _m,OnPostDeleteDefinition as Hm,OnPostFlairUpdateDefinition as jm,OnPostNsfwUpdateDefinition as Wm,OnPostReportDefinition as Vm,OnPostSpoilerUpdateDefinition as Gm,OnPostSubmitDefinition as Jm,OnPostUpdateDefinition as zm}from"@devvit/protos";var ki;(function(r){function e(d,c){return d.length<=c?d:`${d.slice(0,c-1)}\u2026`}r.ellipsize=e;function t(d){return d[0]==null?d:`${d[0].toLocaleUpperCase()}${d.slice(1)}`}r.capitalize=t;function i(d){return d==null||/^\s*$/.test(d)}r.isBlank=i;function s(d,c="stack"){return d instanceof Error?`${d[c]||d.stack||d.message||d.name}`:String(d)}r.caughtToString=s;function o(d,c="stack"){return d instanceof Error?`${d[c]||d.stack||d.message||d.name}`:String(d)}r.caughtToStringUntyped=o})(ki||(ki={}));function q(r,e){return p(e),async(t,i)=>{let s={...t,type:r},o=Object.assign(ke({metadata:i}),se(i)),d=await Promise.allSettled(e.map(m=>m(s,o))),c=qm(d);if(c)throw c.err;return{}}}function ml(r){for(let e of u.triggerOnEventHandlers.keys())switch(e){case"PostSubmit":r.provides(Jm),R("OnPostSubmit",q("PostSubmit",u.triggerOnEventHandlers.get(e)));break;case"PostCreate":r.provides(_m),R("OnPostCreate",q("PostCreate",u.triggerOnEventHandlers.get(e)));break;case"PostUpdate":r.provides(zm),R("OnPostUpdate",q("PostUpdate",u.triggerOnEventHandlers.get(e)));break;case"PostReport":r.provides(Vm),R("OnPostReport",q("PostReport",u.triggerOnEventHandlers.get(e)));break;case"PostDelete":r.provides(Hm),R("OnPostDelete",q("PostDelete",u.triggerOnEventHandlers.get(e)));break;case"PostFlairUpdate":r.provides(jm),R("OnPostFlairUpdate",q("PostFlairUpdate",u.triggerOnEventHandlers.get(e)));break;case"CommentSubmit":r.provides(Um),R("OnCommentSubmit",q("CommentSubmit",u.triggerOnEventHandlers.get(e)));break;case"CommentCreate":r.provides(Om),R("OnCommentCreate",q("CommentCreate",u.triggerOnEventHandlers.get(e)));break;case"CommentUpdate":r.provides(Dm),R("OnCommentUpdate",q("CommentUpdate",u.triggerOnEventHandlers.get(e)));break;case"CommentReport":r.provides(Mm),R("OnCommentReport",q("CommentReport",u.triggerOnEventHandlers.get(e)));break;case"CommentDelete":r.provides(Bm),R("OnCommentDelete",q("CommentDelete",u.triggerOnEventHandlers.get(e)));break;case"AppInstall":r.provides(Em),R("OnAppInstall",q("AppInstall",u.triggerOnEventHandlers.get(e)));break;case"AppUpgrade":r.provides(Am),R("OnAppUpgrade",q("AppUpgrade",u.triggerOnEventHandlers.get(e)));break;case"ModAction":r.provides(Nm),R("OnModAction",q("ModAction",u.triggerOnEventHandlers.get(e)));break;case"ModMail":r.provides(Lm),R("OnModMail",q("ModMail",u.triggerOnEventHandlers.get(e)));break;case"PostNsfwUpdate":r.provides(Wm),R("OnPostNsfwUpdate",q("PostNsfwUpdate",u.triggerOnEventHandlers.get(e)));break;case"PostSpoilerUpdate":r.provides(Gm),R("OnPostSpoilerUpdate",q("PostSpoilerUpdate",u.triggerOnEventHandlers.get(e)));break;case"AutomoderatorFilterPost":r.provides(Rm),R("OnAutomoderatorFilterPost",q("AutomoderatorFilterPost",u.triggerOnEventHandlers.get(e)));break;case"AutomoderatorFilterComment":r.provides(Tm),R("OnAutomoderatorFilterComment",q("AutomoderatorFilterComment",u.triggerOnEventHandlers.get(e)));break;default:throw new Error(`Unknown trigger event: ${e}`)}}function qm(r){let e=r.reduce((t,i)=>i.status==="rejected"?[...t,i.reason]:t,[]);if(e.length!==0)return e.length===1?{err:e[0]}:{err:new Error(e.map(t=>ki.caughtToString(t)).join(`
|
|
3
|
+
`))}}import{EffectType as bp,HandleUIEventResponse as pa,UIEventHandlerDefinition as yp}from"@devvit/protos";var Al=ed(wl(),1);function Fl(r){return r?.constructor===Object}function Et(r,e){return Object.is(r,e)?!0:typeof r!=typeof e?!1:Array.isArray(r)&&Array.isArray(e)?xl(r,e):r instanceof Date&&e instanceof Date?r.getTime()===e.getTime():r instanceof RegExp&&e instanceof RegExp?r.toString()===e.toString():Fl(r)&&Fl(e)?fp(r,e):r instanceof ArrayBuffer&&e instanceof ArrayBuffer?Il(new DataView(r),new DataView(e)):r instanceof DataView&&e instanceof DataView?Il(r,e):El(r)&&El(e)?r.byteLength!==e.byteLength?!1:xl(r,e):!1}function fp(r,e){let t=Object.keys(r),i=Object.keys(e);if(!Et(t,i))return!1;for(let s of t)if(!Et(r[s],e[s]))return!1;return!0}function xl(r,e){return r.length!==e.length?!1:r.every((t,i)=>Et(t,e[i]))}function Il(r,e){if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r.getUint8(t)!==e.getUint8(t))return!1;return!0}function El(r){return ArrayBuffer.isView(r)&&!(r instanceof DataView)}async function vp(r,e){let t=r.state??{},i=(0,Al.default)(t),s=ke({ui:!0,metadata:e});if(r.event?.formSubmitted&&r.event.formSubmitted.formId){let m=r.event.formSubmitted.formId;if(m.includes("form.hook.")&&u.customPostType){let v=new Ne((O,L)=>u.customPostType?.render(L)??null,r.event,r.state,e,void 0);return await v.reconcile(),pa.fromJSON({state:v.state,effects:v.getEffects()})}let b=u.formDefinitions.get(m);if(!b)throw new Error(`Form with key ${m} not found`);let y,f;if(i.__contextAction){let{actionId:v,thingId:O}=i.__contextAction,L=Vr(v);L?.location==="post"?y=O:L?.location==="comment"&&(f=O)}let S=Object.assign(s,se(e,y,f),{uiEnvironment:{timezone:e[P.Timezone]?.values[0],locale:e[P.Language]?.values[0]}});await dl(S,r),await b.onSubmit({values:ze(r.event.formSubmitted.results)},S)}else if(r.event?.realtimeEvent){if(u.customPostType){let m=new Ne((b,y)=>u.customPostType?.render(y)??null,r.event,r.state,e,void 0);return await m.reconcile(),pa.fromJSON({state:m.state,effects:m.getEffects()})}}else if(r.event?.toastAction)throw new Error("Toast actions not yet implemented");let o=!Et(t,i),d=fi(s.ui),c=o?[...d,{type:bp.EFFECT_RERENDER_UI,rerenderUi:{delaySeconds:0}}]:d;return pa.fromJSON({state:i,effects:c})}function Tl(r){r.provides(yp),R("HandleUIEvent",vp)}import{CustomPostDefinition as uo,UIResponse as nu}from"@devvit/protos";import{UIEventScope as Ip}from"@devvit/protos";var ga="ServerCallRequired";function Xs(r){return r?.message===ga}var ya={now(){return new Date}};function Rl(r){return`__autocache__${r}`}function Ol(r){return`__lock__${r}`}var kp=300,Cp=1e3,Qs=5e3,ha=3,Bl=.1,Ml=1e3,Sp=3e4;function Ul(r){if(r.error)throw new Error(r.error);return r.value}var Ye,et,Se,Ci,z,Dl,Nl,Ll,fa,_l,Hl,ba,jl,Ys=class{constructor(e,t,i=ya){l(this,z);l(this,Ye);l(this,et,{});l(this,Se);l(this,Ci);a(this,Ye,e),a(this,Ci,t),a(this,Se,i)}async cache(e,t){var d;(d=n(this,Ci)).__cache??(d.__cache={}),a(this,et,n(this,Ci).__cache),h(this,z,jl).call(this,t);let i=h(this,z,Dl).call(this,t.key);if(i!==void 0)return i;let s=await h(this,z,ba).call(this,t.key),o=await h(this,z,Nl).call(this,t,s,e);return Ul(o)}};Ye=new WeakMap,et=new WeakMap,Se=new WeakMap,Ci=new WeakMap,z=new WeakSet,Dl=function(e){let t=n(this,et)[e];if(t){let i=n(this,Se).now().getTime(),s=t?.error&&t?.errorTime&&t.errorCount<ha&&Math.random()<Bl&&t.errorTime+Ml<i;if(t?.expires&&t.expires<i&&t.checkedAt+Ml<i||s){delete n(this,et)[e];return}else return Ul(t)}},Nl=async function(e,t,i){let s=t?.expires,o=s?h(this,z,Hl).call(this,s):1;return!t||t?.error&&t.errorCount<ha&&Bl>Math.random()||o>Math.random()?h(this,z,Ll).call(this,e,t,i):t},Ll=async function(e,t,i){let s=Ol(e.key),o=n(this,Se).now().getTime(),d=new Date(o+e.ttl/2);if(await n(this,Ye).set(s,"1",{expiration:d,nx:!0}))return h(this,z,_l).call(this,e.key,t,i,e.ttl);if(t)return t;{let m=n(this,Se).now();return h(this,z,fa).call(this,m,e.key,e.ttl)}},fa=async function(e,t,i){let s=Math.min(i,Cp),o=await h(this,z,ba).call(this,t);if(o)return o;if(n(this,Se).now().getTime()-e.getTime()>=s)throw new Error(`Cache request timed out trying to get data at key: ${t}`);return await new Promise(d=>setTimeout(d,kp)),h(this,z,fa).call(this,e,t,i)},_l=async function(e,t,i,s){let o=n(this,Se).now().getTime()+s;t=t??{value:null,expires:o,errorCount:0,error:null,errorTime:null,checkedAt:0};try{t.value=await i(),t.error=null,t.errorCount=0,t.errorTime=null}catch(d){t.value=null,t.error=d.message??"Unknown error",t.errorTime=n(this,Se).now().getTime(),t.errorCount++}return n(this,et)[e]=t,await n(this,Ye).set(Rl(e),JSON.stringify(t),{expiration:new Date(o+Sp)}),t.error&&t.errorCount<ha&&await n(this,Ye).del(Ol(e)),t},Hl=function(e){let t=n(this,Se).now().getTime(),i=e-t;return i<0?1:i<1e3?.1:i<2e3?.01:i<3e3?.001:0},ba=async function(e){let t=await n(this,Ye).get(Rl(e));if(t){let i=JSON.parse(t);return i.checkedAt=n(this,Se).now().getTime(),n(this,et)[e]=i,i}},jl=function(e){e.ttl<Qs&&(console.warn(`Cache TTL cannot be less than ${Qs} milliseconds! Updating ttl value of ${e.ttl} to ${Qs}.`),e.ttl=Qs)};function Wl(r,e,t=ya){let i=new Ys(r,e,t);return i.cache.bind(i)}import{EffectType as eo,ToastAppearance as Jl}from"@devvit/protos";function Vl(r){let e=r.match(/form\.hook\.(.+)\.0/);if(e?.[1])return e[1]}var va=class{constructor(e,t,i){this.state=null;this.hookId=e.hookId,this.form=t,this.onSubmit=i,this.onUIEvent=async s=>{s.formSubmitted&&await i(ze(s.formSubmitted.results))}}};function ka(r,e){let t=me({namespace:"useForm",initializer:i=>new va(i,r,e)});return Pp({id:t.hookId})}function Pp(r){return`form.hook.${r.id}.0`}function Gl(r,e){let t=Vl(e);return r.getHook({id:t})}var _e,io,Gr,ro,to=class{constructor(e){l(this,_e);l(this,io,0);l(this,Gr);l(this,ro,(e,t)=>{let i=t!==void 0?e:"",s=t!==void 0?t:e;n(this,_e).emitEffect(`postMessage${td(this,io)._++}`,{type:eo.EFFECT_WEB_VIEW,webView:{postMessage:{webViewId:i,app:{message:s}}}})});a(this,_e,e),a(this,Gr,{postMessage:n(this,ro)})}get webView(){return n(this,Gr)}showForm(e,t){let i=Gl(n(this,_e),e);if(!i)throw new Error("Form does not exist. Make sure you have added it using useForm.");let s=i.form instanceof Function?i.form(t??{}):i.form,o={fields:[],id:e,title:s.title,acceptLabel:s.acceptLabel,cancelLabel:s.cancelLabel,shortDescription:s.description};wt(s.fields),o.fields=De(s.fields),n(this,_e).emitEffect(e,{type:eo.EFFECT_SHOW_FORM,showForm:{form:o}})}showToast(e){let t;e instanceof Object?t={text:e.text,appearance:e.appearance==="success"?Jl.SUCCESS:Jl.NEUTRAL}:t={text:e},n(this,_e).emitEffect(e.toString(),{type:eo.EFFECT_SHOW_TOAST,showToast:{toast:t}})}navigateTo(e){let t;typeof e=="string"?t=new URL(e).toString():t=new URL(e.permalink,"https://www.reddit.com").toString(),n(this,_e).emitEffect(t,{type:eo.EFFECT_NAVIGATE_TO_URL,navigateToUrl:{url:t}})}};_e=new WeakMap,io=new WeakMap,Gr=new WeakMap,ro=new WeakMap;import{EffectType as wp,RealtimeSubscriptionStatus as zl}from"@devvit/protos";var tt,Te,it,At,Jr,Sa,no=class no{constructor(e,t){l(this,Jr);l(this,tt);l(this,Te);l(this,it);l(this,At);a(this,tt,t.context),a(this,Te,!!t.context._devvitContext?.debug.realtime),a(this,At,e),a(this,it,t.invalidate);let i=t.context.meta[P.App]?.values[0];if(!i)throw Error("useChannel missing app ID metadata");let s=t.context.meta[P.Installation]?.values[0];if(!s)throw Error("useChannel missing install ID from metadata");let o=`${i}:${s}:${e.name}`;if(Object.values(n(this,tt)._hooks).filter(c=>c instanceof no).some(c=>c.state.channel===o))throw Error(`useChannel channel names must be unique; "${o}" duplicated`);this.state={channel:o,connected:!1,subscribed:!1}}async onUIEvent(e){let t=e.realtimeEvent;if(!(!t||!this.state.subscribed))switch(t.status){case zl.REALTIME_SUBSCRIBED:n(this,Te)&&console.debug(`[realtime] "${this.state.channel}" connected`),this.state.connected=!0,n(this,it).call(this),await n(this,At).onSubscribed?.();break;case zl.REALTIME_UNSUBSCRIBED:n(this,Te)&&console.debug(`[realtime] "${this.state.channel}" disconnected`),this.state.connected=!1,n(this,it).call(this),await n(this,At).onUnsubscribed?.();break;default:n(this,Te)&&console.debug(`[realtime] "${this.state.channel}" received message: ${JSON.stringify(e,void 0,2)}`),n(this,At).onMessage(t.event?.data?.msg);break}}async send(e){if(n(this,Te)&&console.debug(`[realtime] "${this.state.channel}" send message: ${JSON.stringify(e,void 0,2)}`),!this.state.subscribed||!this.state.connected)throw console.debug(`[realtime] "${this.state.channel}" send failed; channel not connected`),Error(`useChannel send failed; "${this.state.channel}" channel not connected`);await n(this,tt).devvitContext.realtime.send(this.state.channel,e)}get status(){return this.state.subscribed&&this.state.connected?2:this.state.subscribed&&!this.state.connected?1:!this.state.subscribed&&this.state.connected?3:4}subscribe(){this.state.subscribed||(n(this,Te)&&console.debug(`[realtime] "${this.state.channel}" subscribed`),this.state.subscribed=!0,n(this,it).call(this),h(this,Jr,Sa).call(this))}unsubscribe(){this.state.subscribed&&(n(this,Te)&&console.debug(`[realtime] "${this.state.channel}" unsubscribed`),this.state.subscribed=!1,n(this,it).call(this),h(this,Jr,Sa).call(this))}};tt=new WeakMap,Te=new WeakMap,it=new WeakMap,At=new WeakMap,Jr=new WeakSet,Sa=function(){let e=Object.values(n(this,tt)._hooks).filter(t=>t instanceof no&&t.state.subscribed).map(t=>t.state.channel);n(this,tt).emitEffect(this.state.channel,{type:wp.EFFECT_REALTIME_SUB,realtimeSubscriptions:{subscriptionIds:e}})};var Ca=no;function Pa(r){if(!r.name||/[^a-zA-Z0-9_]/.test(r.name))throw Error(`useChannel error: The name "${r.name}" you provided for the hook is invalid. Valid names can only contain letters, numbers, and underscores (_).`);let e=`useChannel:${r.name}`;return me({id:e,namespace:e,initializer:t=>new Ca(r,t)})}import{EffectType as wa}from"@devvit/protos";function ql(r){return typeof r=="object"&&r!==null&&"__deleted"in r}var Tt,rt,Si=class Si{constructor(e,t){l(this,Tt);this._segments=[];l(this,rt,{});this._prevHooks={};this._prevHookId="";this._effects={};this._changed={};this._touched={};this._requeueEvents=[];this._rootProps={};this._generated={};this._undeliveredHandlers={};this.request=e,this.meta=t,a(this,Tt,e.state??{__cache:{}}),this._rootProps=e.props??{}}get devvitContext(){if(!this._devvitContext)throw new Error("Devvit context not available");return this._devvitContext}set devvitContext(e){this._devvitContext=e}get _changedState(){let e={__cache:n(this,Tt).__cache??{}};for(let i in this._changed)e[i]=this._state[i];let t=new Set(Object.keys(this._state));return Object.keys(n(this,rt)).forEach(i=>{i!=="__cache"&&t.delete(i)}),t.forEach(i=>{if(i==="__cache")return;let s={__deleted:!0};this._state[i]=e[i]=s}),e}get _hooks(){return n(this,rt)}set _hooks(e){this._prevHooks=n(this,rt),a(this,rt,e)}get _state(){return n(this,Tt)}set _state(e){a(this,Tt,e)}push(e){this._segments.push({...e,next:0})}pop(){this._segments.pop()}addUndeliveredEventHandler(e,t){this._undeliveredHandlers[e]=t}addGlobalUndeliveredEventHandler(e,t){Si.addGlobalUndeliveredEventHandler(e,t)}getHook(e){return n(this,rt)[e.id]}static addGlobalUndeliveredEventHandler(e,t){Si._staticUndeliveredHandlers[e]=t}async handleUndeliveredEvent(e){let t={...Si._staticUndeliveredHandlers,...this._undeliveredHandlers};for(let[i,s]of Object.entries(t))await s(e,this)}emitEffect(e,t){this._effects[e]=t}addToRequeueEvents(...e){this._devvitContext?.debug.blocks&&console.debug("[blocks] requeueing events",e);let t=e.reduce((i,s)=>(s.retry?i.retry.push(s):i.normal.push(s),i),{retry:[],normal:[]});this._requeueEvents=[...t.retry,...this._requeueEvents,...t.normal]}get effects(){return Object.values(this._effects)}nextHookId(e){e.key===void 0&&(e.key=this._segments[this._segments.length-1].next+++""),this.push(e);try{let t=[];for(let s=this._segments.length-1;s>=0;s--){let o=this._segments[s];if(o.id){t.unshift(o.id);break}let d=[];o.namespace&&d.push(o.namespace),o.key!==void 0&&o.key!==!1&&d.push(o.key),t.unshift(d.join("-"))}let i=t.join(".");if(this._generated[i]&&!e.shared)throw new Error(`Hook id ${i} already used, cannot register another hook with the same id`);return this._generated[i]=!0,this._prevHookId=i,i}finally{this.pop()}}};Tt=new WeakMap,rt=new WeakMap,Si._staticUndeliveredHandlers={};var Pi=Si;var nt={};Pi.addGlobalUndeliveredEventHandler("intervals",async(r,e)=>{r.timer&&r.hook&&(delete nt[r.hook],e.emitEffect("timers",{type:wa.EFFECT_SET_INTERVALS,interval:{intervals:nt}}))});var st,wi,zr,Fi,Fa=class{constructor(e,t,i){l(this,st);l(this,wi);l(this,zr);l(this,Fi);this.state={duration:{seconds:0,nanos:0},running:!1};a(this,wi,i.invalidate),a(this,st,i.hookId),a(this,zr,e),a(this,Fi,i.context);let s=Math.floor(t/1e3),o=t%1e3*1e6;this.state.duration={seconds:s,nanos:o}}onStateLoaded(){this.state.running?nt[n(this,st)]={duration:this.state.duration}:delete nt[n(this,st)]}async onUIEvent(e){await n(this,zr).call(this)}start(){nt[n(this,st)]={duration:this.state.duration},this.state.running=!0,n(this,wi).call(this),n(this,Fi).emitEffect("timers",{type:wa.EFFECT_SET_INTERVALS,interval:{intervals:nt}})}stop(){delete nt[n(this,st)],this.state.running=!1,n(this,wi).call(this),n(this,Fi).emitEffect("timers",{type:wa.EFFECT_SET_INTERVALS,interval:{intervals:nt}})}};st=new WeakMap,wi=new WeakMap,zr=new WeakMap,Fi=new WeakMap;function xa(r,e){let t=me({namespace:"useInterval",initializer:i=>new Fa(r,e,i)});return{start:()=>t.start(),stop:()=>t.stop()}}import{UIEventScope as xp}from"@devvit/protos";var Rt=class extends Error{};import{UIEventScope as $l}from"@devvit/protos";function Ea(r){if(r instanceof Error){if(r.message===ga)throw r;return console.error(r),{message:r.message,details:r.stack??""}}else return console.error(r),{message:"Unknown error",details:ki.caughtToString(r)}}var Fe,Re,xi,qr,Ii,Ia=class{constructor(e,t,i){l(this,Fe);l(this,Re);l(this,xi);l(this,qr);l(this,Ii);a(this,Fe,!!i.context.devvitContext.debug.useAsync),n(this,Fe)&&console.debug("[useAsync] v1",t),this.state={data:null,load_state:"initial",error:null,depends:null},a(this,Re,i.hookId),this.initializer=e,a(this,xi,i.invalidate),a(this,qr,i.context),this.localDepends=t.depends??null,a(this,Ii,t)}onStateLoaded(){if(n(this,Fe)&&console.debug("[useAsync] async onLoad ",n(this,Re),this.state),n(this,Fe)&&console.debug("[useAsync] async onLoad have ",this.localDepends,"and",this.state.depends),!Et(this.localDepends,this.state.depends)||this.state.load_state==="initial"){n(this,Fe)&&console.debug("[useAsync] attempting to resolve for hookId",n(this,Re)),this.state.load_state="loading",this.state.depends=this.localDepends,n(this,xi).call(this);let e={scope:$l.ALL,hook:n(this,Re),async:!0,asyncRequest:{requestId:n(this,Re)+"-"+JSON.stringify(this.state.depends)}};n(this,Fe)&&console.debug("[useAsync] onLoad requeue"),n(this,qr).addToRequeueEvents(e)}}async onUIEvent(e,t){if(e.asyncRequest){let i={requestId:e.asyncRequest.requestId};try{i.data={value:await this.initializer()}}catch(o){i.error=Ea(o)}let s={scope:$l.ALL,asyncResponse:i,hook:n(this,Re)};n(this,Fe)&&console.debug("[useAsync] onReq requeue"),t.addToRequeueEvents(s)}else if(e.asyncResponse){let i=n(this,Re)+"-"+JSON.stringify(this.state.depends);e.asyncResponse.requestId===i?(this.state={...this.state,data:e.asyncResponse.data?.value??null,error:e.asyncResponse.error??null,load_state:e.asyncResponse.error?"error":"loaded"},n(this,Ii).finally&&await n(this,Ii).finally(this.state.data,this.state.error?new Error(this.state.error?.message??"Unknown error"):null),n(this,xi).call(this)):n(this,Fe)&&console.debug("[useAsync] onResp skip, stale event",e.asyncResponse.requestId," !== ",i)}else throw new Error("Unknown event type")}};Fe=new WeakMap,Re=new WeakMap,xi=new WeakMap,qr=new WeakMap,Ii=new WeakMap;function Fp(r,e={}){let t=me({namespace:"useAsync",initializer:i=>new Ia(r,e,i)});return{data:t.state.data,error:t.state.error,loading:t.state.load_state==="loading"}}var He,Ei,Ot,Bt,Aa=class{constructor(e,t){this.state={value:null,load_state:"initial",error:null};l(this,He);l(this,Ei);l(this,Ot);l(this,Bt);a(this,Ot,e),a(this,Bt,t.hookId),a(this,He,t.invalidate),a(this,Ei,t.context)}async onUIEvent(){if(this.state.load_state==="loading"&&this._promise){try{this.state.value=await this._promise,this.state.load_state="loaded"}catch(e){this.state.load_state="error",this.state.error=Ea(e)}n(this,He).call(this)}else console.warn("Invalid state: ",this.state.load_state,this._promise)}setter(e){this.state.value=e instanceof Function?e(this.state.value):e,this.state.load_state="loaded",n(this,He).call(this)}onStateLoaded(){if(this._promise=n(this,Ei)._prevHooks[n(this,Bt)]?._promise,this.state.load_state==="loading")throw new Rt;if(this.state.load_state==="error")throw new Error(this.state.error?.message??"Unknown error");if(this.state.load_state==="initial"){let e;try{e=n(this,Ot)instanceof Function?n(this,Ot).call(this):n(this,Ot)}catch(t){console.log("error in loading async",t),this.state.load_state="error",n(this,He).call(this);return}if(e instanceof Promise){this._promise=e,this.state.load_state="loading";let t={scope:xp.ALL,asyncRequest:{requestId:n(this,Bt)},hook:n(this,Bt)};throw n(this,Ei).addToRequeueEvents(t),n(this,He).call(this),new Rt}else this.state.value=e,this.state.load_state="loaded";n(this,He).call(this)}}};He=new WeakMap,Ei=new WeakMap,Ot=new WeakMap,Bt=new WeakMap;function Ta(r){let e=me({namespace:"useState",initializer:t=>new Aa(r,t)});return[e.state.value,e.setter.bind(e)]}var so=class{buildContext(e,t,i){let s=new di(i),o=new oi(i),d=new mi(i),c=new ui(i),m=new pi(i),b=new gi(i),y=new to(e),f=new ai(i),S=new ni,v=new li(i),O=Wl(d,e._state),L={modLog:s,kvStore:o,redis:d,reddit:c,scheduler:m,settings:b,media:f,assets:S,realtime:v,ui:y,useState:Ta,useChannel:Pa,useInterval:xa,useForm:ka,cache:O,dimensions:t.env?.dimensions,uiEnvironment:{timezone:i[P.Timezone]?.values[0],locale:i[P.Language]?.values[0],dimensions:t.env?.dimensions,colorScheme:t.env?.colorScheme}},B=se(i,t.props?.postId);return B.debug.effects=e,{...B,...L}}};var pe=null;function Kl(r){return JSON.parse(JSON.stringify(r))}function Ep(r){if(!(r!==""&&!/[-.]/.test(r)))throw new Error(`Hook with namespace '${r}' is invalid. Hook namespaces cannot be empty string or contain dashes/dots because they are used as delimiters internally. Please update the hook namespace and try again.`)}function me({initializer:r,...e}){if(!pe)throw new Error("Hooks can only be declared at the top of a component. You cannot declare hooks outside of components or inside of event handlers. It's almost always a mistake to declare hooks inside of loops or conditionals.");Ep(e.namespace);let t=pe.nextHookId(e),i=pe,s={hookId:t,invalidate:()=>{i._changed[t]=!0,i._state[t]=i?._hooks[t]?.state},context:pe},o=pe._state[t]===void 0||ql(pe._state[t]);pe._hooks[t]=pe._hooks[t]??r(s);let d=pe._hooks[t];return o||(d.state=pe._state[t]),d.onStateLoaded?.(),o&&d.state!==void 0&&d.state!==null&&s.invalidate(),d}var Ap=null,Zl=64,Ai,lo,$r,w,oe,oo,Xl,Ra,Ql,Oa,Ba,ao,Ma,Yl,Mt=class{constructor(e){l(this,w);l(this,Ai);l(this,lo,new so);l(this,$r,new vi(()=>this._latestRenderContext?.devvitContext?.assets));this._latestRenderContext=null;n(this,w,oe)&&console.debug("[blocks] BlocksHandler v1"),a(this,Ai,e),Ap=this}async handle(e,t){let i=new Pi(e,t),s=n(this,lo).buildContext(i,e,t);i.devvitContext=s;let o,d=e.events,m=!e.events?.length||d.some(O=>!O.async),b=d.some(O=>O.blocking),y,f,S=[...d];d.length===0&&d.push({scope:Ip.ALL}),n(this,w,oe)&&console.debug("[blocks] starting processing events");let v=0;for(;d.length>0;){if(v++>Zl)throw new Error(`Exceeded maximum iterations of ${Zl}`);n(this,w,oe)&&console.debug("[blocks] processing events loop iteration",d.length);let O=[];if(!d[0].async)O.push(d.shift());else for(;d[0]?.async;)O.push(d.shift());if(!O.length)throw Error("batch must have at least one event");try{if(O[0].async){let B=Kl(i._state);await h(this,w,Xl).call(this,i,...O),i._state=B}else await h(this,w,Ql).call(this,i,...O)}catch(B){if(!Xs(B))throw B;if(n(this,w,oe)&&console.debug("[blocks] caught in handler",B),i._latestRenderContent=void 0,f){i._state=f._state,i._changed=y,i._effects=f._effects;let Y=S.map(Xt=>{let Mo={...Xt};return Mo.retry=!0,Mo});i.addToRequeueEvents(...Y);break}else throw Xs(B)||console.error("[blocks] unhandled error in handler",B),B}n(this,w,oe)&&console.debug("[blocks] remaining events",i._requeueEvents);let L=[];for(let B of i._requeueEvents){if(!m&&!B.async){n(this,w,oe)&&console.debug("[blocks] NOT reprocessing event in BlocksHandler, sync mismatch A",B),L.push(B);continue}if(m&&B.async&&!b){n(this,w,oe)&&console.debug("[blocks] NOT reprocessing event in BlocksHandler, sync mismatch B",B),L.push(B);continue}n(this,w,oe)&&console.debug("[blocks] reprocessing event in BlocksHandler",B),d.push(B)}i._requeueEvents=L,d.length>0&&(y={...i._changed},f={_state:Kl(i._state),_effects:{...i._effects}},S=[...d])}if(m){i._latestRenderContent||(i._latestRenderContent=h(this,w,Oa).call(this,n(this,Ai),i.request.props??{},i));let O=i._latestRenderContent;O&&(o=n(this,$r).createBlocksElementOrThrow(O),o=n(this,$r).ensureRootBlock(o))}return{state:i._changedState,effects:i.effects,blocks:o,events:i._requeueEvents}}};Ai=new WeakMap,lo=new WeakMap,$r=new WeakMap,w=new WeakSet,oe=function(){return!!this._latestRenderContext?.devvitContext.debug.blocks},oo=function(e,...t){e._hooks={},h(this,w,Oa).call(this,n(this,Ai),e.request.props??{},e)},Xl=async function(e,...t){h(this,w,oo).call(this,e,...t),await Promise.all(t.map(async i=>{if(!i.async)throw new Error("You can't mix main and other queues in one batch. This is likely a platform bug. Please file an issue in the Discord for someone to help! https://discord.com/channels/1050224141732687912/1115441897079574620");await h(this,w,Ra).call(this,e,i)}))},Ra=async function(e,t){let i=e._hooks[t.hook];if(i?.onUIEvent)try{await i.onUIEvent(t,e)}catch(s){throw Xs(s)?n(this,w,oe)&&console.error("Server call required",s):console.error("Error in event handler",s),s}else await e.handleUndeliveredEvent(t)},Ql=async function(e,...t){for(let i of t)n(this,w,oe)&&console.log("[blocks] handling main queue event",i),n(this,w,oe)&&console.log("[blocks] before",e._state),h(this,w,oo).call(this,e,i),await h(this,w,Ra).call(this,e,i),n(this,w,oe)&&console.log("[blocks] after",e._state);h(this,w,oo).call(this,e)},Oa=function(e,t,i){n(this,w,oe)&&console.debug("[blocks] renderRoot"),i._generated={},pe=i,this._latestRenderContext=i;try{let s=h(this,w,Ba).call(this,e,t,i);if(s.length!==1)throw new Error(`There can only be one root element, received: ${s.length}. Please wrap these elements in a <vstack></vstack> or <hstack></hstack> to continue. Fragments cannot be used as a root element.`);let o=s[0];if(o==="[object Promise]")throw new Error('Root elements cannot be async. To use data from an async endpoint, please use "const [data] = useState(async () => {/** your async code */})".');if(typeof o=="string")throw new Error("The root element must return a valid block, not a string. Try wrapping the element in a <text>your content</text> tag to continue.");return i._latestRenderContent=o,o}catch(s){if(s instanceof Rt)return;throw s}finally{pe=null}},Ba=function(e,t,i){i.push({namespace:e.name||"anonymous",...t});try{let s=e(t,i.devvitContext);if(s instanceof Promise)throw new Error(`Components (found: ${e.name??"unknown component"}) cannot be async. To use data from an async endpoint, please use "const [data] = useState(async () => {/** your async code */})".`);return h(this,w,Ma).call(this,s,i)}finally{i.pop()}},ao=function(e,t){return e=e.flat(1/0),e.flatMap((i,s)=>(i&&typeof i=="object"&&"props"in i&&(i.props?.key||(i.props=i.props??{},i.props.key=`${s}`)),h(this,w,Ma).call(this,i,t)))},Ma=function(e,t){if(Array.isArray(e))return h(this,w,ao).call(this,e,t);if(Tp(e))if(e.type===void 0)try{return t.push({namespace:"fragment",...e.props}),h(this,w,ao).call(this,e.children,t)}finally{t.pop()}else if(typeof e.type=="function"){let i={...e.props,children:e.children.flat(1/0)};return h(this,w,Ba).call(this,e.type,i,t)}else try{t.push({namespace:e.type,...e.props});let i=h(this,w,ao).call(this,e.children,t),s=h(this,w,Yl).call(this,e.props??{});return[{type:e.type,children:i,props:s}]}finally{t.pop()}else return[(e??"").toString()]},Yl=function(e){let t={};for(let i in e)if(!(typeof e[i]>"u"))if(typeof e[i]=="function"){let s=me({namespace:i,key:!1,initializer:({hookId:o})=>({hookId:o,state:null,onUIEvent:d=>{if(d.userAction)return e[i](d.userAction.data);if(d.webView?.postMessage)return e[i](d.webView.postMessage.message)}})});t[i]=s.hookId,"captureHookRef"in e[i]&&e[i].captureHookRef()}else{let s=JSON.parse(JSON.stringify(e[i]));s!=null&&(t[i]=s)}return t};function Tp(r){return typeof r=="object"&&r!=null&&"type"in r}var eu=r=>{let e=Number(r.trim().split(".").pop());return isNaN(e)?void 0:e},tu=r=>{let[e,t,i]=r.trim().split(";");if(!e||!t||!i){console.warn(`Received a malformed devvit-user-agent! Received: '${r}'`);return}if(e!=="Reddit"){console.warn(`Received unknown company name in user agent! Received: '${r}'`);return}if(t==="iOS"){let s=eu(i);if(s===void 0){console.warn(`Could not parse version number from user agent! Received: '${r}'`);return}return{company:"Reddit",platform:"iOS",rawVersion:i,versionNumber:s}}if(t==="Android"){let s=eu(i);if(s===void 0){console.warn(`Could not parse version number from user agent! Received: '${r}'`);return}return{company:"Reddit",platform:"Android",rawVersion:i,versionNumber:s}}if(t==="Shreddit")return{company:"Reddit",platform:"Shreddit",rawVersion:i};if(t==="Play")return{company:"Reddit",platform:"Play",rawVersion:i};console.warn("Received unknown platform:",t)},iu=r=>r?r.platform==="Android"?r.versionNumber<1875012:r.platform==="iOS"?r.versionNumber<614973:!1:(console.warn(`Could not parse devvit-user-agent! Received: '${JSON.stringify(r)}'`),!1),Rp=r=>{switch(r){case"Android":return"https://play.google.com/store/apps/details?id=com.reddit.frontpage";case"iOS":return"https://apps.apple.com/us/app/reddit/id1064216828";case"Play":case"Shreddit":break;default:console.error(`No upgrade link for platform: ${r}`)}},Op=({platform:r},e)=>u.createElement("blocks",null,u.createElement("vstack",{alignment:"middle center",height:100,width:100},u.createElement("vstack",{maxWidth:"300px",gap:"large",alignment:"middle center"},u.createElement("vstack",{gap:"medium",alignment:"middle center"},u.createElement("image",{imageHeight:100,imageWidth:100,url:"https://i.redd.it/p1vmc5ulmpib1.png"}),u.createElement("text",{size:"large",weight:"bold",wrap:!0,alignment:"center"},"Uh oh, the app you're trying to use requires the latest version of Reddit. Please upgrade your app to continue.")),u.createElement("hstack",{alignment:"middle center"},u.createElement("button",{onPress:()=>{let t=Rp(r);t?e.ui.navigateTo(t):console.warn("No upgrade link found for platform:",r)}},"Upgrade"))))),ru=r=>()=>u.createElement(Op,{platform:r});var Bp=()=>u.createElement("vstack",{alignment:"center middle",width:"100%",height:"100%"},u.createElement("text",null,"This feature is not available yet")),Mp=[[uo,uo.methods.renderPostContent,(r,e)=>u.customPostType?.render(e)??null],[uo,uo.methods.renderPostComposer,(r,e)=>u.createElement(Bp,null)]];function Up(r){return async(e,t)=>{let i=tu(t["devvit-user-agent"]?.values?.[0]??"");if(i&&iu(i)){let o=new Mt(ru(i.platform));return nu.fromJSON(await o.handle(e,t))}let s=new Mt(r);return nu.fromJSON(await s.handle(e,t))}}function su(r){for(let[e,t,i]of Mp)r.provides(e),R(t.name,Up(i))}var Ti,Kr,Ri,Ut,Dt,Oi,Bi,Nt,ot,Zr,Xr,Lt,j,U=class U extends Ms{static configure(e){a(this,Ri,{...n(this,Ri),...e}),Le(e.http)&&this.use(k.HTTPDefinition),(e.redis===void 0||Le(e.kvStore)||Le(e.redis))&&(this.use(k.KVStoreDefinition),this.use(k.RedisAPIDefinition)),Le(e.media)&&this.use(k.MediaServiceDefinition),Le(e.modLog)&&this.use(k.ModlogDefinition),Le(e.redditAPI)&&(this.use(k.FlairDefinition),this.use(k.GraphQLDefinition),this.use(k.LinksAndCommentsDefinition),this.use(k.ListingsDefinition),this.use(k.ModerationDefinition),this.use(k.ModNoteDefinition),this.use(k.NewModmailDefinition),this.use(k.PrivateMessagesDefinition),this.use(k.SubredditsDefinition),this.use(k.UsersDefinition),this.use(k.WidgetsDefinition),this.use(k.WikiDefinition)),Le(e.realtime)&&this.use(k.RealtimeDefinition)}static addMenuItem(e){n(this,Bi).push(e)}static addCustomPostType(e){a(this,Ut,e)}static createForm(e,t){let i=`form.${n(this,Dt).size}`;return n(this,Dt).set(i,{form:e,onSubmit:t}),i}static addSchedulerJob(e){if(n(this,j)[k.SchedulerDefinition.fullName]||this.use(k.SchedulerDefinition),n(this,Nt).has(e.name))throw new Error(`Job ${e.name} is already defined`);n(this,Nt).set(e.name,e.onRun)}static addSettings(e){wt(e);let t=e.filter(s=>s.type==="group"||!s.scope||s.scope==="installation"),i=e.filter(s=>s.type!=="group"&&s.scope==="app");t.length>0&&a(this,Oi,t),i.length>0&&a(this,Ti,i),n(this,j)[k.SettingsDefinition.fullName]||this.use(k.SettingsDefinition)}static addTrigger(e){if("events"in e){for(let t of e.events)this.addTrigger({event:t,onEvent:(i,s)=>e.onEvent(i,s)});return this}return n(this,ot).has(e.event)?n(this,ot).get(e.event)?.push(e.onEvent):n(this,ot).set(e.event,[e.onEvent]),U}static provide(e){n(this,Xr).push(e)}static use(e,t){n(this,Lt)[e.fullName]={def:e,options:t??{},handler:void 0};let i={};for(let s of Object.values(e.methods))i[s.name]=(o,d)=>n(this,Lt)[e.fullName].handler?.[s.name]?.(s.requestType?.fromPartial(o??{}),d);return n(this,j)[e.fullName]=i,i}static get redditAPIPlugins(){if(!Le(n(this,Ri).redditAPI))throw new Error("Reddit API is not enabled. You can enable it by passing `redditAPI: true` to `Devvit.configure`.");return{Flair:n(this,j)[k.FlairDefinition.fullName],GraphQL:n(this,j)[k.GraphQLDefinition.fullName],LinksAndComments:n(this,j)[k.LinksAndCommentsDefinition.fullName],Listings:n(this,j)[k.ListingsDefinition.fullName],Moderation:n(this,j)[k.ModerationDefinition.fullName],ModNote:n(this,j)[k.ModNoteDefinition.fullName],NewModmail:n(this,j)[k.NewModmailDefinition.fullName],PrivateMessages:n(this,j)[k.PrivateMessagesDefinition.fullName],Subreddits:n(this,j)[k.SubredditsDefinition.fullName],Users:n(this,j)[k.UsersDefinition.fullName],Widgets:n(this,j)[k.WidgetsDefinition.fullName],Wiki:n(this,j)[k.WikiDefinition.fullName]}}static get modLogPlugin(){let e=n(this,j)[k.ModlogDefinition.fullName];if(!e)throw new Error("ModLog is not enabled. You can enable it by passing `modLog: true` to `Devvit.configure`");return e}static get schedulerPlugin(){let e=n(this,j)[k.SchedulerDefinition.fullName];if(!e)throw new Error("Scheduler is not enabled. You can enable it by calling `Devvit.addSchedulerJob` at the top level of your app.");return e}static get kvStorePlugin(){let e=n(this,j)[k.KVStoreDefinition.fullName];if(!e)throw new Error("Key Value Store is not enabled. You can enable it by passing `kvStore: true` to `Devvit.configure`");return e}static get redisPlugin(){let e=n(this,j)[k.RedisAPIDefinition.fullName];if(!e)throw new Error("Redis is not enabled. You can enable it by passing `redis: true` to `Devvit.configure`");return e}static get mediaPlugin(){let e=n(this,j)[k.MediaServiceDefinition.fullName];if(!e)throw new Error("MediaService is not enabled. You can enable it by passing `media: true` to `Devvit.configure`");return e}static get settingsPlugin(){let e=n(this,j)[k.SettingsDefinition.fullName];if(!e)throw new Error("Settings must first be configured with `Devvit.addSettings()` before they can be accessed");return e}static get realtimePlugin(){let e=n(this,j)[k.RealtimeDefinition.fullName];if(!e)throw new Error("Realtime is not enabled. You can enable it by passing `realtime: true` to `Devvit.configure`");return e}static get menuItems(){return n(this,Bi)}static get customPostType(){return n(this,Ut)}static get formDefinitions(){return n(this,Dt)}static get scheduledJobHandlers(){return n(this,Nt)}static get installationSettings(){return n(this,Oi)}static get appSettings(){return n(this,Ti)}static get triggerOnEventHandlers(){return n(this,ot)}static get assets(){return n(this,Kr)}static get webViewAssets(){return n(this,Zr)}constructor(e){super(e),a(U,Kr,e.assets??{}),a(U,Zr,e.webviewAssets??{});for(let t in n(U,Lt)){let i=n(U,Lt)[t];i.handler=e.use(i.def,i.options)}n(U,Bi).length>0&&ul(e),n(U,Nt).size>0&&cl(e),n(U,Ut)&&(nl(e),su(e)),(n(U,Ut)||n(U,Dt).size>0)&&Tl(e),n(U,Oi)&&sl(e),n(U,Ti)&&_d(e),n(U,ot).size>0&&ml(e);for(let t of n(U,Xr))e.provides(t)}};Ti=new WeakMap,Kr=new WeakMap,Ri=new WeakMap,Ut=new WeakMap,Dt=new WeakMap,Oi=new WeakMap,Bi=new WeakMap,Nt=new WeakMap,ot=new WeakMap,Zr=new WeakMap,Xr=new WeakMap,Lt=new WeakMap,j=new WeakMap,U.debug={},l(U,Ti),l(U,Kr,{}),l(U,Ri,{}),l(U,Ut),l(U,Dt,new Map),l(U,Oi),l(U,Bi,[]),l(U,Nt,new Map),l(U,ot,new Map),l(U,Zr,{}),l(U,Xr,[]),l(U,Lt,{}),l(U,j,{});var u=U;(e=>{function r(t,i,...s){return{type:t,props:i,children:s}}e.createElement=r})(u||(u={}));function K(r){let e=Object.getOwnPropertyDescriptors(r.constructor.prototype);for(let[t,i]of Object.entries(e))i.get&&Object.defineProperty(r,t,{...i,enumerable:!0})}var Ua;(function(r){r[r.bold=1]="bold",r[r.italic=2]="italic",r[r.underline=4]="underline",r[r.strikethrough=8]="strikethrough",r[r.subscript=16]="subscript",r[r.superscript=32]="superscript",r[r.monospace=64]="monospace"})(Ua||(Ua={}));var ou="text",au="raw",du="br",lu="link",uu="c/",cu="p/",mu="r/",pu="u/",gu="@",hu="spoilertext",fu="par",bu="h",yu="hr",vu="blockquote",ku="code",Cu="li",Su="list",Pu="L",wu="R",Fu="C",xu="table",Iu="embed",Eu="img",Au="gif",Tu="video";function Ru(r){return{e:Au,id:r.mediaId,...r.caption&&{c:r.caption},...r.blur&&{o:r.blur}}}function Ou(r,e){let t={},i=[];return Object.assign(t,Qr(t,i),Yr(t,i),en(t,i),nn(t,i),sn(t,i),on(t,i)),e(t),{e:vu,c:i,...r.author&&{a:r.author}}}function Bu(r,e){let t={},i=[];return Object.assign(t,Na(t,i)),e(t),{e:ku,c:i,...r.language&&{l:r.language}}}function Mu(r){return{e:uu,t:r.permalink}}function Uu(r,e){let t={},i=[];return Object.assign(t,Na(t,i),rn(t,i)),e(t),{e:bu,l:r.level,c:i}}function Du(r){return{e:Iu,u:r.sourceUrl,c:r.contentUrl,x:r.width,y:r.height}}function Nu(){return{e:yu}}function Lu(r){return{e:Eu,id:r.mediaId,...r.caption&&{c:r.caption},...r.blur&&{o:r.blur}}}function _u(){return{e:du}}function Hu(r){return{e:lu,t:r.text,u:r.url,...r.formatting&&{f:r.formatting},...r.tooltip&&{a:r.tooltip}}}function ju(r,e){let t={},i=[];return Object.assign(t,rc(t,i)),e(t),{e:Su,o:r.ordered,c:i}}function Wu(r){let e={},t=[];return Object.assign(e,Qr(e,t),Yr(e,t),en(e,t),co(e,t),nn(e,t),sn(e,t),on(e,t)),r(e),{e:Cu,c:t}}function Vu(r){let e={},t=[];return Object.assign(e,mo(e,t),rn(e,t),Da(e,t),La(e,t),tn(e,t)),r(e),{e:fu,c:t}}function Gu(r){return{e:cu,t:r.permalink}}function Ju(r){return{e:au,t:r}}function zu(r){let e={},t=[];return Object.assign(e,mo(e,t),rn(e,t),Da(e,t)),r(e),{e:hu,c:t}}function qu(r){return{e:mu,t:r.subredditName,l:r.showPrefix}}function $u(r){let e={},t=[],i=[];return Object.assign(e,nc(e,t,i)),r(e),{e:xu,h:t,c:i}}function Ku(r){let[e,t]=ic();return r(e),{c:t}}function Zu(r,e){let[t,i]=ic();e(t);let s;switch(r.columnAlignment){case"left":s=Pu;break;case"right":s=wu;break;case"center":s=Fu;break}return{...s&&{a:s},...i&&{c:i}}}function Xu(r){let e={},t=[];return Object.assign(e,sc(e,t)),r(e),t}function Qu(r){return{e:ou,t:r.text,...r.formatting&&{f:r.formatting}}}function Yu(r){return{e:pu,t:r.username,l:r.showPrefix}}function ec(r){return{e:gu,t:r.username,l:r.showPrefix}}function tc(r){return{e:Tu,id:r.mediaId,...r.caption&&{c:r.caption},...r.blur&&{o:r.blur},...r.thumbnail&&{p:r.thumbnail},...r.convertToGif&&{gifify:r.convertToGif}}}function ic(){let r={},e=[];return Object.assign(r,mo(r,e),rn(r,e),La(r,e),tn(r,e)),[r,e]}function Qr(r,e){return{blockQuote(t,i){return e.push(Ou(t,i)),r}}}function Yr(r,e){return{codeBlock(t,i){return e.push(Bu(t,i)),r}}}function oc(r,e){return{embed(t){return e.push(Du(t)),r}}}function en(r,e){return{heading(t,i){return e.push(Uu(t,i)),r}}}function co(r,e){return{horizontalRule(){return e.push(Nu()),r}}}function tn(r,e){return{image(t){return e.push(Lu(t)),r},animatedImage(t){return e.push(Ru(t)),r}}}function Da(r,e){return{linebreak(){return e.push(_u()),r}}}function rn(r,e){return{link(t){return e.push(Hu(t)),r},commentLink(t){return e.push(Mu(t)),r},postLink(t){return e.push(Gu(t)),r},subredditLink(t){return e.push(qu(t)),r},userLink(t){return e.push(Yu(t)),r},userMention(t){return e.push(ec(t)),r}}}function nn(r,e){return{list(t,i){return e.push(ju(t,i)),r}}}function rc(r,e){return{item(t){return e.push(Wu(t)),r}}}function sn(r,e){return{paragraph(t){return e.push(Vu(t)),r}}}function Na(r,e){return{rawText(t){return e.push(Ju(t)),r}}}function La(r,e){return{spoiler(t){return e.push(zu(t)),r}}}function nc(r,e,t){return{headerCell(i,s){return e.push(Zu(i,s)),r},row(i){return t.push(Xu(i)),r}}}function on(r,e){return{table(t){return e.push($u(t)),r}}}function sc(r,e){return{cell(t){return e.push(Ku(t)),r}}}function mo(r,e){return{text(t){return e.push(Qu(t)),r}}}function ac(r,e){return{video(t){return e.push(tc(t)),r}}}var Dp=function(r,e,t,i,s){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},Np=function(r,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(r):i?i.value:e.get(r)},po,_t=class{constructor(){po.set(this,void 0);let e=[];Object.assign(this,sn(this,e),en(this,e),co(this,e),Qr(this,e),Yr(this,e),oc(this,e),nn(this,e),on(this,e),tn(this,e),ac(this,e)),Dp(this,po,{document:e},"f")}build(){return JSON.stringify(Np(this,po,"f"))}paragraph(e){return this}heading(e,t){return this}horizontalRule(){return this}blockQuote(e,t){return this}codeBlock(e,t){return this}embed(e){return this}list(e,t){return this}table(e){return this}image(e){return this}animatedImage(e){return this}video(e){return this}};po=new WeakMap;function Mi(r){let e;return r instanceof _t?e=r.build():typeof r=="object"?e=JSON.stringify(r):e=r,e}var dc=100,lc=1/0,Ht,jt,at,Ui,Di,go,W=class{constructor(e){l(this,Di);l(this,Ht);l(this,jt);l(this,at);l(this,Ui,!1);this.pageSize=dc;this.limit=lc;this.children=[];K(this),this._fetch=e.fetch,this.pageSize=e.pageSize??dc,this.limit=e.limit??lc,a(this,jt,e.after),a(this,Ht,e.before),a(this,at,e.more),e.children&&(this.children=e.children)}get hasMore(){return!n(this,Ui)||!!(n(this,jt)||n(this,Ht)||n(this,at))}async*[Symbol.asyncIterator](){let e=0;for(;;){if(e===this.children.length)if(this.hasMore){if((await h(this,Di,go).call(this)).length===0)break}else break;if(yield this.children[e],e++,e===this.limit)break}}setMore(e){a(this,at,e)}preventInitialFetch(){a(this,Ui,!0)}async all(){for(;this.hasMore&&this.children.length<this.limit;)await h(this,Di,go).call(this);return this.children.slice(0,this.limit)}async get(e){let t=e<=this.limit?e:this.limit;for(;this.hasMore&&this.children.length<t;)await h(this,Di,go).call(this);return this.children.slice(0,t)}};Ht=new WeakMap,jt=new WeakMap,at=new WeakMap,Ui=new WeakMap,Di=new WeakSet,go=async function(){if(!this.hasMore)throw new Error("This listing does not have any more items to load.");let{children:e,before:t,after:i,more:s}=await this._fetch({before:n(this,Ht),after:n(this,jt),limit:this.pageSize,more:n(this,at)});return this.children.push(...e),a(this,Ht,t),a(this,jt,i),a(this,at,s),a(this,Ui,!0),e};var an,_a,ve=class{constructor(){}static get(e,t){let i=u.redditAPIPlugins.ModNote;return new W({hasMore:!0,before:e.before,limit:e.limit,pageSize:e.limit,fetch:async s=>{let o=await i.GetNotes({subreddit:e.subreddit,user:e.user,filter:e.filter,before:s.before,limit:s.limit},t);return{children:o.modNotes?.map(d=>h(this,an,_a).call(this,d))||[],before:o.hasNextPage?o.endCursor:void 0,hasMore:o.hasNextPage}}})}static async delete(e,t){let i=u.redditAPIPlugins.ModNote,{deleted:s}=await i.DeleteNotes(e,t);return!!s}static async add(e,t){let s=await u.redditAPIPlugins.ModNote.PostNotes(e,t);if(!s?.created)throw new Error("Failed to create mod note");return h(this,an,_a).call(this,s.created)}static async addRemovalNote(e,t){await u.redditAPIPlugins.ModNote.PostRemovalNote(e,t)}};an=new WeakSet,_a=function(e){return p(e.id,"Mod note ID is null or undefined"),p(e.createdAt,"Mod note createdAt is null or undefined"),p(e.type,"Mod note type is null or undefined"),p(e.subreddit,"Mod note subreddit is null or undefined"),p(e.subredditId,"Mod note subredditId is null or undefined"),p(e.operator,"Mod note operator is null or undefined"),p(e.operatorId,"Mod note operatorId is null or undefined"),p(e.user,"Mod note user is null or undefined"),p(e.userId,"Mod note userId is null or undefined"),p(e.userNoteData,"Mod note userNote is null or undefined"),p(e.modActionData,"Mod note modAction is null or undefined"),{id:e.id,user:{id:te(e.userId??""),name:e.user},subreddit:{id:$(e.subredditId??""),name:e.subreddit},operator:{id:te(e.operatorId??""),name:e.operator},createdAt:new Date(e.createdAt*1e3),userNote:{note:e.userNoteData?.note,redditId:e.userNoteData?.redditId?fe(e.userNoteData?.redditId):void 0,label:e.userNoteData?.label},type:e.type}},l(ve,an);var Q=class{static queryWithQueryString(e,t){return u.redditAPIPlugins.GraphQL.Query({query:e},t)}static query(e,t,i,s){return u.redditAPIPlugins.GraphQL.PersistedQuery({operationName:e,id:t,variables:i},s)}};var uc=["all","wiki","posts","access","mail","config","flair","channels","chat_config","chat_operator","community_chat"];function Lp(r,e){return e.map(t=>(r.includes(t)?"+":"-")+t).join(",")}function Ha(r){return Lp(r,uc)}function cc(r){return r.filter(e=>uc.includes(e))}import"@devvit/protos";var _p=(t=>(t.User="USER_FLAIR",t.Post="LINK_FLAIR",t))(_p||{}),Wt,Ni,Li,_i,Hi,ji,Wi,Vi,Gi,Ji,zi,ho,xe=class xe{constructor(e,t,i){l(this,Wt);l(this,Ni);l(this,Li);l(this,_i);l(this,Hi);l(this,ji);l(this,Wi);l(this,Vi);l(this,Gi);l(this,Ji);K(this),p(e.id),p(e.text),a(this,Wt,e.id),a(this,Ni,t),a(this,Li,e.text),a(this,_i,Hp(e.textColor)),a(this,Hi,jp(e.backgroundColor)),a(this,ji,Wp(e.allowableContent)),a(this,Wi,e.modOnly),a(this,Vi,e.maxEmojis),a(this,Gi,e.textEditable),a(this,Ji,i)}get id(){return n(this,Wt)}get text(){return n(this,Li)}get textColor(){return n(this,_i)}get backgroundColor(){return n(this,Hi)}get allowableContent(){return n(this,ji)}get modOnly(){return n(this,Wi)}get maxEmojis(){return n(this,Vi)}get allowUserEdits(){return n(this,Gi)}async delete(){return xe.deleteFlairTemplate(n(this,Wt),n(this,Ni),n(this,Ji))}async edit(e){return xe.editFlairTemplate({id:n(this,Wt),subredditName:n(this,Ni),text:e.text??n(this,Li),allowableContent:e.allowableContent??n(this,ji),backgroundColor:e.backgroundColor??n(this,Hi),maxEmojis:e.maxEmojis??n(this,Vi),modOnly:e.modOnly??n(this,Wi),textColor:e.textColor??n(this,_i),allowUserEdits:e.allowUserEdits??n(this,Gi)},n(this,Ji))}static async createPostFlairTemplate(e,t){var i;return h(i=xe,zi,ho).call(i,{...e,flairType:"LINK_FLAIR"},t)}static async createUserFlairTemplate(e,t){var i;return h(i=xe,zi,ho).call(i,{...e,flairType:"USER_FLAIR"},t)}static async editFlairTemplate(e,t){var i;return h(i=xe,zi,ho).call(i,e,t)}static async getPostFlairTemplates(e,t){return(await u.redditAPIPlugins.Flair.LinkFlair({subreddit:e},t)).flair?.map(o=>new xe(o,e,t))||[]}static async getUserFlairTemplates(e,t){return(await u.redditAPIPlugins.Flair.UserFlair({subreddit:e},t)).flair?.map(o=>new xe(o,e,t))||[]}static async deleteFlairTemplate(e,t,i){await u.redditAPIPlugins.Flair.DeleteFlairTemplate({subreddit:e,flairTemplateId:t},i)}};Wt=new WeakMap,Ni=new WeakMap,Li=new WeakMap,_i=new WeakMap,Hi=new WeakMap,ji=new WeakMap,Wi=new WeakMap,Vi=new WeakMap,Gi=new WeakMap,Ji=new WeakMap,zi=new WeakSet,ho=async function(e,t){let{subredditName:i,allowableContent:s="all",backgroundColor:o="transparent",flairType:d="",maxEmojis:c=10,modOnly:m=!1,text:b,textColor:y="dark",allowUserEdits:f=!1,id:S=""}=e;if(m&&f)throw new Error("Cannot have a mod only flair that is editable by users");let O=await u.redditAPIPlugins.Flair.FlairTemplate({subreddit:i,allowableContent:s,backgroundColor:o,flairType:d,maxEmojis:c,modOnly:m,text:b,textColor:y,textEditable:f,flairTemplateId:S,cssClass:"",overrideCss:!1},t);return new xe(O,i,t)},l(xe,zi);var ne=xe;function dn(r){return{flairCssClass:r.flairCssClass,user:r.user,flairText:r.flairText}}var Oe,ja,mc,Wa,dt=class dt{static async getUserFlairBySubreddit(e,t){return u.redditAPIPlugins.Flair.FlairList(e,t)}static setUserFlair(e,t){var i;return h(i=dt,Oe,ja).call(i,e,t)}static setUserFlairBatch(e,t,i){var s;return h(s=dt,Oe,mc).call(s,e,t,i)}static setPostFlair(e,t){var i;return h(i=dt,Oe,ja).call(i,{...e,postId:de(e.postId)},t)}static async removePostFlair(e,t,i){var s;return h(s=dt,Oe,Wa).call(s,e,t,void 0,i)}static async removeUserFlair(e,t,i){var s;return h(s=dt,Oe,Wa).call(s,e,void 0,t,i)}};Oe=new WeakSet,ja=async function(e,t){await u.redditAPIPlugins.Flair.SelectFlair({subreddit:e.subredditName,flairTemplateId:e.flairTemplateId??"",text:e.text??"",name:e.username,link:e.postId,backgroundColor:e.backgroundColor??"",textColor:e.textColor??"dark",cssClass:e.cssClass??"",returnRtjson:"none"},t)},mc=async function(e,t,i){if(!t.length)return[];if(t.length>100)throw new Error("Unexpected input: flairs array cannot be longer than 100 entries.");let o=",",d=t.map(b=>{for(let y in b)if(b[y]?.includes(o))throw new Error(`Unexpected input: ${y} cannot contain the "," character`);return[b.username,b.text||"",b.cssClass||""].join(o)}).join(`
|
|
4
|
+
`);return(await u.redditAPIPlugins.Flair.FlairCsv({subreddit:e,flairCsv:d},i)).result},Wa=async function(e,t,i,s){await u.redditAPIPlugins.Flair.SelectFlair({subreddit:e,name:i??"",link:t??"",flairTemplateId:"",backgroundColor:"",text:"",textColor:"",cssClass:"",returnRtjson:"none"},s)},l(dt,Oe);var ce=dt;function Hp(r){if(p(r,"Flair text color is required"),r==="light"||r==="dark")return r;throw new Error(`Invalid flair text color: ${r}`)}function jp(r){if(!r||r.length===0||r==="transparent")return"transparent";if(/^#([A-Fa-f0-9]{6})$/.test(r))return r;throw new Error(`Invalid flair background color: ${r}`)}function Wp(r){if(r==="all"||r==="text"||r==="emoji")return r;throw new Error(`Invalid allowable content: ${r}`)}import"@devvit/protos";import{Block as fc,UIResponse as Xp}from"@devvit/protos";var Ja=ed(hc(),1);var Ga=r=>"text"in r?r.text:Zp(r.richtext),Zp=r=>r instanceof _t?r.build():typeof r=="object"?JSON.stringify(r):r;var Qp={NONE:0,BLOCKS:1,UNRECOGNIZED:-1},qi,un,$i,cn,Ki,mn,pn,gn,Gt,hn,fn,bn,yn,vn,kn,lt,Cn,Sn,Jt,Zi,ut,Xi,Qi,Yi,ct,mt,pt,er,gt,ht,ft,je,Pn,wn,tr,ir,M,D=class D{constructor(e,t){l(this,qi);l(this,un);l(this,$i);l(this,cn);l(this,Ki);l(this,mn);l(this,pn);l(this,gn);l(this,Gt);l(this,hn);l(this,fn);l(this,bn);l(this,yn);l(this,vn);l(this,kn);l(this,lt);l(this,Cn);l(this,Sn);l(this,Jt);l(this,Zi);l(this,ut);l(this,Xi);l(this,Qi);l(this,Yi);l(this,ct);l(this,mt);l(this,pt);l(this,er);l(this,gt);l(this,ht);l(this,ft);l(this,je);l(this,Pn);l(this,wn);l(this,tr);l(this,ir);l(this,M);K(this),p(e.id,"Post is missing id"),p(e.title,"Post is missing title"),p(e.createdUtc,"Post is missing created date"),p(e.author,"Post is missing author name"),p(e.subreddit,"Post is missing subreddit name"),p(e.subredditId,"Post is missing subreddit id"),p(e.url,"Post is missing url"),p(e.permalink,"Post is missing permalink"),a(this,qi,de(`t3_${e.id}`)),a(this,$i,e.author),a(this,un,e.authorFullname?te(e.authorFullname):void 0),a(this,Ki,$(e.subredditId)),a(this,mn,e.subreddit),a(this,bn,e.score??0),a(this,yn,e.numComments??0),a(this,vn,e.numReports??0);let i=new Date(0);i.setUTCSeconds(e.createdUtc),a(this,cn,i),a(this,gn,e.title),a(this,Gt,e.selftext),a(this,hn,e.selftextHtml),a(this,fn,e.url),a(this,pn,e.permalink),e.thumbnail&&e.thumbnail!=="self"&&e.thumbnail!=="nsfw"&&e.thumbnailHeight!=null&&e.thumbnailWidth!=null&&a(this,kn,{url:e.thumbnail,height:e.thumbnailHeight,width:e.thumbnailWidth}),a(this,lt,e.approved??!1),a(this,Cn,e.approvedAtUtc??0),a(this,Sn,e.bannedAtUtc??0),a(this,ut,e.removed??!1),a(this,Xi,e.removedBy),a(this,Qi,e.removedByCategory),a(this,Jt,e.spam??!1),a(this,Zi,e.stickied??!1),a(this,Yi,e.archived??!1),a(this,ct,e.edited??!1),a(this,mt,e.locked??!1),a(this,pt,e.over18??!1),a(this,er,e.quarantine??!1),a(this,gt,e.spoiler),a(this,ht,e.hidden??!1),a(this,ft,e.ignoreReports??!1),a(this,je,e.distinguished),a(this,wn,e.secureMedia),a(this,tr,(e.modReports??[]).map(([s])=>s)),a(this,ir,(e.userReports??[]).map(([s])=>s)),a(this,M,t),(e.linkFlairBackgroundColor||e.linkFlairCssClass||e.linkFlairText||e.linkFlairType||e.linkFlairTemplateId||e.linkFlairRichtext||e.linkFlairTextColor)&&a(this,Pn,{backgroundColor:e.linkFlairBackgroundColor,cssClass:e.linkFlairCssClass,text:e.linkFlairText,type:e.linkFlairType,templateId:e.linkFlairTemplateId,richtext:(e.linkFlairRichtext??[]).map(({e:s,t:o,a:d,u:c})=>({elementType:s,text:o,emojiRef:d,url:c})),textColor:e.linkFlairTextColor})}get id(){return n(this,qi)}get authorId(){return n(this,un)}get authorName(){return n(this,$i)}get subredditId(){return n(this,Ki)}get subredditName(){return n(this,mn)}get permalink(){return n(this,pn)}get title(){return n(this,gn)}get body(){return n(this,Gt)}get bodyHtml(){return n(this,hn)}get url(){return n(this,fn)}get thumbnail(){return n(this,kn)}get createdAt(){return n(this,cn)}get score(){return n(this,bn)}get numberOfComments(){return n(this,yn)}get numberOfReports(){return n(this,vn)}get approved(){return n(this,lt)}get approvedAtUtc(){return n(this,Cn)}get bannedAtUtc(){return n(this,Sn)}get spam(){return n(this,Jt)}get stickied(){return n(this,Zi)}get removed(){return n(this,ut)}get removedBy(){return n(this,Xi)}get removedByCategory(){return n(this,Qi)}get archived(){return n(this,Yi)}get edited(){return n(this,ct)}get locked(){return n(this,mt)}get nsfw(){return n(this,pt)}get quarantined(){return n(this,er)}get spoiler(){return n(this,gt)}get hidden(){return n(this,ht)}get ignoringReports(){return n(this,ft)}get distinguishedBy(){return n(this,je)}get comments(){return X.getComments({postId:this.id},n(this,M))}get flair(){return n(this,Pn)}get secureMedia(){return n(this,wn)}get userReportReasons(){return n(this,ir)}get modReportReasons(){return n(this,tr)}toJSON(){return{id:this.id,authorId:this.authorId,authorName:this.authorName,subredditId:this.subredditId,subredditName:this.subredditName,permalink:this.permalink,title:this.title,body:this.body,bodyHtml:this.bodyHtml,url:this.url,thumbnail:this.thumbnail,score:this.score,numberOfComments:this.numberOfComments,numberOfReports:this.numberOfReports,createdAt:this.createdAt,approved:this.approved,spam:this.spam,stickied:this.stickied,removed:this.removed,removedBy:n(this,Xi),removedByCategory:n(this,Qi),archived:this.archived,edited:this.edited,locked:this.locked,nsfw:this.nsfw,quarantined:this.quarantined,spoiler:this.spoiler,hidden:this.hidden,ignoringReports:this.ignoringReports,distinguishedBy:this.distinguishedBy,flair:this.flair,secureMedia:this.secureMedia,modReportReasons:n(this,tr),userReportReasons:n(this,ir)}}isApproved(){return n(this,lt)}isSpam(){return n(this,Jt)}isStickied(){return n(this,Zi)}isRemoved(){return n(this,ut)}isArchived(){return n(this,Yi)}isEdited(){return n(this,ct)}isLocked(){return n(this,mt)}isNsfw(){return n(this,pt)}isQuarantined(){return n(this,er)}isSpoiler(){return n(this,gt)}isHidden(){return n(this,ht)}isIgnoringReports(){return n(this,ft)}isDistinguishedBy(){return n(this,je)}async edit(e){let t=await D.edit({id:this.id,...e},n(this,M));a(this,Gt,t.body),a(this,ct,t.edited)}async setSuggestedCommentSort(e){await D.setSuggestedCommentSort({id:this.id,subredditId:n(this,Ki),suggestedSort:e},n(this,M))}async setCustomPostPreview(e){await D.setCustomPostPreview({id:this.id,ui:e},n(this,M))}async setTextFallback(e){let t=await D.setTextFallback(e,this.id,n(this,M));a(this,Gt,t.body),a(this,ct,t.edited)}async addComment(e){return X.submit({id:this.id,...e},n(this,M))}async delete(){return D.delete(this.id,n(this,M))}async approve(){await D.approve(this.id,n(this,M)),a(this,lt,!0),a(this,ut,!1)}async remove(e=!1){await D.remove(this.id,e,n(this,M)),a(this,ut,!0),a(this,Jt,e),a(this,lt,!1)}async lock(){await D.lock(this.id,n(this,M)),a(this,mt,!0)}async unlock(){await D.unlock(this.id,n(this,M)),a(this,mt,!1)}async hide(){await D.hide(this.id,n(this,M)),a(this,ht,!0)}async unhide(){await D.unhide(this.id,n(this,M)),a(this,ht,!1)}async markAsNsfw(){await D.markAsNsfw(this.id,n(this,M)),a(this,pt,!0)}async unmarkAsNsfw(){await D.unmarkAsNsfw(this.id,n(this,M)),a(this,pt,!1)}async markAsSpoiler(){await D.markAsSpoiler(this.id,n(this,M)),a(this,gt,!0)}async unmarkAsSpoiler(){await D.unmarkAsSpoiler(this.id,n(this,M)),a(this,gt,!1)}async sticky(e){await D.sticky(this.id,e,n(this,M))}async unsticky(){await D.unsticky(this.id,n(this,M))}async distinguish(){let{distinguishedBy:e}=await D.distinguish(this.id,!1,n(this,M));a(this,je,e)}async distinguishAsAdmin(){let{distinguishedBy:e}=await D.distinguish(this.id,!0,n(this,M));a(this,je,e)}async undistinguish(){let{distinguishedBy:e}=await D.undistinguish(this.id,n(this,M));a(this,je,e)}async ignoreReports(){await D.ignoreReports(this.id,n(this,M)),a(this,ft,!0)}async unignoreReports(){await D.unignoreReports(this.id,n(this,M)),a(this,ft,!1)}async getAuthor(){return C.getByUsername(n(this,$i),n(this,M))}async crosspost(e){return D.crosspost({...e,postId:this.id},n(this,M))}addRemovalNote(e){return ve.addRemovalNote({itemIds:[n(this,qi)],...e},n(this,M))}async getEnrichedThumbnail(){return Yp({id:this.id},n(this,M))}static async getById(e,t){let i=u.redditAPIPlugins.LinksAndComments,s=Pt(e)?e:`t3_${e}`,o=await i.Info({subreddits:[],thingIds:[s]},t);if(!o.data?.children?.length)throw new Error("could not find post");let d=o.data.children[0];if(!d?.data)throw new Error("could not find post");return new D(d.data,t)}static async submit(e,t){let i=u.redditAPIPlugins.LinksAndComments,s;if("preview"in e){p(t,"Missing metadata in `SubmitPostOptions`");let c=await new Ne(()=>e.preview,void 0,{},t,void 0).buildBlocksUI(),m=fc.encode(c).finish(),{textFallback:b,...y}=e,f=b?Ga(b):"",S={kind:"custom",sr:e.subredditName,richtextJson:(0,Ja.fromByteArray)(m),richtextFallback:f,...y};s=await i.SubmitCustomPost(S,t)}else s=await i.Submit({kind:"kind"in e?e.kind:"url"in e?"link":"self",sr:e.subredditName,richtextJson:"richtext"in e?Mi(e.richtext):void 0,...e},t);if("kind"in e&&["image","video","videogif"].includes(e.kind)&&!s.json?.data?.id&&"url"in e)throw new Error(`Post of ${e.kind} type with ${e.url} is being created asynchronously and should be updated in the subreddit soon.`);if(!s.json?.data?.id||s.json?.errors?.length)throw new Error(`failed to submit post - either post ID is empty or request failed with errors: ${s.json?.errors}`);return D.getById(`t3_${s.json.data.id}`,t)}static async crosspost(e,t){let i=u.redditAPIPlugins.LinksAndComments,{postId:s,subredditName:o,...d}=e,c=await i.Submit({kind:"crosspost",sr:o,crosspostFullname:de(s),...d},t);if(!c.json?.data?.id||c.json?.errors?.length)throw new Error("failed to crosspost post");return D.getById(`t3_${c.json.data.id}`,t)}static async edit(e,t){let i=u.redditAPIPlugins.LinksAndComments,{id:s}=e,o;if("richtext"in e&&(o=Mi(e.richtext)),(await i.EditUserText({thingId:s,text:"text"in e?e.text:"",richtextJson:o},t)).json?.errors?.length)throw new Error("Failed to edit post");return D.getById(s,t)}static async setSuggestedCommentSort(e,t){if(!(await Q.query("SetSuggestedSort","cf6052acc7fefaa65b710625b81dba8041f258313aafe9730e2a3dc855e5d10d",{input:{subredditId:e.subredditId,postId:e.id,sort:e.suggestedSort}},t)).data?.setSuggestedSort?.ok)throw new Error("Failed to set suggested sort")}static async setCustomPostPreview(e,t){if(!t)throw new Error("Failed to set custom post preview. Metadata not found");let i=u.redditAPIPlugins.LinksAndComments,s=new Mt(e.ui),d=Xp.fromJSON(await s.handle({events:[]},t)).blocks,c=(0,Ja.fromByteArray)(fc.encode(d).finish());await i.SetCustomPostPreview({thingId:e.id,bodyType:Qp.BLOCKS,blocksRenderContent:c},t)}static async setTextFallback(e,t,i){if(!("text"in e)&&!("richtext"in e))throw new Error(`No text fallback provided for post ${t}.`);let s=u.redditAPIPlugins.LinksAndComments,o=Ga(e);if((await s.EditCustomPost({thingId:t,richtextFallback:o},i)).json?.errors?.length)throw new Error("Failed to set post text fallback");return D.getById(t,i)}static async delete(e,t){await u.redditAPIPlugins.LinksAndComments.Del({id:e},t)}static async approve(e,t){await u.redditAPIPlugins.Moderation.Approve({id:e},t)}static async remove(e,t=!1,i){await u.redditAPIPlugins.Moderation.Remove({id:e,spam:t},i)}static async hide(e,t){await u.redditAPIPlugins.LinksAndComments.Hide({id:e},t)}static async unhide(e,t){await u.redditAPIPlugins.LinksAndComments.Unhide({id:e},t)}static async markAsNsfw(e,t){await u.redditAPIPlugins.LinksAndComments.MarkNSFW({id:e},t)}static async unmarkAsNsfw(e,t){await u.redditAPIPlugins.LinksAndComments.UnmarkNSFW({id:e},t)}static async markAsSpoiler(e,t){await u.redditAPIPlugins.LinksAndComments.Spoiler({id:e},t)}static async unmarkAsSpoiler(e,t){await u.redditAPIPlugins.LinksAndComments.Unspoiler({id:e},t)}static async sticky(e,t,i){await u.redditAPIPlugins.LinksAndComments.SetSubredditSticky({id:e,state:!0,num:t},i)}static async unsticky(e,t){await u.redditAPIPlugins.LinksAndComments.SetSubredditSticky({id:e,state:!1},t)}static async lock(e,t){await u.redditAPIPlugins.LinksAndComments.Lock({id:e},t)}static async unlock(e,t){await u.redditAPIPlugins.LinksAndComments.Unlock({id:e},t)}static async distinguish(e,t,i){let d=(await u.redditAPIPlugins.Moderation.Distinguish({id:e,how:t?"admin":"yes",sticky:!1},i)).json?.data?.things?.[0]?.data;return p(d),{distinguishedBy:d.distinguished}}static async undistinguish(e,t){let o=(await u.redditAPIPlugins.Moderation.Distinguish({id:e,how:"no",sticky:!1},t)).json?.data?.things?.[0]?.data;return p(o),{distinguishedBy:o.distinguished}}static async ignoreReports(e,t){await u.redditAPIPlugins.Moderation.IgnoreReports({id:e},t)}static async unignoreReports(e,t){await u.redditAPIPlugins.Moderation.UnignoreReports({id:e},t)}static getControversialPosts(e={},t){return this.getSortedPosts({...e,sort:"controversial"},t)}static getTopPosts(e={},t){return this.getSortedPosts({...e,sort:"top"},t)}static getSortedPosts(e,t){let i=u.redditAPIPlugins.Listings;return new W({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,fetch:async s=>{let o=await i.Sort({show:"all",sort:e.sort,t:e.timeframe,subreddit:e.subredditName,...s},t);return ln(o,t)}})}static getHotPosts(e={location:"GLOBAL"},t){let i=u.redditAPIPlugins.Listings;return new W({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,fetch:async s=>{let o=await i.Hot({g:e.location,show:"all",subreddit:e.subredditName,...s},t);return ln(o,t)}})}static getNewPosts(e,t){let i=u.redditAPIPlugins.Listings;return new W({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,fetch:async s=>{let o=await i.New({show:"all",subreddit:e.subredditName,...s},t);return ln(o,t)}})}static getRisingPosts(e,t){let i=u.redditAPIPlugins.Listings;return new W({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,fetch:async s=>{let o=await i.Rising({show:"all",subreddit:e.subredditName,...s},t);return ln(o,t)}})}static getPostsByUser(e,t){let i=u.redditAPIPlugins.Users;return new W({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,async fetch(s){let o=await i.UserWhere({username:e.username,where:"submitted",...s},t);return ln(o,t)}})}};qi=new WeakMap,un=new WeakMap,$i=new WeakMap,cn=new WeakMap,Ki=new WeakMap,mn=new WeakMap,pn=new WeakMap,gn=new WeakMap,Gt=new WeakMap,hn=new WeakMap,fn=new WeakMap,bn=new WeakMap,yn=new WeakMap,vn=new WeakMap,kn=new WeakMap,lt=new WeakMap,Cn=new WeakMap,Sn=new WeakMap,Jt=new WeakMap,Zi=new WeakMap,ut=new WeakMap,Xi=new WeakMap,Qi=new WeakMap,Yi=new WeakMap,ct=new WeakMap,mt=new WeakMap,pt=new WeakMap,er=new WeakMap,gt=new WeakMap,ht=new WeakMap,ft=new WeakMap,je=new WeakMap,Pn=new WeakMap,wn=new WeakMap,tr=new WeakMap,ir=new WeakMap,M=new WeakMap;var V=D;function ln(r,e){if(!r.data?.children)throw new Error("Listing response is missing children");return{children:r.data.children.map(i=>new V(i.data,e)),before:r.data.before,after:r.data.after}}async function Yp(r,e){let o=(await Q.query("GetThumbnailV2","81580ce4e23d748c5a59a1618489b559bf4518b6a73af41f345d8d074c8b2ce9",{id:r.id},e)).data?.postInfoById?.thumbnailV2;if(o){if(!o.image)return}else throw new Error("Failed to get thumbnail");return{attribution:o.attribution,image:{url:o.image.url,width:o.image.dimensions.width,height:o.image.dimensions.height},isObfuscatedDefault:o.isObfuscatedDefault,...o.obfuscatedImage&&{obfuscatedImage:{url:o.obfuscatedImage.url,width:o.obfuscatedImage.dimensions.width,height:o.obfuscatedImage.dimensions.height}}}}var eg=(_=>(_.Custom="CUSTOM",_.Reddit="REDDIT",_.Instagram="INSTAGRAM",_.Twitter="TWITTER",_.Tiktok="TIKTOK",_.Twitch="TWITCH",_.Facebook="FACEBOOK",_.Youtube="YOUTUBE",_.Tumblr="TUMBLR",_.Spotify="SPOTIFY",_.Soundcloud="SOUNDCLOUD",_.Beacons="BEACONS",_.Linktree="LINKTREE",_.Discord="DISCORD",_.Venmo="VENMO",_.CashApp="CASH_APP",_.Patreon="PATREON",_.Kofi="KOFI",_.Paypal="PAYPAL",_.Cameo="CAMEO",_.Onlyfans="ONLYFANS",_.Substack="SUBSTACK",_.Kickstarter="KICKSTARTER",_.Indiegogo="INDIEGOGO",_.BuyMeACoffee="BUY_ME_A_COFFEE",_.Shopify="SHOPIFY",_))(eg||{}),Fn,rr,xn,In,En,An,Tn,bt,Rn,On,Bn,Me,zt=class zt{constructor(e,t){l(this,Fn);l(this,rr);l(this,xn);l(this,In);l(this,En);l(this,An);l(this,Tn);l(this,bt,new Map);l(this,Rn);l(this,On);l(this,Bn);l(this,Me);K(this),p(e.id,"User ID is missing or undefined"),p(e.name,"Username is missing or undefined"),p(e.createdUtc,"User is missing created date"),a(this,Fn,te(Bs(e.id)?e.id:`t2_${e.id}`)),a(this,rr,e.name),a(this,An,e.over18??!1),a(this,Tn,e.isEmployee??!1);let i=new Date(0);if(i.setUTCSeconds(e.createdUtc),a(this,xn,i),a(this,In,e.linkKarma??0),a(this,En,e.commentKarma??0),e.modPermissions)for(let[s,o]of Object.entries(e.modPermissions))n(this,bt).set(s,cc(o));a(this,Rn,new URL(e.subreddit?.url??"","https://www.reddit.com").toString()),a(this,On,e.subreddit?.url??""),a(this,Bn,e.hasVerifiedEmail??!1),a(this,Me,t)}get id(){return n(this,Fn)}get username(){return n(this,rr)}get createdAt(){return n(this,xn)}get linkKarma(){return n(this,In)}get commentKarma(){return n(this,En)}get nsfw(){return n(this,An)}get isAdmin(){return n(this,Tn)}get modPermissions(){return n(this,bt)}get url(){return n(this,Rn)}get permalink(){return n(this,On)}get hasVerifiedEmail(){return n(this,Bn)}toJSON(){return{id:this.id,username:this.username,createdAt:this.createdAt,linkKarma:this.linkKarma,commentKarma:this.commentKarma,nsfw:this.nsfw,modPermissionsBySubreddit:Object.fromEntries(this.modPermissions)}}async getModPermissionsForSubreddit(e){if(n(this,bt).has(e))return n(this,bt).get(e);let t=await zt.getSubredditUsersByType({subredditName:e,type:"moderators",username:this.username},n(this,Me)).all();if(t.length===0)return[];let i=t[0].modPermissions.get(e)??[];return i.length>0&&n(this,bt).set(e,i),i}getComments(e){return X.getCommentsByUser({username:this.username,...e},n(this,Me))}getPosts(e){return V.getPostsByUser({username:this.username,...e},n(this,Me))}async getUserFlairBySubreddit(e){let t=await ce.getUserFlairBySubreddit({subreddit:e,name:n(this,rr)},n(this,Me));return t.users[0]?dn(t.users[0]):void 0}getSnoovatarUrl(){return zt.getSnoovatarUrl(this.username,n(this,Me))}async getSocialLinks(){let i=await Q.query("GetUserSocialLinks","2aca18ef5f4fc75fb91cdaace3e9aeeae2cb3843b5c26ad511e6f01b8521593a",{name:this.username},n(this,Me));return i.data?.user?.profile?.socialLinks?i.data.user.profile.socialLinks.map(s=>({...s,handle:s.handle??void 0})):[]}static async getById(e,t){let i=await bc(e,t);return i==null?void 0:zt.getByUsername(i,t)}static async getByUsername(e,t){let i=u.redditAPIPlugins.Users;try{let s=await i.UserAbout({username:e},t);if(s.data?.id)return new zt(s.data,t)}catch(s){if(s instanceof Error&&s.message.includes("404 Not Found"))return;throw s}}static async getFromMetadata(e,t){p(t);let i=t?.[e]?.values[0];return i?zt.getById(te(i),t):Promise.resolve(void 0)}static getSubredditUsersByType(e,t){let i=u.redditAPIPlugins.Subreddits;return new W({hasMore:!0,pageSize:e.pageSize,limit:e.limit,after:e.after,before:e.before,fetch:async s=>{let o=await i.AboutWhere({where:e.type,user:e.username,subreddit:e.subredditName,show:"all",...s},t);return ig(o,e.subredditName,t)}})}static async createRelationship(e,t){let i=u.redditAPIPlugins.Users,{type:s,subredditName:o,username:d,permissions:c,...m}=e,b=await i.Friend({type:s,subreddit:o,name:d,permissions:c?Ha(c):void 0,...m},t);if(b.json?.errors?.length)throw new Error(b.json.errors.join(`
|
|
5
|
+
`))}static async removeRelationship(e,t){await u.redditAPIPlugins.Users.Unfriend({type:e.type,subreddit:e.subredditName,name:e.username},t)}static async setModeratorPermissions(e,t,i,s){let d=await u.redditAPIPlugins.Users.SetPermissions({subreddit:t,name:e,type:"moderator",permissions:Ha(i)},s);if(d.json?.errors?.length)throw new Error(d.json.errors.join(`
|
|
6
|
+
`))}static async getSnoovatarUrl(e,t){return(await Q.query("GetSnoovatarUrlByName","c47fd42345af268616d2d8904b56856acdc05cf61d3650380f539ad7d596ac0c",{username:e},t)).data?.redditorInfoByName?.snoovatarIcon?.url}static getOverview(e,t){let i=u.redditAPIPlugins.Users;return new W({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,async fetch(s){let o=await i.UserWhere({username:e.username,where:"overview",...s},t);return tg(o,t)}})}};Fn=new WeakMap,rr=new WeakMap,xn=new WeakMap,In=new WeakMap,En=new WeakMap,An=new WeakMap,Tn=new WeakMap,bt=new WeakMap,Rn=new WeakMap,On=new WeakMap,Bn=new WeakMap,Me=new WeakMap;var C=zt;function tg(r,e){if(!r.data?.children)throw new Error("Listing response is missing children");return{children:r.data.children.map(i=>{if(i.kind==="t3")return new V(i.data,e);if(i.kind==="t1")return new X(i.data,e);throw new Error(`Type ${i.kind} is not supported`)}),before:r.data.before,after:r.data.after}}async function ig(r,e,t){let i=u.redditAPIPlugins.Users;if(!r.data?.children)throw new Error("Listing response is missing children");let s=r.data.children.map(y=>(p(y.data?.id,"User id is still from listing data"),y.data.id)),o=100,d=[];for(let y=0;y<s.length;y+=o)d.push(s.slice(y,y+o));let m=(await Promise.all(d.map(y=>i.UserDataByAccountIds({ids:y.join(",")},t)))).reduce((y,f)=>({...y,...f.users}),{});return{children:r.data.children.map(y=>{let f=y.data?.id;p(f,"User id is missing from listing");let S=m[f];return p(S,"User data is missing from response"),new C({id:f,name:S.name,linkKarma:S.linkKarma,commentKarma:S.commentKarma,createdUtc:S.createdUtc,over18:S.profileOver18,snoovatarSize:[],modPermissions:{[e]:y.data?.modPermissions??[]}},t)}),before:r.data.before,after:r.data.after}}async function bc(r,e){return(await u.redditAPIPlugins.Users.UserDataByAccountIds({ids:r},e))?.users?.[r]?.name}async function xd(r){p(r);let e=r?.[P.Username]?.values[0];if(e)return e;let t=r?.[P.User]?.values[0];if(t)return bc(t,r)}var qt,Mn,nr,sr,Un,Dn,or,Nn,Ln,ar,yt,_n,Hn,$t,vt,kt,We,Kt,Ve,jn,Wn,Vn,Gn,Jn,zn,qn,Ct,Z,Ue,bo,yo,H=class H{constructor(e,t){l(this,qt);l(this,Mn);l(this,nr);l(this,sr);l(this,Un);l(this,Dn);l(this,or);l(this,Nn);l(this,Ln);l(this,ar);l(this,yt);l(this,_n);l(this,Hn);l(this,$t);l(this,vt);l(this,kt);l(this,We);l(this,Kt);l(this,Ve);l(this,jn);l(this,Wn);l(this,Vn);l(this,Gn);l(this,Jn);l(this,zn);l(this,qn);l(this,Ct);l(this,Z);var s;K(this),p(e.id,"Comment id is null or undefined"),p(e.body,"Comment body is null or undefined"),p(e.createdUtc,"Comment is missing created date"),p(e.author,"Comment author is null or undefined"),p(e.parentId,"Comment parentId is null or undefined"),p(e.linkId,"Comment linkId is null or undefined"),p(e.permalink,"Comment permalink is null or undefined"),p(e.subreddit,"Comment is missing subreddit name"),p(e.subredditId,"Comment is missing subreddit id"),a(this,qt,Yt(`t1_${e.id}`)),a(this,Mn,e.authorFullname?te(e.authorFullname):void 0),a(this,nr,e.author),a(this,sr,e.body),a(this,Nn,$(e.subredditId)),a(this,Ln,e.subreddit),a(this,Dn,Do(e.parentId)?Yt(e.parentId):de(e.parentId)),a(this,or,de(e.linkId)),a(this,$t,e.edited??!1),a(this,vt,e.locked??!1),a(this,kt,e.removed??!1),a(this,We,e.stickied??!1),a(this,yt,e.approved??!1),a(this,_n,e.approvedAtUtc??0),a(this,Hn,e.bannedAtUtc??0),a(this,Kt,e.spam??!1),a(this,Ve,e.distinguished),a(this,jn,e.numReports??0),a(this,Wn,e.collapsedBecauseCrowdControl??!1),a(this,Vn,e.score??0),a(this,Gn,e.permalink),a(this,qn,new URL(e.permalink??"","https://www.reddit.com/").toString()),a(this,Ct,e.ignoreReports??!1),a(this,Jn,(e.modReports??[]).map(([o])=>o)),a(this,zn,(e.userReports??[]).map(([o])=>o));let i=new Date(0);i.setUTCSeconds(e.createdUtc),a(this,Un,i),a(this,ar,h(s=H,Ue,bo).call(s,{postId:n(this,or),commentId:n(this,qt)},t)),a(this,Z,t)}get id(){return n(this,qt)}get authorId(){return n(this,Mn)}get authorName(){return n(this,nr)}get subredditId(){return n(this,Nn)}get subredditName(){return n(this,Ln)}get body(){return n(this,sr)}get createdAt(){return n(this,Un)}get parentId(){return n(this,Dn)}get postId(){return n(this,or)}get replies(){return n(this,ar)}get distinguishedBy(){return n(this,Ve)}get locked(){return n(this,vt)}get stickied(){return n(this,We)}get removed(){return n(this,kt)}get approved(){return n(this,yt)}get approvedAtUtc(){return n(this,_n)}get bannedAtUtc(){return n(this,Hn)}get spam(){return n(this,Kt)}get edited(){return n(this,$t)}get numReports(){return n(this,jn)}get collapsedBecauseCrowdControl(){return n(this,Wn)}get score(){return n(this,Vn)}get permalink(){return n(this,Gn)}get userReportReasons(){return n(this,zn)}get modReportReasons(){return n(this,Jn)}get url(){return n(this,qn)}get ignoringReports(){return n(this,Ct)}toJSON(){return{id:this.id,authorName:this.authorName,subredditId:this.subredditId,subredditName:this.subredditName,body:this.body,createdAt:this.createdAt,parentId:this.parentId,postId:this.postId,replies:this.replies,approved:this.approved,locked:this.locked,removed:this.removed,stickied:this.stickied,spam:this.spam,edited:this.edited,distinguishedBy:this.distinguishedBy,numReports:this.numReports,collapsedBecauseCrowdControl:this.collapsedBecauseCrowdControl,score:this.score,permalink:this.permalink,modReportReasons:this.modReportReasons,userReportReasons:this.userReportReasons,url:this.url,ignoringReports:this.ignoringReports}}isLocked(){return n(this,vt)}isApproved(){return n(this,yt)}isRemoved(){return n(this,kt)}isSpam(){return n(this,Kt)}isStickied(){return n(this,We)}isDistinguished(){return!!n(this,Ve)}isEdited(){return n(this,$t)}isIgnoringReports(){return n(this,Ct)}async delete(){return H.delete(this.id,n(this,Z))}async edit(e){let t=await H.edit({id:this.id,...e},n(this,Z));return a(this,sr,t.body),a(this,$t,t.edited),this}async approve(){await H.approve(this.id,n(this,Z)),a(this,yt,!0),a(this,kt,!1)}async remove(e=!1){await H.remove(this.id,e,n(this,Z)),a(this,kt,!0),a(this,Kt,e),a(this,yt,!1)}async lock(){await H.lock(this.id,n(this,Z)),a(this,vt,!0)}async unlock(){await H.unlock(this.id,n(this,Z)),a(this,vt,!1)}async reply(e){return H.submit({id:this.id,...e},n(this,Z))}async getAuthor(){return C.getByUsername(n(this,nr),n(this,Z))}async distinguish(e=!1){let{distinguishedBy:t,stickied:i}=await H.distinguish(this.id,e,!1,n(this,Z));a(this,Ve,t),a(this,We,i)}async distinguishAsAdmin(e=!1){let{distinguishedBy:t,stickied:i}=await H.distinguish(this.id,e,!0,n(this,Z));a(this,Ve,t),a(this,We,i)}async undistinguish(){let{distinguishedBy:e,stickied:t}=await H.undistinguish(this.id,n(this,Z));a(this,Ve,e),a(this,We,t)}async ignoreReports(){await H.ignoreReports(this.id,n(this,Z)),a(this,Ct,!0)}async unignoreReports(){await H.unignoreReports(this.id,n(this,Z)),a(this,Ct,!1)}addRemovalNote(e){return ve.addRemovalNote({itemIds:[n(this,qt)],...e},n(this,Z))}static async getById(e,t){let i=u.redditAPIPlugins.LinksAndComments,s=Ge(e)?e:`t1_${e}`,o=await i.Info({subreddits:[],thingIds:[s]},t);if(!o.data?.children?.[0]?.data)throw new Error("not found");return new H(o.data.children[0].data,t)}static getComments(e,t){var d;let{postId:i,commentId:s,...o}=e;return h(d=H,Ue,bo).call(d,{postId:de(i),commentId:s?Yt(s):void 0,...o},t)}static async edit(e,t){let i=u.redditAPIPlugins.LinksAndComments,{id:s}=e,o;"richtext"in e&&(o=Mi(e.richtext));let d=await i.EditUserText({thingId:s,text:"text"in e?e.text:"",richtextJson:o},t);if(d.json?.errors?.length)throw new Error("Failed to edit comment");let c=d.json?.data?.things?.[0]?.data;return p(c),new H(c,t)}static async delete(e,t){await u.redditAPIPlugins.LinksAndComments.Del({id:e},t)}static async approve(e,t){await u.redditAPIPlugins.Moderation.Approve({id:e},t)}static async remove(e,t=!1,i){await u.redditAPIPlugins.Moderation.Remove({id:e,spam:t},i)}static async lock(e,t){await u.redditAPIPlugins.LinksAndComments.Lock({id:e},t)}static async unlock(e,t){await u.redditAPIPlugins.LinksAndComments.Unlock({id:e},t)}static async submit(e,t){let i=u.redditAPIPlugins.LinksAndComments,{id:s}=e,o;"richtext"in e&&(o=Mi(e.richtext));let d=await i.Comment({thingId:s,text:"text"in e?e.text:"",richtextJson:o},t);if(d.json?.errors?.length)throw new Error("failed to reply to comment");let c=d.json?.data?.things?.[0]?.data;return p(c),new H(c,t)}static async distinguish(e,t,i,s){let c=(await u.redditAPIPlugins.Moderation.Distinguish({id:e,how:i?"admin":"yes",sticky:t},s)).json?.data?.things?.[0]?.data;return p(c),{distinguishedBy:c.distinguished,stickied:!!c.stickied}}static async undistinguish(e,t){let o=(await u.redditAPIPlugins.Moderation.Distinguish({id:e,how:"no",sticky:!1},t)).json?.data?.things?.[0]?.data;return p(o),{distinguishedBy:o.distinguished,stickied:!!o.stickied}}static getCommentsByUser(e,t){let i=u.redditAPIPlugins.Users;return new W({hasMore:!0,before:e.before,after:e.after,pageSize:e.pageSize,limit:e.limit,async fetch(s){let o=await i.UserWhere({username:e.username,where:"comments",...s},t);return p(o.data,"Failed to get comments for user"),{children:o.data.children?.map(c=>new H(c.data,t))||[],before:o.data.before,after:o.data.after}}})}static async ignoreReports(e,t){await u.redditAPIPlugins.Moderation.IgnoreReports({id:e},t)}static async unignoreReports(e,t){await u.redditAPIPlugins.Moderation.UnignoreReports({id:e},t)}};qt=new WeakMap,Mn=new WeakMap,nr=new WeakMap,sr=new WeakMap,Un=new WeakMap,Dn=new WeakMap,or=new WeakMap,Nn=new WeakMap,Ln=new WeakMap,ar=new WeakMap,yt=new WeakMap,_n=new WeakMap,Hn=new WeakMap,$t=new WeakMap,vt=new WeakMap,kt=new WeakMap,We=new WeakMap,Kt=new WeakMap,Ve=new WeakMap,jn=new WeakMap,Wn=new WeakMap,Vn=new WeakMap,Gn=new WeakMap,Jn=new WeakMap,zn=new WeakMap,qn=new WeakMap,Ct=new WeakMap,Z=new WeakMap,Ue=new WeakSet,bo=function(e,t,i=0){return new W({limit:e.limit,pageSize:e.pageSize,fetch:async s=>{var S,v;let o=s.limit,d=u.redditAPIPlugins.Listings,c=u.redditAPIPlugins.LinksAndComments,m=e.commentId;if(s.more)if(s.more.children.length){let O=s.more;(!o||o>100)&&(o=100);let L=O.children.splice(0,o),B=await c.MoreChildren({linkId:e.postId,children:L,sort:e.sort},t);if(!B.json?.data?.things?.length)return{children:[]};let{children:Y}=h(S=H,Ue,yo).call(S,B.json.data.things,e.postId,e,t);return{children:Y,more:O.children.length?O:void 0}}else m=s.more.parentId,i=i+s.more.depth;let y=(await d.Comments({article:e.postId.substring(3),comment:m?.substring(3),limit:o,depth:e.depth,sort:e.sort},t)).listings?.[1]?.data?.children??[],f=y[0];return m&&f?.data?.replyList?.data&&(y=f.data.replyList.data.children),h(v=H,Ue,yo).call(v,y,m??e.postId,e,t,i)}})},yo=function(e,t,i,s,o=0){var b,y;let d=[],c,m={};for(let f of e){if(!f.data||(f.data.depth!=null&&(f.data.depth=f.data.depth+o),f.data.depth!=null&&i.depth!=null&&f.data.depth>=i.depth))continue;let S=f.data.parentId?m[f.data.parentId]:void 0;if(f.kind==="t1"){if(f.data.name===t)continue;let v=new H(f.data,s);if(m[v.id]=v,a(v,ar,h(b=H,Ue,bo).call(b,{...i,postId:v.postId,commentId:v.id},s,o)),"replyList"in f.data&&f.data.replyList?.data){let{children:O,more:L}=h(y=H,Ue,yo).call(y,f.data.replyList.data.children,v.id,i,s,o);O.length&&v.replies.children.push(...O),L&&v.replies.setMore(L)}v.replies.preventInitialFetch(),S?S.replies.children.push(v):d.push(v)}else if(f.kind==="more"&&f.data.parentId&&f.data.depth!=null){let v={parentId:Do(f.data.parentId)?Yt(f.data.parentId):de(f.data.parentId),children:f.data.children??[],depth:f.data.depth};S?S.replies.setMore(v):v.parentId===t&&(c=v)}}return{children:d,more:c}},l(H,Ue);var X=H;function Ns(r,e){let t=u.redditAPIPlugins.Moderation;return new W({hasMore:!0,after:r.after,before:r.before,limit:r.limit,pageSize:r.pageSize,fetch:async i=>{let s=await t.AboutLog({subreddit:r.subredditName,mod:r.moderatorUsernames?r.moderatorUsernames.join(","):void 0,type:r.type,...i},e);return rg(s)}})}function rg(r){if(!r.data?.children)throw new Error("AboutLogResponse is missing children");return{children:r.data.children.map(t=>{if(!t.data)throw new Error("ModAction from AboutLogResponse is missing or invalid");let{id:i,mod:s,modId36:o,createdUtc:d,subreddit:c,subredditNamePrefixed:m,action:b,srId36:y,description:f,details:S,targetAuthor:v,targetBody:O,targetFullname:L,targetPermalink:B,targetTitle:Y}=t.data;p(i,"ModAction from AboutLogResponse is missing id"),p(s,"ModAction from AboutLogResponse is missing mod"),p(o,"ModAction from AboutLogResponse is missing modId36"),p(d,"ModAction from AboutLogResponse is missing createdUtc"),p(c,"ModAction from AboutLogResponse is missing subreddit"),p(m,"ModAction from AboutLogResponse is missing subredditNamePrefixed"),p(b,"ModAction from AboutLogResponse is missing action"),p(y,"ModAction from AboutLogResponse is missing srId36");let Xt=new Date(0);return Xt.setUTCSeconds(d),{id:i,type:b,moderatorName:s,moderatorId:`t2_${o}`,createdAt:Xt,subredditName:c,subredditId:`t5_${y}`,description:f,details:S,target:L?{id:L,author:v,body:O,permalink:B,title:Y}:void 0}}),after:r.data.after,before:r.data.before}}import"@devvit/protos";var ng=(d=>(d.New="New",d.InProgress="InProgress",d.Archived="Archived",d.Appeals="Appeals",d.JoinRequests="JoinRequests",d.Filtered="Filtered",d))(ng||{}),sg={0:"New",1:"InProgress",2:"Archived",3:"Appeals",4:"JoinRequests",5:"Filtered"},og=(v=>(v.Highlighted="Highlighted",v.Unhighlighted="Unhighlighted",v.Archived="Archived",v.Unarchived="Unarchived",v.ReportedToAdmins="ReportedToAdmins",v.Muted="Muted",v.Unmuted="Unmuted",v.Banned="Banned",v.Unbanned="Unbanned",v.Approved="Approved",v.Disapproved="Disapproved",v.Filtered="Filtered",v.Unfiltered="Unfiltered",v))(og||{}),ag={0:"Highlighted",1:"Unhighlighted",2:"Archived",3:"Unarchived",4:"ReportedToAdmins",5:"Muted",6:"Unmuted",7:"Banned",8:"Unbanned",9:"Approved",10:"Disapproved",11:"Filtered",12:"Unfiltered"},N,G,re,yc,vc,Ls=class{constructor(e){l(this,G);l(this,N);this.notificationSubjectPrefix="[notification]";a(this,N,e)}async bulkReadConversations(e,t){let i=u.redditAPIPlugins.NewModmail,{conversationIds:s}=await i.BulkReadConversations({entity:e.join(","),state:t},n(this,N));return s}async getConversations(e){let i=await u.redditAPIPlugins.NewModmail.GetConversations({after:e.after,entity:e.subreddits?e.subreddits.join(","):void 0,limit:e.limit,sort:e.sort,state:e.state},n(this,N)),s={};for(let o in i.conversations)s[o]=h(this,G,re).call(this,{protoConversation:i.conversations[o],protoMessages:i.messages,protoModActions:{}});return{conversations:s,viewerId:i.viewerId,conversationIds:i.conversationIds}}async getConversation(e){let i=await u.redditAPIPlugins.NewModmail.GetConversation({...e,markRead:!!e.markRead},n(this,N));return{participantSubreddit:i.participantSubreddit,conversation:h(this,G,re).call(this,{protoConversation:i.conversation,protoMessages:i.messages,protoModActions:i.modActions}),user:i.user}}async getSubreddits(){let e=u.redditAPIPlugins.NewModmail,{subreddits:t}=await e.Subreddits({},n(this,N));return t}async createConversation(e){let i=await u.redditAPIPlugins.NewModmail.CreateConversation({body:e.body,isAuthorHidden:e.isAuthorHidden??!1,srName:e.subredditName,subject:e.subject,to:e.to?e.to:void 0},n(this,N));return{conversation:h(this,G,re).call(this,{protoConversation:i.conversation,protoMessages:i.messages,protoModActions:i.modActions}),user:i.user}}async createModDiscussionConversation(e){return za({subject:e.subject,bodyMarkdown:e.bodyMarkdown,subredditId:$(e.subredditId),isInternal:!0,participantType:"MODERATOR",conversationType:"INTERNAL"},n(this,N))}async createModInboxConversation(e){return za({subject:e.subject,bodyMarkdown:e.bodyMarkdown,subredditId:$(e.subredditId),isInternal:!1,participantType:"PARTICIPANT_USER",conversationType:"SR_USER"},n(this,N))}async createModNotification(e){let t=e.subject;return e.subject.startsWith(this.notificationSubjectPrefix)||(t=`${this.notificationSubjectPrefix} ${e.subject}`),za({subject:t,bodyMarkdown:e.bodyMarkdown,subredditId:$(e.subredditId),isInternal:!1,participantType:"PARTICIPANT_USER",conversationType:"SR_USER"},n(this,N))}async reply(e){let i=await u.redditAPIPlugins.NewModmail.CreateConversationMessage({body:e.body,conversationId:e.conversationId,isAuthorHidden:e.isAuthorHidden??!1,isInternal:e.isInternal??!1},n(this,N));return{conversation:h(this,G,re).call(this,{protoConversation:i.conversation,protoMessages:i.messages,protoModActions:{}}),user:i.user}}async highlightConversation(e){let i=await u.redditAPIPlugins.NewModmail.HighlightConversation({conversationId:e},n(this,N));return{conversation:h(this,G,re).call(this,{protoConversation:i.conversation,protoMessages:i.messages,protoModActions:i.modActions})}}async unhighlightConversation(e){let i=await u.redditAPIPlugins.NewModmail.UnhighlightConversation({conversationId:e},n(this,N));return{conversation:h(this,G,re).call(this,{protoConversation:i.conversation,protoMessages:i.messages,protoModActions:i.modActions})}}async archiveConversation(e){let i=await u.redditAPIPlugins.NewModmail.ArchiveConversation({conversationId:e},n(this,N));return{conversation:h(this,G,re).call(this,{protoConversation:i.conversation,protoMessages:i.messages,protoModActions:i.modActions})}}async unarchiveConversation(e){let i=await u.redditAPIPlugins.NewModmail.UnarchiveConversation({conversationId:e},n(this,N));return{conversation:h(this,G,re).call(this,{protoConversation:i.conversation,protoMessages:i.messages,protoModActions:i.modActions})}}async muteConversation(e){let i=await u.redditAPIPlugins.NewModmail.MuteConversation({conversationId:e.conversationId,numHours:e.numHours},n(this,N));return{conversation:h(this,G,re).call(this,{protoConversation:i.conversations,protoMessages:i.messages,protoModActions:i.modActions}),user:i.user}}async unmuteConversation(e){let i=await u.redditAPIPlugins.NewModmail.UnmuteConversation({conversationId:e},n(this,N));return{conversation:h(this,G,re).call(this,{protoConversation:i.conversations,protoMessages:i.messages,protoModActions:i.modActions}),user:i.user}}async readConversations(e){await u.redditAPIPlugins.NewModmail.Read({conversationIds:e.join(",")},n(this,N))}async unreadConversations(e){await u.redditAPIPlugins.NewModmail.Unread({conversationIds:e.join(",")},n(this,N))}async approveConversation(e){let i=await u.redditAPIPlugins.NewModmail.ApproveConversation({conversationId:e},n(this,N));return{conversation:h(this,G,re).call(this,{protoConversation:i.conversations,protoMessages:i.messages,protoModActions:i.modActions}),user:i.user}}async disapproveConversation(e){let i=await u.redditAPIPlugins.NewModmail.DisapproveConversation({conversationId:e},n(this,N));return{conversation:h(this,G,re).call(this,{protoConversation:i.conversations,protoMessages:i.messages,protoModActions:i.modActions}),user:i.user}}async tempBanConversation(e){let i=await u.redditAPIPlugins.NewModmail.TempBan({...e},n(this,N));return{conversation:h(this,G,re).call(this,{protoConversation:i.conversations,protoMessages:i.messages,protoModActions:i.modActions}),user:i.user}}async unbanConversation(e){let i=await u.redditAPIPlugins.NewModmail.Unban({conversationId:e},n(this,N));return{conversation:h(this,G,re).call(this,{protoConversation:i.conversations,protoMessages:i.messages,protoModActions:i.modActions}),user:i.user}}async getUnreadCount(){return await u.redditAPIPlugins.NewModmail.UnreadCount({},n(this,N))}async getUserConversations(e){return await u.redditAPIPlugins.NewModmail.UserConversations({conversationId:e},n(this,N))}};N=new WeakMap,G=new WeakSet,re=function({protoConversation:e,protoMessages:t,protoModActions:i}){return{...e,state:sg[e.state],messages:h(this,G,yc).call(this,e,t),modActions:h(this,G,vc).call(this,e,i)}},yc=function(e,t){let i={},s=e.objIds.filter(o=>o.key==="messages").map(({id:o})=>o);for(let o of s){let d=t[o];d&&(i[o]=d)}return i},vc=function(e,t){let i={},s=e.objIds.filter(o=>o.key==="modActions").map(({id:o})=>o);for(let o of s){let d=t[o];d&&(i[o]={...d,actionType:ag[d.actionTypeId]})}return i};async function za(r,e){let t=e[P.AppUser]?.values[0],o=await Q.query("CreateModmailConversation","5f9ae20b0c7bdffcafb80241728a72e67cd4239bc09f67284b79d4aa706ee0e5",{subject:r.subject,bodyMarkdown:r.bodyMarkdown,subredditId:r.subredditId,authorId:t,isInternal:r.isInternal,participantType:r.participantType,conversationType:r.conversationType},e);if(o.data?.createModmailConversationV2?.ok)return o.data?.createModmailConversationV2?.conversationId;throw new Error("modmail conversation creation failed; ${response.data?.createModmailConversationV2?.errors[0].message}")}var dr,lr,$n,Kn,Zn,Xn,qa=class qa{constructor(e,t){l(this,dr);l(this,lr);l(this,$n);l(this,Kn);l(this,Zn);l(this,Xn);if(K(this),p(e.id,"PrivateMessage: Invalid data, no id"),p(e.name,"PrivateMessage: Invalid data, no name"),p(e.created,"PrivateMessage: Invalid data, no created date"),a(this,dr,fe(e.name)),e.author!=null)a(this,lr,{type:"user",username:e.author,id:e.authorFullname?te(e.authorFullname):void 0});else if(e.subreddit!=null)a(this,lr,{type:"subreddit",name:e.subreddit,id:e.subredditId?$(e.subredditId):void 0});else throw new Error("PrivateMessage: Invalid data, no author or subreddit");a(this,$n,e.body??""),a(this,Kn,e.bodyHtml??"");let i=new Date(0);i.setUTCSeconds(e.createdUtc),a(this,Zn,i),a(this,Xn,t)}static async getMessages(e,t){let i=u.redditAPIPlugins.PrivateMessages;return new W({...e,fetch:async s=>{let o=await i.MessageWhere({...s,where:e.type??"inbox"},t);return{after:o.data?.after,before:o.data?.before,children:o.data?.children?.map(d=>new qa(d.data,t)).filter(Boolean)||[]}}})}static async send({to:e,subject:t,text:i},s){await u.redditAPIPlugins.PrivateMessages.Compose({to:e,subject:t,text:i,fromSr:""},s)}static async sendAsSubreddit({to:e,fromSubredditName:t,subject:i,text:s},o){await u.redditAPIPlugins.PrivateMessages.Compose({to:e,fromSr:t,subject:i,text:s},o)}static async markAllAsRead(e){await u.redditAPIPlugins.PrivateMessages.ReadAllMessages({filterTypes:""},e)}get id(){return n(this,dr)}get from(){return n(this,lr)}get body(){return n(this,$n)}get bodyHtml(){return n(this,Kn)}get created(){return n(this,Zn)}async markAsRead(){await u.redditAPIPlugins.PrivateMessages.ReadMessage({id:n(this,dr)},n(this,Xn))}};dr=new WeakMap,lr=new WeakMap,$n=new WeakMap,Kn=new WeakMap,Zn=new WeakMap,Xn=new WeakMap;var Ft=qa;var Id=(o=>(o.Reports="reports",o.Spam="spam",o.Modqueue="modqueue",o.Unmoderated="unmoderated",o.Edited="edited",o))(Id||{}),kc=class{},Cc=class{},Sc=class{},Pc=class{},ur,F,Qn,Yn,es,ts,is,rs,ns,ss,os,cr,A,Ie=class Ie{constructor(e,t){l(this,ur);l(this,F);l(this,Qn);l(this,Yn);l(this,es);l(this,ts);l(this,is);l(this,rs);l(this,ns);l(this,ss);l(this,os);l(this,cr);l(this,A);K(this),p(e.id,"Subreddit id is missing or undefined"),p(e.displayName,"Subreddit name is missing or undefined"),a(this,ur,$(`t5_${e.id}`)),a(this,F,e.displayName),p(e.createdUtc,"Subreddit is missing created date");let i=new Date(0);i.setUTCSeconds(e.createdUtc),a(this,Qn,i),a(this,Yn,dg(e.subredditType)),a(this,es,e.title),a(this,ts,e.description),p(e.lang,"Subreddit is missing language"),a(this,is,e.lang),a(this,rs,e.subscribers??0),a(this,ns,e.activeUserCount??0),a(this,ss,e.over18??!1),a(this,cr,e.url??""),a(this,os,{acceptFollowers:e.acceptFollowers??!1,allOriginalContent:e.allOriginalContent??!1,allowChatPostCreation:e.allowChatPostCreation??!1,allowDiscovery:e.allowDiscovery??!1,allowGalleries:e.allowGalleries??!1,allowImages:e.allowImages??!1,allowPolls:e.allowPolls??!1,allowPredictionContributors:e.allowPredictionContributors??!1,allowPredictions:e.allowPredictions??!1,allowPredictionsTournament:e.allowPredictionsTournament??!1,allowTalks:e.allowTalks??!1,allowVideoGifs:e.allowVideogifs??!1,allowVideos:e.allowVideos??!1,chatPostEnabled:e.isChatPostFeatureEnabled??!1,collectionsEnabled:e.collectionsEnabled??!1,crosspostable:e.isCrosspostableSubreddit??!1,emojisEnabled:e.emojisEnabled??!1,eventPostsEnabled:e.eventPostsEnabled??!1,linkFlairEnabled:e.linkFlairEnabled??!1,originalContentTagEnabled:e.originalContentTagEnabled??!1,restrictCommenting:e.restrictCommenting??!1,restrictPosting:e.restrictPosting??!1,shouldArchivePosts:e.shouldArchivePosts??!1,spoilersEnabled:e.spoilersEnabled??!1,wikiEnabled:e.wikiEnabled??!1,allowedPostType:lg(e.submissionType),allowedMediaInComments:(e.allowedMediaInComments??[]).map(ug),bannerBackgroundColor:e.bannerBackgroundColor,bannerBackgroundImage:e.bannerBackgroundImage,bannerImage:e.bannerImg,communityIcon:e.communityIcon,headerTitle:e.headerTitle,keyColor:e.keyColor,mobileBannerImage:e.mobileBannerImage,primaryColor:e.primaryColor,userFlairs:{enabled:e.userFlairEnabledInSr??!1,usersCanAssign:e.canAssignUserFlair??!1,userFlairBackgroundColor:e.userFlairBackgroundColor,userFlairTextColor:e.userFlairTextColor},postFlairs:{enabled:e.linkFlairEnabled??!1,usersCanAssign:e.canAssignLinkFlair??!1},url:new URL(n(this,cr),"https://www.reddit.com").toString()}),a(this,A,t)}get id(){return n(this,ur)}get name(){return n(this,F)}get createdAt(){return n(this,Qn)}get type(){return n(this,Yn)}get title(){return n(this,es)}get description(){return n(this,ts)}get language(){return n(this,is)}get numberOfSubscribers(){return n(this,rs)}get numberOfActiveUsers(){return n(this,ns)}get nsfw(){return n(this,ss)}get settings(){return n(this,os)}get userFlairsEnabled(){return this.settings.userFlairs.enabled}get postFlairsEnabled(){return this.settings.postFlairs.enabled}get usersCanAssignUserFlairs(){return this.settings.userFlairs.usersCanAssign}get usersCanAssignPostFlairs(){return this.settings.postFlairs.usersCanAssign}get url(){return this.settings.url}get permalink(){return n(this,cr)}toJSON(){return{id:this.id,name:this.name,createdAt:this.createdAt,type:this.type,title:this.title,description:this.description,language:this.language,nsfw:this.nsfw,numberOfSubscribers:this.numberOfSubscribers,numberOfActiveUsers:this.numberOfActiveUsers,settings:this.settings}}async submitPost(e){let t={...e,subredditName:n(this,F)};return V.submit(t,n(this,A))}getControversialPosts(e={}){if(!n(this,F))throw new Error("subreddit missing displayName - it might not have been fetched");return V.getControversialPosts({...e,subredditName:n(this,F)},n(this,A))}getTopPosts(e={}){if(!n(this,F))throw new Error("subreddit missing displayName - it might not have been fetched");return V.getTopPosts({...e,subredditName:n(this,F)},n(this,A))}getApprovedUsers(e={}){return C.getSubredditUsersByType({type:"contributors",subredditName:n(this,F),...e},n(this,A))}approveUser(e){return C.createRelationship({username:e,subredditName:n(this,F),type:"contributor"},n(this,A))}removeUser(e){return C.removeRelationship({username:e,subredditName:n(this,F),type:"contributor"},n(this,A))}getWikiContributors(e={}){return C.getSubredditUsersByType({type:"wikicontributors",subredditName:n(this,F),...e},n(this,A))}addWikiContributor(e){return C.createRelationship({username:e,subredditName:n(this,F),type:"wikicontributor"},n(this,A))}removeWikiContributor(e){return C.removeRelationship({username:e,subredditName:n(this,F),type:"wikicontributor"},n(this,A))}getBannedUsers(e={}){return C.getSubredditUsersByType({type:"banned",subredditName:n(this,F),...e},n(this,A))}banUser(e){return C.createRelationship({username:e.username,subredditName:n(this,F),type:"banned",banReason:e.reason,banMessage:e.message,note:e.note,duration:e.duration,banContext:e.context},n(this,A))}unbanUser(e){return C.removeRelationship({username:e,subredditName:n(this,F),type:"banned"},n(this,A))}getBannedWikiContributors(e={}){return C.getSubredditUsersByType({type:"wikibanned",subredditName:n(this,F),...e},n(this,A))}banWikiContributor(e){return C.createRelationship({username:e.username,subredditName:n(this,F),type:"wikibanned",banReason:e.reason,note:e.note,duration:e.duration},n(this,A))}unbanWikiContributor(e){return C.removeRelationship({username:e,subredditName:n(this,F),type:"wikibanned"},n(this,A))}getModerators(e={}){return C.getSubredditUsersByType({type:"moderators",subredditName:n(this,F),...e},n(this,A))}inviteModerator(e,t){return C.createRelationship({type:"moderator_invite",subredditName:n(this,F),username:e,permissions:t??[]},n(this,A))}revokeModeratorInvite(e){return C.removeRelationship({username:e,subredditName:n(this,F),type:"moderator_invite"},n(this,A))}removeModerator(e){return C.removeRelationship({type:"moderator",subredditName:n(this,F),username:e},n(this,A))}setModeratorPermissions(e,t){return C.setModeratorPermissions(e,n(this,F),t,n(this,A))}getMutedUsers(e={}){return C.getSubredditUsersByType({type:"muted",subredditName:n(this,F),...e},n(this,A))}muteUser(e,t){return C.createRelationship({username:e,subredditName:n(this,F),type:"muted",note:t},n(this,A))}unmuteUser(e){return C.removeRelationship({username:e,subredditName:n(this,F),type:"muted"},n(this,A))}getModerationLog(e){return Ns({subredditName:n(this,F),...e},n(this,A))}getUserFlairTemplates(){return ne.getUserFlairTemplates(n(this,F),n(this,A))}getPostFlairTemplates(){return ne.getPostFlairTemplates(n(this,F),n(this,A))}createPostFlairTemplate(e){return ne.createPostFlairTemplate({subredditName:n(this,F),...e},n(this,A))}createUserFlairTemplate(e){return ne.createUserFlairTemplate({subredditName:n(this,F),...e},n(this,A))}async getUserFlair(e){if(e?.usernames!==void 0)return{users:await Promise.all(e.usernames.map(async i=>{let s=await ce.getUserFlairBySubreddit({subreddit:n(this,F),name:i},n(this,A));return dn(s.users[0])}))};{let t=await ce.getUserFlairBySubreddit({...e,subreddit:n(this,F)},n(this,A));return{next:t.next,prev:t.prev,users:t.users.map(i=>dn(i))}}}getModQueue(e={type:"all"}){return Ie.aboutLocation({...e,location:"modqueue",subreddit:n(this,F)},n(this,A))}getReports(e={type:"all"}){return Ie.aboutLocation({...e,location:"reports",subreddit:n(this,F)},n(this,A))}getSpam(e={type:"all"}){return Ie.aboutLocation({...e,location:"spam",subreddit:n(this,F)},n(this,A))}getUnmoderated(e={type:"all"}){return Ie.aboutLocation({...e,location:"unmoderated",subreddit:n(this,F)},n(this,A))}getEdited(e={type:"all"}){return Ie.aboutLocation({...e,location:"edited",subreddit:n(this,F)},n(this,A))}static aboutLocation(e,t){let i=u.redditAPIPlugins.Moderation,s;switch(e.type){case"post":s="links";break;case"comment":s="comments";break;default:s=void 0}return new W({...e,fetch:async o=>{let d=await i.AboutLocation({...o,...e,only:s},t);return wc(d,t)}})}getCommentsAndPostsByIds(e){let t=u.redditAPIPlugins.LinksAndComments;return new W({fetch:async()=>{let i=await t.Info({thingIds:e,subreddits:[n(this,ur)]},n(this,A));return wc(i,n(this,A))}})}static async addRemovalReason(e,t,i,s){return(await u.redditAPIPlugins.Subreddits.SubredditAddRemovalReason({title:t,message:i,subreddit:e},s)).id}static async getRemovalReasons(e,t){let s=await u.redditAPIPlugins.Subreddits.SubredditGetRemovalReasons({subreddit:e},t);return s.order.map(o=>({...s.data[o]}))}static async getFromMetadata(e){p(e);let t=e?.[P.SubredditName]?.values[0];if(t)return Ie.getByName(t,e);let i=e?.[P.Subreddit]?.values[0];return p(i),Ie.getById($(i),e)}static async getById(e,t){let i=await Vo(e,t);if(i)return Ie.getByName(i,t)}static async getByName(e,t){let s=await u.redditAPIPlugins.Subreddits.SubredditAbout({subreddit:e},t);if(!s?.data)throw new Error("not found");return new Ie(s.data,t)}};ur=new WeakMap,F=new WeakMap,Qn=new WeakMap,Yn=new WeakMap,es=new WeakMap,ts=new WeakMap,is=new WeakMap,rs=new WeakMap,ns=new WeakMap,ss=new WeakMap,os=new WeakMap,cr=new WeakMap,A=new WeakMap;var le=Ie;async function Ed(r,e){let o=(await Q.query("GetSubredditInfoById","315a9b75c22a017d526afdf2d274616946156451aacfd56dfb91e7ad3f7a2fde",{id:r},e)).data?.subredditInfoById;if(!o)throw new Error("subreddit info not found");return o}async function Ad(r,e){let o=(await Q.query("GetSubredditInfoByName","4aa69726c7e3f5d33ab2bee22b3d74fce645824fddd5ea3ec6dfe30bdb4295cb",{name:r},e)).data?.subredditInfoByName;if(!o)throw new Error("subreddit info not found");return o}async function Td(r,e){let o=(await Q.query("GetSubredditLeaderboard","18ead70c46b6446d45ecd8b679b16d9a929a933d6ef25d8262a459cb18b72848",{id:r},e)).data?.subredditInfoById?.leaderboard;if(!o)throw new Error("subreddit leaderboard not found");if(!o.summary)throw new Error("subreddit leaderboard summary not found");return{id:o.id,summary:o.summary}}async function Rd(r,e){let o=(await Q.query("GetSubredditStyles","d491d17ea8858f563ea578b26b9595d64adecf4bf34557d567c7e53c470f5f22",{id:r},e)).data?.subredditInfoById?.styles;if(!o)throw new Error("subreddit styles not found");return o}function dg(r){if(r==="public"||r==="private"||r==="restricted"||r==="employees_only"||r==="gold_only"||r==="gold_restricted"||r==="archived"||r==="user")return r;throw new Error(`invalid subreddit type: ${r}`)}function lg(r){if(r==="any"||r==="link"||r==="self")return r;throw new Error(`invalid allowed post type: ${r}`)}function ug(r){if(r==="animated"||r==="giphy"||r==="static"||r==="expression")return r;throw new Error(`invalid comment media type: ${r}`)}function wc(r,e){let i=(r.data?.children??[]).map(d=>{let c=s(d);if(c!=null)return c;let m=o(d);return m??null}).filter(Boolean);return{after:r.data?.after,before:r.data?.before,children:i};function s(d){try{return new V(d.data,e)}catch{return null}}function o(d){try{return new X(d.data,e)}catch{return null}}}async function Vo(r,e){return(await u.redditAPIPlugins.LinksAndComments.Info({thingIds:[r],subreddits:[]},e)).data?.children[0]?.data?.displayName}async function Od(r,e){return Fc("GetVaultContactByAddress","3e2f7966a5c120e64fd2795d06a46595c52d988185be98d3ed71c3f81ae80d2e",{provider:"ethereum",address:r},e)}async function Bd(r,e){return Fc("GetVaultContactByUserId","a854ddc19d0e22c4f36ed917fdbd568f299f3571427e393aee5e2972080fffe9",{provider:"ethereum",userId:r},e)}async function Fc(r,e,t,i){let o=(await Q.query(r,e,t,i))?.data?.vault?.contact;return{provider:o?.provider,userId:te(o?.userId),address:o?.address,createdAt:o?.createdAt,isActive:o?.isActive}}import{CommunityListWidget_CommunityData as cg,GetWidgetsResponse_WidgetItem as ae}from"@devvit/protos";var as,ds,ls,us,Ka=class Ka{constructor(e,t,i){l(this,as);l(this,ds);l(this,ls);l(this,us);K(this),a(this,as,e.id),a(this,ds,e.shortName),a(this,ls,t),a(this,us,i)}get id(){return n(this,as)}get name(){return n(this,ds)}get subredditName(){return n(this,ls)}toJSON(){return{id:this.id,name:this.name,subredditName:this.subredditName}}delete(){return Ka.delete(this.subredditName,this.id,n(this,us))}static async getWidgets(e,t){let s=await u.redditAPIPlugins.Widgets.GetWidgets({subreddit:e},t);p(s.layout,"Failed to load widgets for subreddit");let o=s.items,d=[];for(let c of s.layout.sidebar?.order??[]){let m=o[c];switch(m?.kind){case"image":d.push(new vo(m,e,t));break;case"calendar":d.push(new ko(m,e,t));break;case"textarea":d.push(new Co(m,e,t));break;case"button":d.push(new So(m,e,t));break;case"community-list":d.push(new Po(m,e,t));break;case"post-flair":d.push(new wo(m,e,t));break;case"custom":d.push(new Fo(m,e,t));break;case"subreddit-rules":{let b=await u.redditAPIPlugins.Subreddits.SubredditAboutRules({subreddit:e},t);d.push(new $a(b,m,e,t));break}default:throw new Error(`Unknown widget type: ${m.kind}`)}}return d}static async delete(e,t,i){await u.redditAPIPlugins.Widgets.DeleteWidget({subreddit:e,id:t},i)}static async reorder(e,t,i){await u.redditAPIPlugins.Widgets.OrderWidgets({subreddit:e,order:t},i)}static async add(e,t){switch(e?.type){case"image":return vo.create(e,t);case"calendar":return ko.create(e,t);case"textarea":return Co.create(e,t);case"button":return So.create(e,t);case"community-list":return Po.create(e,t);case"post-flair":return wo.create(e,t);case"custom":return Fo.create(e,t);default:throw new Error("Unknown widget type")}}};as=new WeakMap,ds=new WeakMap,ls=new WeakMap,us=new WeakMap;var ie=Ka,cs,xo=class xo extends ie{constructor(t,i,s){super(t,i,s);l(this,cs);a(this,cs,t.data.map(o=>(p(o.url,"Image widget data is missing url"),p(o.height,"Image widget data is missing height"),p(o.width,"Image widget data is missing width"),p(o.linkUrl,"Image widget data is missing linkUrl"),{url:o.url,height:o.height,width:o.width,linkUrl:o.linkUrl})))}get images(){return n(this,cs)}toJSON(){return{...super.toJSON(),images:this.images}}static async create(t,i){let o=await u.redditAPIPlugins.Widgets.AddImageWidget(t,i);return new xo(ae.fromJSON(o),t.subreddit,i)}static async update(t,i){let o=await u.redditAPIPlugins.Widgets.UpdateImageWidget(t,i);return new xo(ae.fromJSON(o),t.subreddit,i)}};cs=new WeakMap;var vo=xo,ms,ps,gs,Io=class Io extends ie{constructor(t,i,s){super(t,i,s);l(this,ms);l(this,ps);l(this,gs);p(t.googleCalendarId,"Calendar widget data is missing googleCalendarId"),p(t.configuration,"Calendar widget data is missing configuration"),p(t.styles,"Calendar widget data is missing styles"),a(this,ms,t.googleCalendarId),a(this,ps,t.configuration),a(this,gs,t.styles)}get googleCalendarId(){return n(this,ms)}get configuration(){return n(this,ps)}get styles(){return n(this,gs)}toJSON(){return{...super.toJSON(),googleCalendarId:this.googleCalendarId,configuration:this.configuration,styles:this.styles}}static async create(t,i){let o=await u.redditAPIPlugins.Widgets.AddCalendarWidget(t,i);return new Io(ae.fromJSON(o),t.subreddit,i)}static async update(t,i){let o=await u.redditAPIPlugins.Widgets.UpdateCalendarWidget(t,i);return new Io(ae.fromJSON(o),t.subreddit,i)}};ms=new WeakMap,ps=new WeakMap,gs=new WeakMap;var ko=Io,hs,fs,Eo=class Eo extends ie{constructor(t,i,s){super(t,i,s);l(this,hs);l(this,fs);p(t.text,"Textarea widget data is missing text"),p(t.styles,"Textarea widget data is missing styles"),a(this,hs,t.text),a(this,fs,t.styles)}get text(){return n(this,hs)}get styles(){return n(this,fs)}toJSON(){return{...super.toJSON(),text:this.text,styles:this.styles}}static async create(t,i){let o=await u.redditAPIPlugins.Widgets.AddTextAreaWidget(t,i);return new Eo(ae.fromJSON(o),t.subreddit,i)}static async update(t,i){let o=await u.redditAPIPlugins.Widgets.UpdateTextAreaWidget(t,i);return new Eo(ae.fromJSON(o),t.subreddit,i)}};hs=new WeakMap,fs=new WeakMap;var Co=Eo,bs,ys,vs,Ao=class Ao extends ie{constructor(t,i,s){super(t,i,s);l(this,bs);l(this,ys);l(this,vs);p(t.styles,"Button widget data is missing styles"),a(this,bs,t.buttons),a(this,ys,t.description??""),a(this,vs,t.styles)}get buttons(){return n(this,bs)}get description(){return n(this,ys)}get styles(){return n(this,vs)}toJSON(){return{...super.toJSON(),buttons:this.buttons,description:this.description,styles:this.styles}}static async create(t,i){let o=await u.redditAPIPlugins.Widgets.AddButtonWidget(t,i);return new Ao(ae.fromJSON(o),t.subreddit,i)}static async update(t,i){let o=await u.redditAPIPlugins.Widgets.UpdateButtonWidget(t,i);return new Ao(ae.fromJSON(o),t.subreddit,i)}};bs=new WeakMap,ys=new WeakMap,vs=new WeakMap;var So=Ao,ks,Cs,To=class To extends ie{constructor(t,i,s){super(t,i,s);l(this,ks);l(this,Cs);a(this,ks,t.data.map(o=>cg.fromJSON(o))),p(t.styles,"Community list widget data is missing styles"),a(this,Cs,t.styles)}get communities(){return n(this,ks)}get styles(){return n(this,Cs)}toJSON(){return{...super.toJSON(),communities:this.communities,styles:this.styles}}static async create(t,i){let o=await u.redditAPIPlugins.Widgets.AddCommunityListWidget(t,i);return new To(ae.fromJSON(o),t.subreddit,i)}static async update(t,i){let o=await u.redditAPIPlugins.Widgets.UpdateCommunityListWidget(t,i);return new To(ae.fromJSON(o),t.subreddit,i)}};ks=new WeakMap,Cs=new WeakMap;var Po=To,Ss,Ps,ws,Ro=class Ro extends ie{constructor(t,i,s){super(t,i,s);l(this,Ss);l(this,Ps);l(this,ws);if(p(t.styles,"Post flair widget data is missing styles"),a(this,Ss,t.styles),a(this,Ps,t.order.map(o=>t.templates[o])),!(t.display&&t.display==="list"||t.display==="cloud"))throw new Error("Post flair widget data is missing display type");a(this,ws,t.display)}get styles(){return n(this,Ss)}get templates(){return n(this,Ps)}get display(){return n(this,ws)}toJSON(){return{...super.toJSON(),styles:this.styles,templates:this.templates,display:this.display}}static async create(t,i){let o=await u.redditAPIPlugins.Widgets.AddPostFlairWidget(t,i);return new Ro(ae.fromJSON(o),t.subreddit,i)}static async update(t,i){let o=await u.redditAPIPlugins.Widgets.UpdatePostFlairWidget(t,i);return new Ro(ae.fromJSON(o),t.subreddit,i)}};Ss=new WeakMap,Ps=new WeakMap,ws=new WeakMap;var wo=Ro,Fs,xs,Is,Es,As,Oo=class Oo extends ie{constructor(t,i,s){super(t,i,s);l(this,Fs);l(this,xs);l(this,Is);l(this,Es);l(this,As);p(t.stylesheetUrl,"Custom widget data is missing stylesheetUrl"),p(t.height,"Custom widget data is missing height"),p(t.css,"Custom widget data is missing css"),a(this,Fs,t.imageData??[]),a(this,xs,t.text??""),a(this,Is,t.stylesheetUrl),a(this,Es,t.height),a(this,As,t.css)}get images(){return n(this,Fs)}get text(){return n(this,xs)}get stylesheetUrl(){return n(this,Is)}get height(){return n(this,Es)}get css(){return n(this,As)}toJSON(){return{...super.toJSON(),images:this.images,text:this.text,stylesheetUrl:this.stylesheetUrl,height:this.height,css:this.css}}static async create(t,i){let o=await u.redditAPIPlugins.Widgets.AddCustomWidget(t,i);return new Oo(ae.fromJSON(o),t.subreddit,i)}static async update(t,i){let o=await u.redditAPIPlugins.Widgets.UpdateCustomWidget(t,i);return new Oo(ae.fromJSON(o),t.subreddit,i)}};Fs=new WeakMap,xs=new WeakMap,Is=new WeakMap,Es=new WeakMap,As=new WeakMap;var Fo=Oo,Ts,$a=class extends ie{constructor(t,i,s,o){super(i,s,o);l(this,Ts);let d=t.rules.map(({description:c,priority:m,shortName:b,violationReason:y})=>(p(c,"Subreddit rule is missing description"),p(m,"Subreddit rule is missing priority"),p(b,"Subreddit rule is missing shortName"),p(y,"Subreddit rule is missing violationReason"),{description:c,priority:m,shortName:b,violationReason:y}));a(this,Ts,d)}get rules(){return n(this,Ts)}toJSON(){return{...super.toJSON(),rules:this.rules}}};Ts=new WeakMap;var mg=(i=>(i[i.SUBREDDIT_PERMISSIONS=0]="SUBREDDIT_PERMISSIONS",i[i.APPROVED_CONTRIBUTORS_ONLY=1]="APPROVED_CONTRIBUTORS_ONLY",i[i.MODS_ONLY=2]="MODS_ONLY",i))(mg||{}),ge,he,mr,pr,gr,hr,fr,br,Ee,we=class we{constructor(e,t,i,s){l(this,ge);l(this,he);l(this,mr);l(this,pr);l(this,gr);l(this,hr);l(this,fr);l(this,br);l(this,Ee);K(this),a(this,ge,e),a(this,he,t),a(this,mr,i.contentMd),a(this,pr,i.contentHtml),a(this,gr,i.revisionId),a(this,hr,new Date(i.revisionDate*1e3)),a(this,fr,i.reason??""),a(this,br,i.revisionBy?.data?new C(i.revisionBy.data,s):void 0),a(this,Ee,s)}get name(){return n(this,ge)}get subredditName(){return n(this,he)}get content(){return n(this,mr)}get contentHtml(){return n(this,pr)}get revisionId(){return n(this,gr)}get revisionDate(){return n(this,hr)}get revisionReason(){return n(this,fr)}get revisionAuthor(){return n(this,br)}toJSON(){return{name:n(this,ge),subredditName:n(this,he),content:n(this,mr),contentHtml:n(this,pr),revisionId:n(this,gr),revisionDate:n(this,hr),revisionReason:n(this,fr),revisionAuthor:n(this,br)?.toJSON()}}async update(e,t){return we.updatePage({subredditName:n(this,he),page:n(this,ge),content:e,reason:t},n(this,Ee))}async getRevisions(e){return we.getPageRevisions({subredditName:n(this,he),page:n(this,ge),...e},n(this,Ee))}async revertTo(e){return we.revertPage(n(this,he),n(this,ge),e,n(this,Ee))}async getSettings(){return we.getPageSettings(n(this,he),n(this,ge),n(this,Ee))}async updateSettings(e){return we.updatePageSettings({subredditName:n(this,he),page:n(this,ge),listed:e.listed,permLevel:e.permLevel},n(this,Ee))}async addEditor(e){return we.addEditor(n(this,he),n(this,ge),e,n(this,Ee))}async removeEditor(e){return we.removeEditor(n(this,he),n(this,ge),e,n(this,Ee))}static async getPage(e,t,i){let o=await u.redditAPIPlugins.Wiki.GetWikiPage({subreddit:e,page:t},i);return p(o.data,"Failed to get wiki page"),new we(t,e,o.data,i)}static async getPages(e,t){return(await u.redditAPIPlugins.Wiki.GetWikiPages({subreddit:e},t)).data||[]}static async createPage(e,t){return we.updatePage(e,t)}static async updatePage(e,t){return await u.redditAPIPlugins.Wiki.EditWikiPage({subreddit:e.subredditName,page:e.page,content:e.content,reason:e.reason??""},t),we.getPage(e.subredditName,e.page,t)}static getPageRevisions(e,t){let i=u.redditAPIPlugins.Wiki;return new W({hasMore:!0,after:e.after,limit:e.limit,pageSize:e.pageSize,async fetch(s){let o=await i.GetWikiPageRevisions({subreddit:e.subredditName,page:e.page,limit:s.limit,after:s.after,before:s.before},t);return pg(o,t)}})}static async revertPage(e,t,i,s){await u.redditAPIPlugins.Wiki.RevertWikiPage({subreddit:e,page:t,revision:i},s)}static async getPageSettings(e,t,i){let o=await u.redditAPIPlugins.Wiki.GetWikiPageSettings({subreddit:e,page:t},i);return p(o.data,"Failed to get wiki page settings"),new Bo(o.data,i)}static async updatePageSettings(e,t){let s=await u.redditAPIPlugins.Wiki.UpdateWikiPageSettings({subreddit:e.subredditName,page:e.page,listed:e.listed?"on":"",permlevel:e.permLevel},t);return p(s.data,"Failed to update wiki page settings"),new Bo(s.data,t)}static async addEditor(e,t,i,s){await u.redditAPIPlugins.Wiki.AllowEditor({act:"add",subreddit:e,page:t,username:i},s)}static async removeEditor(e,t,i,s){await u.redditAPIPlugins.Wiki.AllowEditor({act:"del",subreddit:e,page:t,username:i},s)}};ge=new WeakMap,he=new WeakMap,mr=new WeakMap,pr=new WeakMap,gr=new WeakMap,hr=new WeakMap,fr=new WeakMap,br=new WeakMap,Ee=new WeakMap;var ue=we,yr,vr,kr,Cr,Sr,Pr,Za=class{constructor(e,t){l(this,yr);l(this,vr);l(this,kr);l(this,Cr);l(this,Sr);l(this,Pr);a(this,yr,e.id),a(this,vr,e.page),a(this,kr,new Date(e.timestamp)),p(e.author?.data,"Wiki page revision author details are missing"),a(this,Cr,new C(e.author.data,t)),a(this,Sr,e.reason??""),a(this,Pr,e.revisionHidden??!1)}get id(){return n(this,yr)}get page(){return n(this,vr)}get date(){return n(this,kr)}get author(){return n(this,Cr)}get reason(){return n(this,Sr)}get hidden(){return n(this,Pr)}toJSON(){return{id:n(this,yr),page:n(this,vr),date:n(this,kr),author:n(this,Cr).toJSON(),reason:n(this,Sr),hidden:n(this,Pr)}}};yr=new WeakMap,vr=new WeakMap,kr=new WeakMap,Cr=new WeakMap,Sr=new WeakMap,Pr=new WeakMap;var wr,Fr,xr,Bo=class{constructor(e,t){l(this,wr);l(this,Fr);l(this,xr);a(this,wr,e.listed),a(this,Fr,e.permLevel),a(this,xr,e.editors.map(i=>(p(i.data,"Wiki page editor details are missing"),new C(i.data,t))))}get listed(){return n(this,wr)}get permLevel(){return n(this,Fr)}get editors(){return n(this,xr)}toJSON(){return{listed:n(this,wr),permLevel:n(this,Fr),editors:n(this,xr).map(e=>e.toJSON())}}};wr=new WeakMap,Fr=new WeakMap,xr=new WeakMap;function pg(r,e){return p(r.data?.children,"Wiki page revision listing is missing children"),{children:r.data.children.map(i=>new Za(i,e)),before:r.data.before,after:r.data.after}}var gg=["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"],hg=["border-image","border-image-source","behavior","expression","list-style-image","cursor","content"],fg=["onload","onerror","onclick","onmouseover"];function bg(r){return/xmlns=["']http:\/\/www\.w3\.org\/2000\/svg["']/.test(r)?r:r.replace(/<svg\b/,'<svg xmlns="http://www.w3.org/2000/svg"')}function xc(r){if(r){if(!r.trim().startsWith("<svg")){console.log("The provided string is not a valid SVG.");return}try{let e=new RegExp(`<\\s*(${gg.join("|")})\\b`,"gi"),t=new RegExp(`(${hg.join("|")})\\s*:\\s*url\\s*\\((['"]?)(.*?)\\2\\)`,"gi"),i=new RegExp(`(${fg.join("|")})\\s*(=\\s*(['"]?)(.*?)\\3)?`,"gi");r=r.trim().replace(/\s+/g," "),r=bg(r);let s=r.match(e)||[],o=r.match(t)||[],d=r.match(i)||[],c=!1;return s.length>0&&(c=!0,console.warn(`Disallowed elements detected in SVG: ${s.map(m=>m.replace("<","")).join(", ")}`)),o.length>0&&(c=!0,console.warn(`Disallowed styles detected in SVG: ${o.map(m=>m.split(":")[0]).join(", ")}`)),d.length>0&&(c=!0,console.warn(`Disallowed attributes detected in SVG: ${d.map(m=>m.split("=")[0]).join(", ")}`)),c?void 0:r}catch{return}}}function DS(r,...e){let t="";return r.forEach((i,s)=>{t+=i;let o=e[s];o!==void 0&&(t+=`${o}`)}),t=xc(t),t===void 0?"":`data:image/svg+xml;charset=UTF-8,${encodeURIComponent(t)}`}import{EffectType as Ic}from"@devvit/protos";import{WebViewVisibility as yg}from"@devvit/protos";var Ir,Rs,Os,Er,Zt,Xa=class{constructor(e,t){this.state={messageCount:0};l(this,Ir);l(this,Rs);l(this,Os);l(this,Er);l(this,Zt);this.postMessage=e=>{n(this,Zt).emitEffect(`postMessage${this.state.messageCount++}`,{type:Ic.EFFECT_WEB_VIEW,webView:{postMessage:{webViewId:n(this,Ir),app:{message:e}}}})};this.mount=()=>{let t=(n(this,Zt)?.devvitContext?.assets).getURL(n(this,Rs),{webView:!0});if(!t)throw Error("useWebView fullscreen request failed; web view asset could not be found");n(this,Zt).emitEffect("fullscreen",{type:Ic.EFFECT_WEB_VIEW,webView:{fullscreen:{id:n(this,Ir),show:!0,url:t}}})};a(this,Rs,t.url??"index.html"),a(this,Ir,e.hookId),a(this,Os,t.onMessage),a(this,Er,t.onUnmount),a(this,Zt,e.context)}async onUIEvent(e){if(e.webView?.fullScreen)!(e.webView.fullScreen.visibility===yg.WEBVIEW_VISIBLE)&&n(this,Er)&&await n(this,Er).call(this,this);else if(e.webView?.postMessage){let{message:t}=e.webView.postMessage;await n(this,Os).call(this,t,this)}}};Ir=new WeakMap,Rs=new WeakMap,Os=new WeakMap,Er=new WeakMap,Zt=new WeakMap;function vg(r){let e=me({namespace:"useWebView",initializer:t=>new Xa(t,r)});return{postMessage:e.postMessage,mount:e.mount}}export{Tg as ALL_ICON_NAMES,Id as AboutLocations,Sc as AuthorFlairSettings,So as ButtonWidget,ko as CalendarWidget,X as Comment,Po as CommunityListWidget,Fo as CustomWidget,u as Devvit,ce as Flair,ne as FlairTemplate,_p as FlairType,Je as Hook,vo as ImageWidget,W as Listing,og as ModMailActionType,ng as ModMailConversationState,Ls as ModMailService,ve as ModNote,V as Post,Pc as PostFlairSettings,wo as PostFlairWidget,Ft as PrivateMessage,_t as RichTextBuilder,No as SettingScope,eg as SocialLinkType,le as Subreddit,kc as SubredditDescription,$a as SubredditRulesWidget,Cc as SubredditWikiSettings,Co as TextAreaWidget,C as User,ie as Widget,ue as WikiPage,mg as WikiPagePermissionLevel,Za as WikiPageRevision,Bo as WikiPageSettings,dn as convertUserFlairProtoToAPI,xd as getCurrentUsernameFromMetadata,Ns as getModerationLog,Ed as getSubredditInfoById,Ad as getSubredditInfoByName,Td as getSubredditLeaderboard,Vo as getSubredditNameById,Rd as getSubredditStyles,Od as getVaultByAddress,Bd as getVaultByUserId,DS as svg,Fp as useAsync,Pa as useChannel,ka as useForm,xa as useInterval,Ta as useState,vg as useWebView};
|
|
6
7
|
/*! Bundled license information:
|
|
7
8
|
|
|
8
9
|
shallow-clone/index.js:
|