@devvit/public-api 0.11.15-next-2025-05-07-302a29e16.0 → 0.11.15-next-2025-05-07-2e2ff6ed9.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/devvit/Devvit.d.ts.map +1 -1
- package/devvit/Devvit.js +18 -2
- package/meta.json +4 -4
- package/meta.min.json +5 -5
- package/package.json +7 -7
- package/public-api.d.ts +21 -1
- package/public-api.iife.js +18 -3
- package/public-api.min.js +6 -6
- package/public-api.min.js.map +3 -3
- package/types/configuration.d.ts +3 -1
- package/types/configuration.d.ts.map +1 -1
package/public-api.min.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var Bc=Object.create;var sd=Object.defineProperty;var Dc=Object.getOwnPropertyDescriptor;var Nc=Object.getOwnPropertyNames;var Lc=Object.getPrototypeOf,_c=Object.prototype.hasOwnProperty;var od=i=>{throw TypeError(i)};var ni=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var Hc=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Nc(e))!_c.call(i,s)&&s!==t&&sd(i,s,{get:()=>e[s],enumerable:!(r=Dc(e,s))||r.enumerable});return i};var ad=(i,e,t)=>(t=i!=null?Bc(Lc(i)):{},Hc(e||!i||!i.__esModule?sd(t,"default",{value:i,enumerable:!0}):t,i));var Ho=(i,e,t)=>e.has(i)||od("Cannot "+t);var n=(i,e,t)=>(Ho(i,e,"read from private field"),t?t.call(i):e.get(i)),l=(i,e,t)=>e.has(i)?od("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),a=(i,e,t,r)=>(Ho(i,e,"write to private field"),r?r.call(i,t):e.set(i,t),t),h=(i,e,t)=>(Ho(i,e,"access private method"),t);var dd=(i,e,t,r)=>({set _(s){a(i,e,s,t)},get _(){return n(i,e,r)}});var fa=ni((pb,Cl)=>{var ip=Object.prototype.toString;Cl.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 ap(e)?"generatorfunction":"function";if(rp(e))return"array";if(up(e))return"buffer";if(lp(e))return"arguments";if(sp(e))return"date";if(np(e))return"error";if(op(e))return"regexp";switch(kl(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(dp(e))return"generator";switch(t=ip.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 kl(i){return typeof i.constructor=="function"?i.constructor.name:null}function rp(i){return Array.isArray?Array.isArray(i):i instanceof Array}function np(i){return i instanceof Error||typeof i.message=="string"&&i.constructor&&typeof i.constructor.stackTraceLimit=="number"}function sp(i){return i instanceof Date?!0:typeof i.toDateString=="function"&&typeof i.getDate=="function"&&typeof i.setDate=="function"}function op(i){return i instanceof RegExp?!0:typeof i.flags=="string"&&typeof i.ignoreCase=="boolean"&&typeof i.multiline=="boolean"&&typeof i.global=="boolean"}function ap(i,e){return kl(i)==="GeneratorFunction"}function dp(i){return typeof i.throw=="function"&&typeof i.return=="function"&&typeof i.next=="function"}function lp(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 up(i){return i.constructor&&typeof i.constructor.isBuffer=="function"?i.constructor.isBuffer(i):!1}});var wl=ni((gb,Sl)=>{"use strict";var Pl=Symbol.prototype.valueOf,cp=fa();function mp(i,e){switch(cp(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 fp(i);case"symbol":return yp(i);case"arraybuffer":return gp(i);case"float32array":case"float64array":case"int16array":case"int32array":case"int8array":case"uint16array":case"uint32array":case"uint8clampedarray":case"uint8array":return hp(i);case"regexp":return pp(i);case"error":return Object.create(i);default:return i}}function pp(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 gp(i){let e=new i.constructor(i.byteLength);return new Uint8Array(e).set(new Uint8Array(i)),e}function hp(i,e){return new i.constructor(i.buffer,i.byteOffset,i.length)}function fp(i){let e=i.length,t=Buffer.allocUnsafe?Buffer.allocUnsafe(e):Buffer.from(e);return i.copy(t),t}function yp(i){return Pl?Object(Pl.call(i)):{}}Sl.exports=mp});var xl=ni((hb,Fl)=>{"use strict";Fl.exports=function(e){return e!=null&&typeof e=="object"&&Array.isArray(e)===!1}});var El=ni((fb,Il)=>{"use strict";var bp=xl();function Al(i){return bp(i)===!0&&Object.prototype.toString.call(i)==="[object Object]"}Il.exports=function(e){var t,r;return!(Al(e)===!1||(t=e.constructor,typeof t!="function")||(r=t.prototype,Al(r)===!1)||r.hasOwnProperty("isPrototypeOf")===!1)}});var Rl=ni((yb,Tl)=>{"use strict";var vp=wl(),kp=fa(),Cp=El();function ya(i,e){switch(kp(i)){case"object":return Pp(i,e);case"array":return Sp(i,e);default:return vp(i)}}function Pp(i,e){if(typeof e=="function")return e(i);if(e||Cp(i)){let t=new i.constructor;for(let r in i)t[r]=ya(i[r],e);return t}return i}function Sp(i,e){let t=new i.constructor(i.length);for(let r=0;r<i.length;r++)t[r]=ya(i[r],e);return t}Tl.exports=ya});var Cc=ni(Po=>{"use strict";Po.byteLength=Qp;Po.toByteArray=eg;Po.fromByteArray=rg;var Be=[],Fe=[],Xp=typeof Uint8Array<"u"?Uint8Array:Array,$a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for($t=0,vc=$a.length;$t<vc;++$t)Be[$t]=$a[$t],Fe[$a.charCodeAt($t)]=$t;var $t,vc;Fe[45]=62;Fe[95]=63;function kc(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 Qp(i){var e=kc(i),t=e[0],r=e[1];return(t+r)*3/4-r}function Yp(i,e,t){return(e+t)*3/4-t}function eg(i){var e,t=kc(i),r=t[0],s=t[1],o=new Xp(Yp(i,r,s)),d=0,c=s>0?r-4:r,m;for(m=0;m<c;m+=4)e=Fe[i.charCodeAt(m)]<<18|Fe[i.charCodeAt(m+1)]<<12|Fe[i.charCodeAt(m+2)]<<6|Fe[i.charCodeAt(m+3)],o[d++]=e>>16&255,o[d++]=e>>8&255,o[d++]=e&255;return s===2&&(e=Fe[i.charCodeAt(m)]<<2|Fe[i.charCodeAt(m+1)]>>4,o[d++]=e&255),s===1&&(e=Fe[i.charCodeAt(m)]<<10|Fe[i.charCodeAt(m+1)]<<4|Fe[i.charCodeAt(m+2)]>>2,o[d++]=e>>8&255,o[d++]=e&255),o}function tg(i){return Be[i>>18&63]+Be[i>>12&63]+Be[i>>6&63]+Be[i&63]}function ig(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(tg(r));return s.join("")}function rg(i){for(var e,t=i.length,r=t%3,s=[],o=16383,d=0,c=t-r;d<c;d+=o)s.push(ig(i,d,d+o>c?c:d+o));return r===1?(e=i[t-1],s.push(Be[e>>2]+Be[e<<4&63]+"==")):r===2&&(e=(i[t-2]<<8)+i[t-1],s.push(Be[e>>10]+Be[e>>4&63]+Be[e<<2&63]+"=")),s.join("")}});var fe={APP:0,USER:1,UNSPECIFIED:2};function p(i,e){if(i==null)throw Error(e??"Expected nonnullish value.")}function It(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 Je(i){return i.startsWith(ee.COMMENT)}function Ls(i){return i.startsWith(ee.ACCOUNT)}function Et(i){return i.startsWith(ee.LINK)}function ld(i){return i.startsWith(ee.MESSAGE)}function ud(i){return i.startsWith(ee.SUBREDDIT)}function cd(i){return i.startsWith(ee.AWARD)}function jc(i){It(Je(i),`Expected comment id to start with ${ee.COMMENT}, got ${i}}`)}function Vc(i){It(Ls(i),`Expected account id to start with ${ee.ACCOUNT}, got ${i}}`)}function Wc(i){It(Et(i),`Expected link id to start with ${ee.LINK}, got ${i}}`)}function Gc(i){It(ld(i),`Expected message id to start with ${ee.MESSAGE}, got ${i}}`)}function Jc(i){It(ud(i),`Expected subreddit id to start with ${ee.SUBREDDIT}, got ${i}}`)}function zc(i){It(cd(i),`Expected award id to start with ${ee.AWARD}, got ${i}}`)}function si(i){return jc(i),i}function te(i){return Vc(i),i}function de(i){return Wc(i),i}function qc(i){return Gc(i),i}function K(i){return Jc(i),i}function $c(i){return zc(i),i}function ye(i){if(Je(i))return si(i);if(Ls(i))return te(i);if(Et(i))return de(i);if(ld(i))return qc(i);if(ud(i))return K(i);if(cd(i))return $c(i);throw new Error(`Expected thing id to start with ${Object.values(ee).join(", ")} got ${i}}`)}function jo(i){return Je(i)}import*as k from"@devvit/protos";var _s=class{constructor(e){}};var Vo=(t=>(t.Installation="installation",t.App="app",t))(Vo||{});function Tt(i,e=new Set){for(let t of i){if(t.type==="group"){Tt(t.fields,e);continue}let r=t.name;if(e.has(r))throw new Error(`Duplicate field name: ${r}`);e.add(r)}Kc(i)}function Kc(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 ze=Object.freeze({INTERVAL:0,FORM:1,STATE:2,CHANNEL:3,WEB_VIEW:4});var _g=["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{DeletionReason as Wg,EventSource as Gg}from"@devvit/protos";import{AppSettingsDefinition as mm,GetFieldsResponse as pm}from"@devvit/protos";import{FormFieldType as be}from"@devvit/protos";function Le(i){return i.map(e=>{switch(e.type){case"string":return Zc(e);case"image":return Xc(e);case"paragraph":return Qc(e);case"number":return Yc(e);case"select":return em(e);case"boolean":return tm(e);case"group":return im(e);default:throw new Error("Unknown field type.")}})}function Zc(i){return{defaultValue:{fieldType:be.STRING,stringValue:i.defaultValue},disabled:i.disabled,fieldConfig:{stringConfig:{placeholder:i.placeholder}},fieldId:i.name,fieldType:be.STRING,helpText:i.helpText,label:i.label,required:i.required,isSecret:i.isSecret}}function Xc(i){return{disabled:i.disabled,fieldId:i.name,fieldType:be.IMAGE,helpText:i.helpText,label:i.label,required:i.required}}function Qc(i){return{defaultValue:{fieldType:be.PARAGRAPH,stringValue:i.defaultValue},disabled:i.disabled,fieldConfig:{paragraphConfig:{lineHeight:i.lineHeight,placeholder:i.placeholder}},fieldId:i.name,fieldType:be.PARAGRAPH,helpText:i.helpText,label:i.label,required:i.required}}function Yc(i){return{defaultValue:{fieldType:be.NUMBER,numberValue:i.defaultValue},disabled:i.disabled,fieldConfig:{numberConfig:{}},fieldId:i.name,fieldType:be.NUMBER,helpText:i.helpText,label:i.label,required:i.required}}function em(i){return{defaultValue:{fieldType:be.SELECTION,selectionValue:{values:i.defaultValue??[]}},disabled:i.disabled,fieldConfig:{selectionConfig:{choices:i.options,multiSelect:i.multiSelect}},fieldId:i.name,fieldType:be.SELECTION,helpText:i.helpText,label:i.label,required:i.required}}function tm(i){return{defaultValue:{fieldType:be.BOOLEAN,boolValue:i.defaultValue},disabled:i.disabled,fieldId:i.name,fieldType:be.BOOLEAN,helpText:i.helpText,label:i.label}}function im(i){return{fieldId:"",fieldType:be.GROUP,fieldConfig:{groupConfig:{fields:Le(i.fields)}},label:i.label,helpText:i.helpText}}function O(i,e){u.prototype[i]=e}import{ValidateFormResponse as cm}from"@devvit/protos";import{RealtimeSubscriptionStatus as pd}from"@devvit/protos";var S=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",UserSnoovatarUrl:"devvit-user-snoovatar-url",UserAgent:"devvit-user-agent",Version:"devvit-version",Language:"devvit-accept-language",Timezone:"devvit-accept-timezone",Traceparent:"traceparent",AppDependencies:"devvit-app-dependencies"});var md;(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"})(md||(md={}));function gd(i){function e(t){let s=i.currentHookIndex,o=i.getCurrentComponentState(),d=i.getPreviousComponentState(),c=i.metadata[S.App]?.values[0];p(c,"useChannel - app is missing from Context");let m=i.metadata[S.Installation]?.values[0];p(m,"useChannel - installation is missing from Context");async function y(V){let U=o[s].channel;if(o[s].active)if(o[s].connected)await i.realtime.send(U,V);else throw Error(`Failed to send to channel '${U}'; it is active but not yet connected`);else throw Error(`Cannot send a message over inactive channel: ${U}`)}function v(){if(!o[s].active){let V=o[s].channel;o[s].active=!0,i.addRealtimeChannel(V)}}function f(){if(o[s].active){let V=o[s].channel;o[s].active=!1,i.removeRealtimeChannel(V)}}function P(V){return async()=>{let U;switch(V.status){case pd.REALTIME_SUBSCRIBED:o[s].connected=!0,U=t.onSubscribed?.();break;case pd.REALTIME_UNSUBSCRIBED:o[s].connected=!1,U=t.onUnsubscribed?.();break;default:U=t.onMessage(V.event?.data?.msg);break}await U}}let b={channel:`${c}:${m}:${t.name}`,active:!1,connected:!1,preventCallback:!1,type:ze.CHANNEL};s in o?b=o[s]:s in d&&(b=d[s]);let L=i.realtimeEvent;i.isInitialRender?b.active=!1:L&&b.active&&L.event.channel===b.channel&&(b.preventCallback||i.runHook(P(L)),i.rerenderIn(0)),o[s]=b,i.currentHookIndex++;let A=0;return b.active&&b.connected?A=2:b.active&&!b.connected?A=1:!b.active&&b.connected?A=3:!b.active&&!b.connected&&(A=4),{subscribe:v,unsubscribe:f,send:y,status:A}}return e}import{FormFieldType as oi}from"@devvit/protos";function Wo(i){switch(i.fieldType){case oi.STRING:return i.stringValue;case oi.IMAGE:return i.stringValue;case oi.PARAGRAPH:return i.stringValue;case oi.NUMBER:return i.numberValue;case oi.BOOLEAN:return i.boolValue;case oi.SELECTION:return i.selectionValue?.values??[];default:return}}function qe(i){return Object.keys(i).reduce((e,t)=>{let r=Wo(i[t]);return r!==void 0&&(e[t]=r),e},{})}function hd(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:ze.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(qe(v.results));f&&f instanceof Promise&&await f,i.rerenderIn(0)}),d[s].preventSubmit=!1,i.currentHookIndex++,m}return e}function fd(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:ze.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[P,b]of Object.entries(o))if(P!==s.toString()&&b?.type===ze.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:ze.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 P=t();P&&P instanceof Promise&&await P,y.lastRun=Date.now()}),i.rerenderIn(m)),y.preventCallback=!1,o[s]=y,i.currentHookIndex++,{start:v,stop:f}}return e}function yd(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 qo={now(){return new Date}};function bd(i){return`__autocache__${i}`}function vd(i){return`__lock__${i}`}var nm=300,sm=1e3,Hs=5e3,Go=3,kd=.1,Cd=1e3,om=3e4;function Pd(i){if(i.error)throw new Error(i.error);return i.value}var $e,Ke,ve,ai,z,Sd,wd,Fd,Jo,xd,Ad,zo,Id,js=class{constructor(e,t,r=qo){l(this,z);l(this,$e);l(this,Ke,{});l(this,ve);l(this,ai);a(this,$e,e),a(this,ai,t),a(this,ve,r)}async cache(e,t){a(this,Ke,n(this,ai).__cache=n(this,ai).__cache??{}),h(this,z,Id).call(this,t);let r=h(this,z,Sd).call(this,t.key);if(r!==void 0)return r;let s=await h(this,z,zo).call(this,t.key),o=await h(this,z,wd).call(this,t,s,e);return Pd(o)}};$e=new WeakMap,Ke=new WeakMap,ve=new WeakMap,ai=new WeakMap,z=new WeakSet,Sd=function(e){let t=n(this,Ke)[e];if(t){let r=n(this,ve).now().getTime(),s=t?.error&&t?.errorTime&&t.errorCount<Go&&Math.random()<kd&&t.errorTime+Cd<r;if(t?.expires&&t.expires<r&&t.checkedAt+Cd<r||s){delete n(this,Ke)[e];return}else return Pd(t)}},wd=async function(e,t,r){let s=t?.expires,o=s?h(this,z,Ad).call(this,s):1;return!t||t?.error&&t.errorCount<Go&&kd>Math.random()||o>Math.random()?h(this,z,Fd).call(this,e,t,r):t},Fd=async function(e,t,r){let s=vd(e.key),o=n(this,ve).now().getTime(),d=new Date(o+e.ttl/2);if(await n(this,$e).set(s,"1",{expiration:d,nx:!0}))return h(this,z,xd).call(this,e.key,t,r,e.ttl);if(t)return t;{let m=n(this,ve).now();return h(this,z,Jo).call(this,m,e.key,e.ttl)}},Jo=async function(e,t,r){let s=Math.min(r,sm),o=await h(this,z,zo).call(this,t);if(o)return o;if(n(this,ve).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,nm)),h(this,z,Jo).call(this,e,t,r)},xd=async function(e,t,r,s){let o=n(this,ve).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,ve).now().getTime(),t.errorCount++}return n(this,Ke)[e]=t,await n(this,$e).set(bd(e),JSON.stringify(t),{expiration:new Date(o+om)}),t.error&&t.errorCount<Go&&await n(this,$e).del(vd(e)),t},Ad=function(e){let t=n(this,ve).now().getTime(),r=e-t;return r<0?1:r<1e3?.1:r<2e3?.01:r<3e3?.001:0},zo=async function(e){let t=await n(this,$e).get(bd(e));if(t){let r=JSON.parse(t);return r.checkedAt=n(this,ve).now().getTime(),n(this,Ke)[e]=r,r}},Id=function(e){e.ttl<Hs&&(console.warn(`Cache TTL cannot be less than ${Hs} milliseconds! Updating ttl value of ${e.ttl} to ${Hs}.`),e.ttl=Hs)};function Ed(i,e,t=qo){let r=new js(i,e,t);return r.cache.bind(r)}function Td(i){new URL(i.slice(0,i.indexOf(",")))}var di,li,ci,Rd,Od,ui=class{constructor(){l(this,ci);l(this,di,{});l(this,li,{});a(this,di,u.assets),a(this,li,u.webViewAssets)}getURL(e,t){return typeof e=="string"?h(this,ci,Rd).call(this,e,t??{webView:!1}):h(this,ci,Od).call(this,e,t??{webView:!1})}};di=new WeakMap,li=new WeakMap,ci=new WeakSet,Rd=function(e,t){let r=t.webView?n(this,li)[e]:n(this,di)[e];if(r)return r;try{return Td(e),e}catch{return""}},Od=function(e,t){let r={},s=[],o=t.webView?n(this,li):n(this,di);if(o)for(let d of e)if(o[d])r[d]=o[d];else try{Td(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 Ze,mi=class{constructor(e){l(this,Ze);a(this,Ze,e)}async get(e){let{messages:t}=await u.kvStorePlugin.Get({keys:[e]},n(this,Ze));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,Ze))}async delete(e){await u.kvStorePlugin.Del({keys:[e]},n(this,Ze))}async list(){let{keys:e}=await u.kvStorePlugin.List({filter:"*"},n(this,Ze));return e}};Ze=new WeakMap;var Rr,pi=class{constructor(e){l(this,Rr);a(this,Rr,e)}async upload(e){let t=await u.mediaPlugin.Upload(e,n(this,Rr));if(!t.mediaId)throw new Error("unable to get mediaId via uploads");return Promise.resolve({mediaId:t.mediaId,mediaUrl:t.mediaUrl})}};Rr=new WeakMap;var Or,gi=class{constructor(e){l(this,Or);a(this,Or,e)}async add(e){await u.modLogPlugin.Add(e,n(this,Or))}};Or=new WeakMap;var Mr,hi=class{constructor(e){l(this,Mr);a(this,Mr,e)}async send(e,t){await u.realtimePlugin.Send({channel:e,data:{msg:t}},n(this,Mr))}};Mr=new WeakMap;import"@devvit/protos";var g,Ur,Br,Dr,fi=class{constructor(e){l(this,g);l(this,Ur);l(this,Br);l(this,Dr);a(this,g,e),a(this,Ur,new Ws(e))}get modMail(){return n(this,Ur)}getSubredditById(e){return le.getById(ye(e),n(this,g))}getSubredditInfoById(e){return Bd(e,n(this,g))}getSubredditByName(e){return le.getByName(e,n(this,g))}getSubredditInfoByName(e){return Dd(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)?.[S.SubredditName]?.values[0];if(e)return e;let t=n(this,g)?.[S.Subreddit]?.values[0],r=await $o(K(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 G.getById(ye(e),n(this,g))}submitPost(e){return G.submit(e,n(this,g))}crosspost(e){return G.crosspost(e,n(this,g))}getUserById(e){return C.getById(ye(e),n(this,g))}getUserByUsername(e){return C.getByUsername(e,n(this,g))}async getCurrentUsername(){return n(this,Dr)??a(this,Dr,Md(n(this,g))),n(this,Dr)}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(S.AppUser,n(this,g))}async getSnoovatarUrl(e){let t=await this.getCurrentUsername();if(t&&e===t){let r=n(this,g)?.[S.UserSnoovatarUrl]?.values[0];if(r)return r}return C.getSnoovatarUrl(e,n(this,g))}getCommentById(e){return Q.getById(ye(e),n(this,g))}getComments(e){return Q.getComments(e,n(this,g))}getCommentsByUser(e){return Q.getCommentsByUser(e,n(this,g))}submitComment(e){return Q.submit({...e,id:ye(e.id)},n(this,g))}getControversialPosts(e){return G.getControversialPosts(e,n(this,g))}getTopPosts(e){return G.getTopPosts(e,n(this,g))}getHotPosts(e){return G.getHotPosts(e,n(this,g))}getNewPosts(e){return G.getNewPosts(e,n(this,g))}getRisingPosts(e){return G.getRisingPosts(e,n(this,g))}getPostsByUser(e){return G.getPostsByUser(e,n(this,g))}getCommentsAndPostsByUser(e){return C.getOverview(e,n(this,g))}getModerationLog(e){return Vs(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 ke.get(e,n(this,g))}deleteModNote(e){return ke.delete(e,n(this,g))}addModNote(e){let t={...e,redditId:e.redditId?ye(e.redditId):void 0};return ke.add(t,n(this,g))}addRemovalNote(e){return ke.addRemovalNote(e,n(this,g))}async sendPrivateMessage(e){return Rt.send(e,n(this,g))}async sendPrivateMessageAsSubreddit(e){return Rt.sendAsSubreddit(e,n(this,g))}async approve(e){if(Je(e))return Q.approve(e,n(this,g));if(Et(e))return G.approve(e,n(this,g));throw new Error("id must start with either t1_ or t3_")}async remove(e,t){if(Je(e))return Q.remove(e,t,n(this,g));if(Et(e))return G.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,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 Rt.getMessages(e,n(this,g))}markAllMessagesAsRead(){return Rt.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 _d(e,n(this,g))}getVaultByUserId(e){return Hd(ye(e),n(this,g))}getSubredditLeaderboard(e){return Nd(e,n(this,g))}getSubredditStyles(e){return Ld(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,Ur=new WeakMap,Br=new WeakMap,Dr=new WeakMap;import{BitfieldOverflowBehavior as Ko,RedisKeyScope as Zo}from"@devvit/protos";function Nr(i){return i&&typeof i=="object"&&"message"in i&&i.message!==void 0&&typeof i.message=="string"?i.message.includes("redis: nil"):!1}var I,E,T,Xo=class{constructor(e,t,r){l(this,I);l(this,E);l(this,T);a(this,I,e),a(this,E,t),a(this,T,r)}async get(e){return await n(this,I).Get({key:e,transactionId:n(this,E)},n(this,T)),this}async multi(){await n(this,I).Multi(n(this,E),n(this,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 n(this,I).Set({key:e,value:t,nx:r?.nx===!0,xx:r?.xx===!0,expiration:s||0,transactionId:n(this,E)},n(this,T)),this}async del(...e){return await n(this,I).Del({keys:e,transactionId:n(this,E)},n(this,T)),this}async type(e){return await n(this,I).Type({key:e,transactionId:n(this,E)},n(this,T)),this}async exec(){let e=await n(this,I).Exec(n(this,E),n(this,T)),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,I).Discard(n(this,E),n(this,T))}async watch(...e){return await n(this,I).Watch({keys:e,transactionId:n(this,E)},n(this,T)),this}async unwatch(){return await n(this,I).Unwatch(n(this,E),n(this,T)),this}async getRange(e,t,r){return await n(this,I).GetRange({key:e,start:t,end:r,transactionId:n(this,E)},n(this,T)),this}async setRange(e,t,r){return await n(this,I).SetRange({key:e,offset:t,value:r,transactionId:n(this,E)},n(this,T)),this}async strlen(e){return this.strLen(e)}async strLen(e){return await n(this,I).Strlen({key:e,transactionId:n(this,E)},n(this,T)),this}async mget(e){return this.mGet(e)}async mGet(e){return await n(this,I).MGet({keys:e,transactionId:n(this,E)},n(this,T)),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,I).MSet({kv:t,transactionId:n(this,E)},n(this,T)),this}async incrBy(e,t){return await n(this,I).IncrBy({key:e,value:t,transactionId:n(this,E)},n(this,T)),this}async expire(e,t){return await n(this,I).Expire({key:e,seconds:t,transactionId:n(this,E)},n(this,T)),this}async expireTime(e){return await n(this,I).ExpireTime({key:e,transactionId:n(this,E)},n(this,T)),this}async zAdd(e,...t){return await n(this,I).ZAdd({key:e,members:t,transactionId:n(this,E)},n(this,T)),this}async zScore(e,t){return await n(this,I).ZScore({key:{key:e,transactionId:n(this,E)},member:t},n(this,T)),this}async zRank(e,t){return await n(this,I).ZRank({key:{key:e,transactionId:n(this,E)},member:t},n(this,T)),this}async zIncrBy(e,t,r){return await n(this,I).ZIncrBy({key:e,member:t,value:r,transactionId:n(this,E)},n(this,T)),this}async zScan(e,t,r,s){let o={key:e,cursor:t,pattern:r,count:s,transactionId:n(this,E)};return await n(this,I).ZScan(o,n(this,T)),this}async zCard(e){return await n(this,I).ZCard({key:e,transactionId:n(this,E)},n(this,T)),this}async zRange(e,t,r,s){let o={rev:!1,byLex:!1,byScore:!1,offset:0,count:1e3};if(s?.reverse&&(o.rev=s.reverse),s?.by==="lex"?o.byLex=!0:s?.by==="score"&&(o.byScore=!0),s?.limit)if(o.byLex||o.byScore)o.offset=s.limit.offset,o.count=s.limit.count;else throw new Error("zRange parsing error: 'limit' only allowed when 'options.by' is 'lex' or 'score'");return await n(this,I).ZRange({key:{key:e,transactionId:n(this,E)},start:t+"",stop:r+"",...o},n(this,T)),this}async zRem(e,t){return await n(this,I).ZRem({key:{key:e,transactionId:n(this,E)},members:t},n(this,T)),this}async zRemRangeByLex(e,t,r){return await n(this,I).ZRemRangeByLex({key:{key:e,transactionId:n(this,E)},min:t,max:r},n(this,T)),this}async zRemRangeByRank(e,t,r){return await n(this,I).ZRemRangeByRank({key:{key:e,transactionId:n(this,E)},start:t,stop:r},n(this,T)),this}async zRemRangeByScore(e,t,r){return await n(this,I).ZRemRangeByScore({key:{key:e,transactionId:n(this,E)},min:t,max:r},n(this,T)),this}async hgetall(e){return this.hGetAll(e)}async hGetAll(e){return await n(this,I).HGetAll({key:e,transactionId:n(this,E)},n(this,T)),this}async hget(e,t){return this.hGet(e,t)}async hGet(e,t){return await n(this,I).HGet({key:e,field:t,transactionId:n(this,E)},n(this,T)),this}async hMGet(e,t){return await n(this,I).HMGet({key:e,fields:t,transactionId:n(this,E)},n(this,T)),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,I).HSet({key:e,fv:r,transactionId:n(this,E)},n(this,T)),this}async hincrby(e,t,r){return this.hIncrBy(e,t,r)}async hIncrBy(e,t,r){return await n(this,I).HIncrBy({key:e,field:t,value:r,transactionId:n(this,E)},n(this,T)),this}async hdel(e,t){return this.hDel(e,t)}async hDel(e,t){return await n(this,I).HDel({key:e,fields:t,transactionId:n(this,E)},n(this,T)),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,E)};return await n(this,I).HScan(o,n(this,T)),this}async hkeys(e){return this.hKeys(e)}async hKeys(e){return await n(this,I).HKeys({key:e,transactionId:n(this,E)},n(this,T)),this}async hlen(e){return this.hLen(e)}async hLen(e){return await n(this,I).HLen({key:e,transactionId:n(this,E)},n(this,T)),this}};I=new WeakMap,E=new WeakMap,T=new WeakMap;var w,yi,Qo=class Qo{constructor(e,t=void 0,r=Zo.INSTALLATION){l(this,w);l(this,yi);a(this,w,e),a(this,yi,t),this.scope=r,this.global=r===Zo.INSTALLATION?new Qo(n(this,w),n(this,yi),Zo.GLOBAL):this}get storage(){return n(this,yi)||u.redisPlugin}async watch(...e){let t=await this.storage.Watch({keys:e},n(this,w));return new Xo(this.storage,t,n(this,w))}async get(e){try{let t=await this.storage.Get({key:e,scope:this.scope},{...n(this,w),"throw-redis-nil":{values:["true"]}});return t!==null?t.value??void 0:t}catch(t){if(Nr(t))return;throw t}}async getBuffer(e){try{let t=await this.storage.GetBytes({key:e,scope:this.scope},{...n(this,w),"throw-redis-nil":{values:["true"]}});return t!==null?Buffer.from(t.value):t}catch(t){if(Nr(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,w))).value}async exists(...e){return(await this.storage.Exists({keys:e,scope:this.scope},n(this,w))).existingKeys}async del(...e){await this.storage.Del({keys:e,scope:this.scope},n(this,w))}async incrBy(e,t){return(await this.storage.IncrBy({key:e,value:t,scope:this.scope},n(this,w))).value}async getRange(e,t,r){let s=await this.storage.GetRange({key:e,start:t,end:r,scope:this.scope},n(this,w));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,w))).value}async strlen(e){return this.strLen(e)}async strLen(e){return(await this.storage.Strlen({key:e,scope:this.scope},n(this,w))).value}async expire(e,t){await this.storage.Expire({key:e,seconds:t,scope:this.scope},n(this,w))}async expireTime(e){return(await this.storage.ExpireTime({key:e,scope:this.scope},n(this,w))).value}async zAdd(e,...t){return(await this.storage.ZAdd({key:e,members:t,scope:this.scope},n(this,w))).value}async zRange(e,t,r,s){let o={rev:!1,byLex:!1,byScore:!1,offset:0,count:1e3};if(s?.reverse&&(o.rev=s.reverse),s?.by==="lex"?o.byLex=!0:s?.by==="score"?o.byScore=!0:(o.offset=0,o.count=0),s?.limit)if(o.byLex||o.byScore)o.offset=s.limit.offset,o.count=s.limit.count;else throw new Error("zRange parsing error: 'limit' only allowed when 'options.by' is 'lex' or 'score'");return(await this.storage.ZRange({key:{key:e},start:t+"",stop:r+"",...o,scope:this.scope},n(this,w))).members}async zRem(e,t){return(await this.storage.ZRem({key:{key:e},members:t,scope:this.scope},n(this,w))).value}async zRemRangeByLex(e,t,r){return(await this.storage.ZRemRangeByLex({key:{key:e},min:t,max:r,scope:this.scope},n(this,w))).value}async zRemRangeByRank(e,t,r){return(await this.storage.ZRemRangeByRank({key:{key:e},start:t,stop:r,scope:this.scope},n(this,w))).value}async zRemRangeByScore(e,t,r){return(await this.storage.ZRemRangeByScore({key:{key:e},min:t,max:r,scope:this.scope},n(this,w))).value}async zScore(e,t){try{let r=await this.storage.ZScore({key:{key:e},member:t,scope:this.scope},{...n(this,w),"throw-redis-nil":{values:["true"]}});return r!==null?r.value:r}catch(r){if(Nr(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,w),"throw-redis-nil":{values:["true"]}});return r!==null?r.value:r}catch(r){if(Nr(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,w));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,w));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,w))}async zCard(e){let t=await this.storage.ZCard({key:e,scope:this.scope},n(this,w));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,w))}async type(e){let t=await this.storage.Type({key:e,scope:this.scope},n(this,w));return t!==null?t.value:t}async rename(e,t){return(await this.storage.Rename({key:e,newKey:t,scope:this.scope},n(this,w))).result}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,w),"throw-redis-nil":{values:["true"]}});return r!==null?r.value??void 0:r}catch(r){if(Nr(r))return;throw r}}async hMGet(e,t){let r=await this.storage.HMGet({key:e,fields:t,scope:this.scope},n(this,w));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,w))).value}async hSetNX(e,t,r){return(await this.storage.HSetNX({key:e,field:t,value:r,scope:this.scope},n(this,w))).success}async hgetall(e){return this.hGetAll(e)}async hGetAll(e){let t=await this.storage.HGetAll({key:e,scope:this.scope},n(this,w));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,w))).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,w))}async hkeys(e){return this.hKeys(e)}async hKeys(e){let t=await this.storage.HKeys({key:e,scope:this.scope},n(this,w));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,w))).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:am(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}};w=new WeakMap,yi=new WeakMap;var bi=Qo;function am(i){let e=i.toLowerCase();switch(e){case"wrap":return Ko.BITFIELD_OVERFLOW_BEHAVIOR_WRAP;case"sat":return Ko.BITFIELD_OVERFLOW_BEHAVIOR_SAT;case"fail":return Ko.BITFIELD_OVERFLOW_BEHAVIOR_FAIL;default:throw Error(`unknown bitfield overflow behavior: ${e}`)}}var Ot,vi=class{constructor(e){l(this,Ot);a(this,Ot,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,Ot))).id}async cancelJob(e){await u.schedulerPlugin.Cancel({id:e},n(this,Ot))}async listJobs(){return(await u.schedulerPlugin.List({after:new Date(0),before:new Date(Date.now()+31536e7)},n(this,Ot))).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}))}};Ot=new WeakMap;import{FormFieldType as Gs}from"@devvit/protos";var Lr,ki=class{constructor(e){l(this,Lr);a(this,Lr,e)}async get(e){return(await this.getAll())[e]}async getAll(){let t=await u.settingsPlugin.GetSettings({},n(this,Lr));if(!t.installationSettings)throw new Error("Could not get installation settings");if(!t.appSettings)throw new Error("Could not get app settings");return dm(t),{...jd(t.installationSettings.settings,u.installationSettings),...jd(t.appSettings.settings,u.appSettings)}}};Lr=new WeakMap;function dm(i){if(!i.appSettings)throw new Error("Could not get app settings");for(let[e,t]of Object.entries(i.appSettings.settings)){let r=u.appSettings?.find(s=>s.type!=="group"&&s.name===e);r&&(r.type==="boolean"&&t.fieldType===Gs.STRING&&t.boolValue==null&&t.stringValue!=null?(t.fieldType=Gs.BOOLEAN,t.boolValue=!!t.stringValue,delete t.stringValue):r.type==="number"&&t.fieldType===Gs.STRING&&t.numberValue==null&&t.stringValue!=null&&(t.fieldType=Gs.NUMBER,t.numberValue=Number(t.stringValue),delete t.stringValue))}}function jd(i,e){let t=Object.keys(i).reduce((r,s)=>(r[s]=Wo(i[s]),r),{});return e&&Vd(t,e),t}function Vd(i,e){for(let t of e)t.type==="group"?Vd(i,t.fields):!(t.name in i)&&"defaultValue"in t&&(i[t.name]=t.defaultValue)}import{EffectType as Js,ToastAppearance as Wd}from"@devvit/protos";var Xe,Ci,_r,qs,zs=class{constructor(e){l(this,Xe,[]);l(this,Ci);l(this,_r);l(this,qs,(e,t)=>{let r=t!==void 0?e:"",s=t!==void 0?t:e;n(this,Xe).push({type:Js.EFFECT_WEB_VIEW,webView:{postMessage:{webViewId:r,app:{message:s}}}})});a(this,Ci,e),a(this,_r,{postMessage:n(this,qs)})}get webView(){return n(this,_r)}showForm(e,t){let r=u.formDefinitions.get(e);if(!r&&n(this,Ci)){let d=n(this,Ci).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};Tt(s.fields),o.fields=Le(s.fields),n(this,Xe).push({type:Js.EFFECT_SHOW_FORM,showForm:{form:o}})}showToast(e){let t;e instanceof Object?t={text:e.text,appearance:e.appearance==="success"?Wd.SUCCESS:Wd.NEUTRAL}:t={text:e},n(this,Xe).push({type:Js.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,Xe).push({type:Js.EFFECT_NAVIGATE_TO_URL,navigateToUrl:{url:t}})}get __effects(){return n(this,Xe)}};Xe=new WeakMap,Ci=new WeakMap,_r=new WeakMap,qs=new WeakMap;function Ce({metadata:i,ui:e,hooks:t,reconciler:r}){let s=new gi(i),o=new mi(i),d=new bi(i),c=Ed(d,r?r.state:{}),m=new fi(i),y=new vi(i),v=new ki(i),f=e?new zs(r):void 0,P=new pi(i),b=new ui,L=new hi(i),A=t&&r?yd(r):void 0,V=t&&r?fd(r):void 0,U=t&&r?hd(r):void 0,ri=t&&r?gd(r):void 0;return{modLog:s,kvStore:o,redis:d,reddit:m,scheduler:y,settings:v,media:P,assets:b,realtime:L,get useForm(){return U??(()=>{throw new Error("useForm() is unavailable")})},get cache(){return c??(()=>{throw new Error("cache() is unavailable")})},get useState(){return A??(()=>{throw new Error("useState() is unavailable")})},get useInterval(){return V??(()=>{throw new Error("useInterval() is unavailable")})},get useChannel(){return ri??(()=>{throw new Error("useChannel() is unavailable")})},get ui(){if(!f)throw new Error("ui client is not available");return f}}}var Gd={name:"@devvit/public-api",version:"0.11.15-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/metrics":"0.11.15-dev","@devvit/protos":"0.11.15-dev","@devvit/shared-types":"0.11.15-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.15-dev","@devvit/tsconfig":"0.11.15-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.8.3",vitest:"1.6.1"},publishConfig:{directory:"dist"},filesize:{"dist/public-api.min.js":{gzip:"62 KB",none:"217 KB"}},source:"./src/index.ts"};function se(i,e,t){let r=i[S.Subreddit]?.values[0];p(r,"subreddit is missing from Context");let s=i[S.SubredditName]?.values[0],o=i[S.AppUser]?.values[0],d=i[S.App]?.values[0],c=i[S.Version]?.values[0],m=i[S.User]?.values[0],y=um(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 um(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[S.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[S.Debug]&&console.info(`[api] @devvit/public-api v${Gd.version} ${Object.entries(r).map(([s,o])=>`${s}=${o}`).join(" ")}`),{...r,metadata:i}}function Jd(i){return i.flatMap(e=>e.type==="group"?Jd(e.fields):e)}async function $s(i,e,t){if(!e)throw new Error("Settings were not defined.");let r={success:!0,errors:{}},s=qe(i.fieldValues),o=Jd(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(Ce({metadata:t}),se(t)),f=await y({value:m,isEditing:i.editing},v);f&&(r.success=!1,r.errors[c]=f)}})),cm.fromJSON(r)}async function gm(){if(!u.appSettings)throw new Error("App settings were not defined.");return pm.fromJSON({fields:{fields:Le(u.appSettings)}})}async function hm(i,e){return $s(i,u.appSettings,e)}function zd(i){i.provides(mm),O("GetAppSettingsFields",gm),O("ValidateAppForm",hm)}import{CustomPostDefinition as Pm,RenderPostResponse as Sm}from"@devvit/protos";import{BlockRenderEventType as ma,EffectType as al}from"@devvit/protos";function Pi(i){return i.__effects}function qd(){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 ca,BlockAvatarBackground as rl,BlockAvatarFacing as nl,BlockAvatarSize as Qe,BlockBorderWidth as Qs,BlockButtonAppearance as Ye,BlockButtonSize as ra,BlockGap as Ys,BlockHorizontalAlignment as na,BlockIconSize as eo,BlockImageResizeMode as Hr,BlockPadding as jr,BlockRadius as Vr,BlockSpacerShape as sa,BlockSpacerSize as to,BlockStackDirection as oa,BlockTextOutline as aa,BlockTextOverflow as da,BlockTextSize as wi,BlockTextStyle as la,BlockTextWeight as sl,BlockType as Re,BlockVerticalAlignment as ua}from"@devvit/protos";var Yo={"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 $d={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"},Kd=i=>!!i.match(/^(#[0-9a-fA-F]{3,8}).*/),Zd=i=>i in Yo,ea=i=>i in $d,Xd=i=>!!i.match(/^rgba?\(.*/),Qd=i=>!!i.match(/^hsla?\(.*/),Yd=(i,e="light")=>{if(ea(i))return Ks(i);let r=Yo[i];return typeof r=="string"?r:r[e]},Ks=i=>$d[i]??i,el=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 Zs}from"@devvit/protos";var ta={stackParentLayout:{hasHeight:!0,hasWidth:!0,direction:Zs.UNRECOGNIZED,alignment:void 0}};function il(i,e,t){if(!e)return{hasHeight:!1,hasWidth:!1};let{growDirection:r,stretchDirection:s}=fm(i?.grow,e.direction,e.alignment),o=t?.height?.value?.value||t?.height?.min?.value||tl(2,r,s,e.hasHeight),d=t?.width?.value?.value||t?.width?.min?.value||tl(1,r,s,e.hasWidth);return{hasHeight:!!o,hasWidth:!!d}}function tl(i,e,t,r){return e===i&&r||t===i&&r}function fm(i,e,t){let r=e===Zs.STACK_VERTICAL||e===Zs.UNRECOGNIZED,s=e===Zs.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 Mt,BlockStackDirection as Xs}from"@devvit/protos";function Si(i){if(i==null)return;if(typeof i=="number")return{value:i,unit:Mt.SIZE_UNIT_PERCENT};let e=i.match(/^(\d+(?:\.\d+)?)(px|%)?$/);if(e==null)return;let t=Mt.SIZE_UNIT_PERCENT;return e.at(2)==="px"&&(t=Mt.SIZE_UNIT_PIXELS),{value:Number.parseFloat(e[1]),unit:t}}function ym(i,e){return(i.width?.value?.unit===Mt.SIZE_UNIT_PERCENT||i.width?.min?.unit===Mt.SIZE_UNIT_PERCENT)&&(e.direction===Xs.STACK_HORIZONTAL||e.direction===Xs.STACK_DEPTH)&&(e.hasWidth||(i.width=void 0)),(i.height?.value?.unit===Mt.SIZE_UNIT_PERCENT||i.height?.min?.unit===Mt.SIZE_UNIT_PERCENT)&&(e.direction===Xs.STACK_VERTICAL||e.direction===Xs.STACK_DEPTH)&&(e.hasHeight||(i.height=void 0)),i}function ia(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:Si(i.width),min:Si(i.minWidth),max:Si(i.maxWidth)}:void 0,height:r?{value:Si(i.height),min:Si(i.minHeight),max:Si(i.maxHeight)}:void 0,grow:i.grow};return e.stackParentLayout&&(s=ym(s,e.stackParentLayout)),s}}}var ol="data-",bm=new Set(["onPress","onMessage"]),vm=new Map([["onPress",ca.ACTION_CLICK],["onMessage",ca.ACTION_WEBVIEW]]),Wr,Fi=class{constructor(e=()=>{}){l(this,Wr);a(this,Wr,e)}createBlocksElementOrThrow({type:e,props:t,children:r}){let s=this.createBlocksElement({type:e,props:t,children:r},ta);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 jr.PADDING_NONE;case"xsmall":return jr.PADDING_XSMALL;case"small":return jr.PADDING_SMALL;case"medium":return jr.PADDING_MEDIUM;case"large":return jr.PADDING_LARGE}}makeBlockRadius(e){switch(e){case"none":return Vr.RADIUS_NONE;case"small":return Vr.RADIUS_SMALL;case"medium":return Vr.RADIUS_MEDIUM;case"large":return Vr.RADIUS_LARGE;case"full":return Vr.RADIUS_FULL}}makeBlockGap(e){switch(e){case"none":return Ys.GAP_NONE;case"small":return Ys.GAP_SMALL;case"medium":return Ys.GAP_MEDIUM;case"large":return Ys.GAP_LARGE}}makeBlockAlignment(e){if(e===void 0)return;let t,r;if(e.includes("top")?t=ua.ALIGN_TOP:e.includes("middle")?t=ua.ALIGN_MIDDLE:e.includes("bottom")&&(t=ua.ALIGN_BOTTOM),e.includes("start")?r=na.ALIGN_START:e.includes("center")?r=na.ALIGN_CENTER:e.includes("end")&&(r=na.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 wi.TEXT_SIZE_XSMALL;case"small":return wi.TEXT_SIZE_SMALL;case"medium":return wi.TEXT_SIZE_MEDIUM;case"large":return wi.TEXT_SIZE_LARGE;case"xlarge":return wi.TEXT_SIZE_XLARGE;case"xxlarge":return wi.TEXT_SIZE_XXLARGE}}makeBlockTextStyle(e){switch(e){case"body":return la.TEXT_STYLE_BODY;case"metadata":return la.TEXT_STYLE_METADATA;case"heading":return la.TEXT_STYLE_HEADING}}makeBlockTextOutline(e){switch(e){case"none":return aa.TEXT_OUTLINE_NONE;case"thin":return aa.TEXT_OUTLINE_THIN;case"thick":return aa.TEXT_OUTLINE_THICK}}makeBlockTextWeight(e){switch(e){case"regular":return sl.TEXT_WEIGHT_REGULAR;case"bold":return sl.TEXT_WEIGHT_BOLD}}makeBlockTextOverflow(e){switch(e){case"clip":return da.TEXT_OVERFLOW_CLIP;case"ellipsis":return da.TEXT_OVERFLOW_ELLIPSE}return da.TEXT_OVERFLOW_ELLIPSE}makeBlockButtonAppearance(e){switch(e){case"secondary":return Ye.BUTTON_APPEARANCE_SECONDARY;case"primary":return Ye.BUTTON_APPEARANCE_PRIMARY;case"plain":return Ye.BUTTON_APPEARANCE_PLAIN;case"bordered":return Ye.BUTTON_APPEARANCE_BORDERED;case"media":return Ye.BUTTON_APPEARANCE_MEDIA;case"destructive":return Ye.BUTTON_APPEARANCE_DESTRUCTIVE;case"caution":return Ye.BUTTON_APPEARANCE_CAUTION;case"success":return Ye.BUTTON_APPEARANCE_SUCCESS}}makeBlockButtonSize(e){switch(e){case"small":return ra.BUTTON_SIZE_SMALL;case"medium":return ra.BUTTON_SIZE_MEDIUM;case"large":return ra.BUTTON_SIZE_LARGE}}makeBlockImageResizeMode(e){switch(e){case"none":return Hr.IMAGE_RESIZE_NONE;case"fit":return Hr.IMAGE_RESIZE_FIT;case"fill":return Hr.IMAGE_RESIZE_FILL;case"cover":return Hr.IMAGE_RESIZE_COVER;case"scale-down":return Hr.IMAGE_RESIZE_SCALE_DOWN}}makeBlockSpacerSize(e){switch(e){case"xsmall":return to.SPACER_XSMALL;case"small":return to.SPACER_SMALL;case"medium":return to.SPACER_MEDIUM;case"large":return to.SPACER_LARGE}}makeBlockSpacerShape(e){switch(e){case"invisible":return sa.SPACER_INVISIBLE;case"thin":return sa.SPACER_THIN;case"square":return sa.SPACER_SQUARE}}makeBlockIconSize(e){switch(e){case"xsmall":return eo.ICON_SIZE_XSMALL;case"small":return eo.ICON_SIZE_SMALL;case"medium":return eo.ICON_SIZE_MEDIUM;case"large":return eo.ICON_SIZE_LARGE}}makeBlockAvatarSize(e){switch(e){case"xxsmall":return Qe.AVATAR_SIZE_XXSMALL;case"xsmall":return Qe.AVATAR_SIZE_XSMALL;case"small":return Qe.AVATAR_SIZE_SMALL;case"medium":return Qe.AVATAR_SIZE_MEDIUM;case"large":return Qe.AVATAR_SIZE_LARGE;case"xlarge":return Qe.AVATAR_SIZE_XXLARGE;case"xxlarge":return Qe.AVATAR_SIZE_XXLARGE;case"xxxlarge":return Qe.AVATAR_SIZE_XXXLARGE}}makeBlockAvatarFacing(e){switch(e){case"left":return nl.AVATAR_FACING_LEFT;case"right":return nl.AVATAR_FACING_RIGHT}}makeBlockAvatarBackground(e){switch(e){case"dark":return rl.AVATAR_BG_DARK;case"light":return rl.AVATAR_BG_LIGHT}}getDataSet(e){return Object.keys(e).filter(t=>t.startsWith(ol)).reduce((t,r)=>(t[r.substring(ol.length)]=e[r],t),{})}makeActions(e,t){let r=[],s=this.getDataSet(t);return bm.forEach(o=>{if(o in t){let d=t[o];r.push({type:vm.get(o)??ca.UNRECOGNIZED,id:d.toString(),data:s})}}),r}blockColorToHex(e,t="light"){if(e)return e=e.toLowerCase(),Kd(e)?e:Zd(e)?Yd(e,t):ea(e)?Ks(e):Xd(e)?el(e):Qd(e)?e:(console.warn(`Could not parse color: ${e}.`),Ks("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,Wr).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,ta))}wrapRoot(e,t){return this.makeBlock(Re.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=ia(t,r),m=il(t,r.stackParentLayout,c);return this.makeBlock(Re.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(oa.STACK_HORIZONTAL,e,t,r)}makeVStack(e,t,...r){return this.makeStackBlock(oa.STACK_VERTICAL,e,t,r)}makeZStack(e,t,...r){return this.makeStackBlock(oa.STACK_DEPTH,e,t,r)}makeText(e,t,...r){let s=this.getThemedColors(e?.color,e?.lightColor,e?.darkColor);return this.makeBlock(Re.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(Re.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(Re.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(Re.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(Re.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(Re.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(Re.BLOCK_WEBVIEW,e,t,{webviewConfig:{url:this.resolveAssetUrl(e.url,{webView:!0})}})}makeBlock(e,t,r,s){return{type:e,sizes:ia(t,r),config:s,actions:(t&&this.makeActions(e,t))??[],id:t?.id,key:t?.key}}ensureRootBlock(e){let t;if(e.type===Re.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}};Wr=new WeakMap;function dl(i){if(typeof i=="string")throw new Error("Root element cannot be a string")}var ll=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+=ll(r);return e+=`</${i.type}>`,e};function km(i){return" ".repeat(i)}function Cm(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+=km(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 Pe,ul,Gr,pa,Jr,_e=class{constructor(e,t,r,s,o){l(this,Pe);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 Fi(()=>this.assets);this.effects=[];l(this,Jr,!1);this.component=e,this.event=t,this.state={__renderState:{},...r},this.metadata=s,this.state.__realtimeChannels&&(this.realtimeChannels=this.state.__realtimeChannels);let d=Ce({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,Pe,Gr).call(this),t={type:this.component,props:e,children:[]},r=await this.processBlock(t);if(dl(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,Pe,ul).call(this)}async buildBlocksUI(){let e=h(this,Pe,Gr).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 dl(r),(u.debug.emitSnapshots||e.debug.emitSnapshots)&&console.debug(Cm(ll(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=qd(),r=[]){let s=e;if(typeof s.type=="string"){let c=[];for(let f=0;f<s.children.length;f++){let P=s.children[f];P!=null&&c.push(await this.processBlock(P,t,[...r,`${s.type}.${f}`]))}let m=c.flat(),y=h(this,Pe,pa).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,Pe,Gr).call(this),...s.props,children:m},v;for(;v===void 0;)try{v=await s.type(y,h(this,Pe,Gr).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===ma.RENDER_INITIAL:!1}get isUserActionRender(){return this.event?this.event.type===ma.RENDER_USER_ACTION:!1}get isEffectRender(){return this.event?this.event.type===ma.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,Jr)||(a(this,Jr,!0),this.effects.push({type:al.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:al.EFFECT_REALTIME_SUB,realtimeSubscriptions:{subscriptionIds:this.realtimeChannels}}]:[]}getEffects(){return[...Pi(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}:{}}}};Pe=new WeakSet,ul=function(){this.actions.clear(),this.currentComponentKey=[],this.currentHookIndex=0,this.pendingHooks=[],this.realtimeChannels=[],this.realtimeUpdated=!1},Gr=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[S.Timezone]?.values[0],locale:this.metadata[S.Language]?.values[0],dimensions:this.dimensions},...this.hooks};return e.debug.effects=this,e},pa=function(e){let t=[];for(let r of e)typeof r=="string"?t.push(r):r.type==="__fragment"?t.push(...h(this,Pe,pa).call(this,r.children)):t.push(r);return t},Jr=new WeakMap;async function wm(i,e){let t=u.customPostType;if(!t)throw new Error("Custom post type not registered");let r=new _e((o,d)=>t.render(d),i.blocks,i.state,e,i.dimensions),s=await r.render();return Sm.fromJSON({state:r.state,blocks:{ui:s},effects:r.getEffects()})}function cl(i){i.provides(Pm),O("RenderPost",wm)}import{GetFieldsResponse as Fm,InstallationSettingsDefinition as xm}from"@devvit/protos";async function Am(){if(!u.installationSettings)throw new Error("Installation settings were not defined.");return Fm.fromJSON({fields:{fields:Le(u.installationSettings)}})}async function Im(i,e){return $s(i,u.installationSettings,e)}function ml(i){i.provides(xm),O("GetSettingsFields",Am),O("ValidateForm",Im)}import{ContextActionDefinition as Em,ContextActionList as Tm,ContextActionResponse as Rm}from"@devvit/protos";function ga(i){let e=i.debug.metadata[S.User].values[0];if(!e)throw new Error("User missing from context");return e}function ha(i){let e=i.debug.metadata[S.Subreddit].values[0];if(!e)throw new Error("Subreddit missing from context");return e}async function pl(i,e){let t=ga(i),r=ha(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=zr(e.actionId);if(!m)throw new Error("Action not found");let y=!!m.forUserType?.includes("moderator");if(y&&!gl(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)}async function gl(i){let e=ga(i),t=ha(i),r=await i.reddit.getSubredditInfoById(t);return!!(await i.reddit.getModerators({subredditName:r.name}).all()).find(o=>o.id===e)}async function hl(i,e){let t=ga(i),r=ha(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 gl(i))throw new Error("User is not a moderator: "+t+"; "+r)}var fl=i=>`menuItem.${i}`;function zr(i){return u.menuItems.find((e,t)=>fl(t)===i)}async function Om(i,e){let t=u.menuItems;if(!t.length)throw new Error("No menu items registered.");let r=t.map((s,o)=>({actionId:fl(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 Tm.fromJSON({actions:r})}async function Mm(i,e){let t=zr(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(Ce({ui:!0,metadata:e}),se(e,s,r),{uiEnvironment:{timezone:e[S.Timezone]?.values[0],locale:e[S.Language]?.values[0]}});return await pl(m,i),await t.onPress(c,m),Rm.fromJSON({effects:Pi(m.ui)})}function yl(i){i.provides(Em),O("GetActions",Om),O("OnAction",Mm)}function Se(i){return i?i===!0?!0:i.enabled:!1}import{SchedulerHandlerDefinition as Um}from"@devvit/protos";async function Bm(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(Ce({metadata:e}),se(e));return await r(s,o),{}}function bl(i){i.provides(Um),O("HandleScheduledAction",Bm)}import{OnAppInstallDefinition as Dm,OnAppUpgradeDefinition as Nm,OnAutomoderatorFilterCommentDefinition as Lm,OnAutomoderatorFilterPostDefinition as _m,OnCommentCreateDefinition as Hm,OnCommentDeleteDefinition as jm,OnCommentReportDefinition as Vm,OnCommentSubmitDefinition as Wm,OnCommentUpdateDefinition as Gm,OnModActionDefinition as Jm,OnModMailDefinition as zm,OnPostCreateDefinition as qm,OnPostDeleteDefinition as $m,OnPostFlairUpdateDefinition as Km,OnPostNsfwUpdateDefinition as Zm,OnPostReportDefinition as Xm,OnPostSpoilerUpdateDefinition as Qm,OnPostSubmitDefinition as Ym,OnPostUpdateDefinition as ep}from"@devvit/protos";var et;(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})(et||(et={}));function $(i,e){return p(e),async(t,r)=>{let s={...t,type:i},o=Object.assign(Ce({metadata:r}),se(r)),d=await Promise.allSettled(e.map(m=>m(s,o))),c=tp(d);if(c)throw c.err;return{}}}function vl(i){for(let e of u.triggerOnEventHandlers.keys())switch(e){case"PostSubmit":i.provides(Ym),O("OnPostSubmit",$("PostSubmit",u.triggerOnEventHandlers.get(e)));break;case"PostCreate":i.provides(qm),O("OnPostCreate",$("PostCreate",u.triggerOnEventHandlers.get(e)));break;case"PostUpdate":i.provides(ep),O("OnPostUpdate",$("PostUpdate",u.triggerOnEventHandlers.get(e)));break;case"PostReport":i.provides(Xm),O("OnPostReport",$("PostReport",u.triggerOnEventHandlers.get(e)));break;case"PostDelete":i.provides($m),O("OnPostDelete",$("PostDelete",u.triggerOnEventHandlers.get(e)));break;case"PostFlairUpdate":i.provides(Km),O("OnPostFlairUpdate",$("PostFlairUpdate",u.triggerOnEventHandlers.get(e)));break;case"CommentSubmit":i.provides(Wm),O("OnCommentSubmit",$("CommentSubmit",u.triggerOnEventHandlers.get(e)));break;case"CommentCreate":i.provides(Hm),O("OnCommentCreate",$("CommentCreate",u.triggerOnEventHandlers.get(e)));break;case"CommentUpdate":i.provides(Gm),O("OnCommentUpdate",$("CommentUpdate",u.triggerOnEventHandlers.get(e)));break;case"CommentReport":i.provides(Vm),O("OnCommentReport",$("CommentReport",u.triggerOnEventHandlers.get(e)));break;case"CommentDelete":i.provides(jm),O("OnCommentDelete",$("CommentDelete",u.triggerOnEventHandlers.get(e)));break;case"AppInstall":i.provides(Dm),O("OnAppInstall",$("AppInstall",u.triggerOnEventHandlers.get(e)));break;case"AppUpgrade":i.provides(Nm),O("OnAppUpgrade",$("AppUpgrade",u.triggerOnEventHandlers.get(e)));break;case"ModAction":i.provides(Jm),O("OnModAction",$("ModAction",u.triggerOnEventHandlers.get(e)));break;case"ModMail":i.provides(zm),O("OnModMail",$("ModMail",u.triggerOnEventHandlers.get(e)));break;case"PostNsfwUpdate":i.provides(Zm),O("OnPostNsfwUpdate",$("PostNsfwUpdate",u.triggerOnEventHandlers.get(e)));break;case"PostSpoilerUpdate":i.provides(Qm),O("OnPostSpoilerUpdate",$("PostSpoilerUpdate",u.triggerOnEventHandlers.get(e)));break;case"AutomoderatorFilterPost":i.provides(_m),O("OnAutomoderatorFilterPost",$("AutomoderatorFilterPost",u.triggerOnEventHandlers.get(e)));break;case"AutomoderatorFilterComment":i.provides(Lm),O("OnAutomoderatorFilterComment",$("AutomoderatorFilterComment",u.triggerOnEventHandlers.get(e)));break;default:throw new Error(`Unknown trigger event: ${e}`)}}function tp(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=>et.caughtToString(t)).join(`
|
|
3
|
-
`))}}import{EffectType as Fp,HandleUIEventResponse as ba,UIEventHandlerDefinition as xp}from"@devvit/protos";var Dl=ad(Rl(),1);function Ol(i){return i?.constructor===Object}function Ut(i,e){return Object.is(i,e)?!0:typeof i!=typeof e?!1:Array.isArray(i)&&Array.isArray(e)?Ml(i,e):i instanceof Date&&e instanceof Date?i.getTime()===e.getTime():i instanceof RegExp&&e instanceof RegExp?i.toString()===e.toString():Ol(i)&&Ol(e)?wp(i,e):i instanceof ArrayBuffer&&e instanceof ArrayBuffer?Ul(new DataView(i),new DataView(e)):i instanceof DataView&&e instanceof DataView?Ul(i,e):Bl(i)&&Bl(e)?i.byteLength!==e.byteLength?!1:Ml(i,e):!1}function wp(i,e){let t=Object.keys(i),r=Object.keys(e);if(!Ut(t,r))return!1;for(let s of t)if(!Ut(i[s],e[s]))return!1;return!0}function Ml(i,e){return i.length!==e.length?!1:i.every((t,r)=>Ut(t,e[r]))}function Ul(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 Bl(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}async function Ap(i,e){let t=i.state??{},r=(0,Dl.default)(t),s=Ce({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 _e((L,A)=>u.customPostType?.render(A)??null,i.event,i.state,e,void 0);return await b.reconcile(),ba.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:L}=r.__contextAction,A=zr(b);A?.location==="post"?v=L:A?.location==="comment"&&(f=L)}let P=Object.assign(s,se(e,v,f),{uiEnvironment:{timezone:e[S.Timezone]?.values[0],locale:e[S.Language]?.values[0]}});await hl(P,i),await y.onSubmit({values:qe(i.event.formSubmitted.results)},P)}else if(i.event?.realtimeEvent){if(u.customPostType){let m=new _e((y,v)=>u.customPostType?.render(v)??null,i.event,i.state,e,void 0);return await m.reconcile(),ba.fromJSON({state:m.state,effects:m.getEffects()})}}else if(i.event?.toastAction)throw new Error("Toast actions not yet implemented");let o=!Ut(t,r),d=Pi(s.ui),c=o?[...d,{type:Fp.EFFECT_RERENDER_UI,rerenderUi:{delaySeconds:0}}]:d;return ba.fromJSON({state:r,effects:c})}function Nl(i){i.provides(xp),O("HandleUIEvent",Ap)}import{CustomPostDefinition as fo,UIResponse as uu}from"@devvit/protos";import{UIEventScope as Bp}from"@devvit/protos";var va="ServerCallRequired";function io(i){return i?.message===va}var Sa={now(){return new Date}};function Ll(i){return`__autocache__${i}`}function _l(i){return`__lock__${i}`}var Ip=300,Ep=1e3,ro=5e3,ka=3,Hl=.1,jl=1e3,Tp=3e4;function Vl(i){if(i.error)throw new Error(i.error);return i.value}var tt,it,we,xi,q,Wl,Gl,Jl,Ca,zl,ql,Pa,$l,no=class{constructor(e,t,r=Sa){l(this,q);l(this,tt);l(this,it,{});l(this,we);l(this,xi);a(this,tt,e),a(this,xi,t),a(this,we,r)}async cache(e,t){var d;(d=n(this,xi)).__cache??(d.__cache={}),a(this,it,n(this,xi).__cache),h(this,q,$l).call(this,t);let r=h(this,q,Wl).call(this,t.key);if(r!==void 0)return r;let s=await h(this,q,Pa).call(this,t.key),o=await h(this,q,Gl).call(this,t,s,e);return Vl(o)}};tt=new WeakMap,it=new WeakMap,we=new WeakMap,xi=new WeakMap,q=new WeakSet,Wl=function(e){let t=n(this,it)[e];if(t){let r=n(this,we).now().getTime(),s=t?.error&&t?.errorTime&&t.errorCount<ka&&Math.random()<Hl&&t.errorTime+jl<r;if(t?.expires&&t.expires<r&&t.checkedAt+jl<r||s){delete n(this,it)[e];return}else return Vl(t)}},Gl=async function(e,t,r){let s=t?.expires,o=s?h(this,q,ql).call(this,s):1;return!t||t?.error&&t.errorCount<ka&&Hl>Math.random()||o>Math.random()?h(this,q,Jl).call(this,e,t,r):t},Jl=async function(e,t,r){let s=_l(e.key),o=n(this,we).now().getTime(),d=new Date(o+e.ttl/2);if(await n(this,tt).set(s,"1",{expiration:d,nx:!0}))return h(this,q,zl).call(this,e.key,t,r,e.ttl);if(t)return t;{let m=n(this,we).now();return h(this,q,Ca).call(this,m,e.key,e.ttl)}},Ca=async function(e,t,r){let s=Math.min(r,Ep),o=await h(this,q,Pa).call(this,t);if(o)return o;if(n(this,we).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,Ip)),h(this,q,Ca).call(this,e,t,r)},zl=async function(e,t,r,s){let o=n(this,we).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,we).now().getTime(),t.errorCount++}return n(this,it)[e]=t,await n(this,tt).set(Ll(e),JSON.stringify(t),{expiration:new Date(o+Tp)}),t.error&&t.errorCount<ka&&await n(this,tt).del(_l(e)),t},ql=function(e){let t=n(this,we).now().getTime(),r=e-t;return r<0?1:r<1e3?.1:r<2e3?.01:r<3e3?.001:0},Pa=async function(e){let t=await n(this,tt).get(Ll(e));if(t){let r=JSON.parse(t);return r.checkedAt=n(this,we).now().getTime(),n(this,it)[e]=r,r}},$l=function(e){e.ttl<ro&&(console.warn(`Cache TTL cannot be less than ${ro} milliseconds! Updating ttl value of ${e.ttl} to ${ro}.`),e.ttl=ro)};function Kl(i,e,t=Sa){let r=new no(i,e,t);return r.cache.bind(r)}import{EffectType as so,ToastAppearance as Ql}from"@devvit/protos";function Zl(i){let e=i.match(/form\.hook\.(.+)\.0/);if(e?.[1])return e[1]}var wa=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(qe(s.formSubmitted.results))}}};function Fa(i,e){let t=me({namespace:"useForm",initializer:r=>new wa(r,i,e)});return Rp({id:t.hookId})}function Rp(i){return`form.hook.${i.id}.0`}function Xl(i,e){let t=Zl(e);return i.getHook({id:t})}var He,ao,qr,lo,oo=class{constructor(e){l(this,He);l(this,ao,0);l(this,qr);l(this,lo,(e,t)=>{let r=t!==void 0?e:"",s=t!==void 0?t:e;n(this,He).emitEffect(`postMessage${dd(this,ao)._++}`,{type:so.EFFECT_WEB_VIEW,webView:{postMessage:{webViewId:r,app:{message:s,jsonString:JSON.stringify(s)}}}})});a(this,He,e),a(this,qr,{postMessage:n(this,lo)})}get webView(){return n(this,qr)}showForm(e,t){let r=Xl(n(this,He),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};Tt(s.fields),o.fields=Le(s.fields),n(this,He).emitEffect(e,{type:so.EFFECT_SHOW_FORM,showForm:{form:o}})}showToast(e){let t;e instanceof Object?t={text:e.text,appearance:e.appearance==="success"?Ql.SUCCESS:Ql.NEUTRAL}:t={text:e},n(this,He).emitEffect(e.toString(),{type:so.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,He).emitEffect(t,{type:so.EFFECT_NAVIGATE_TO_URL,navigateToUrl:{url:t}})}};He=new WeakMap,ao=new WeakMap,qr=new WeakMap,lo=new WeakMap;import{EffectType as Op,RealtimeSubscriptionStatus as Yl}from"@devvit/protos";var rt,Oe,nt,Bt,$r,Aa,uo=class uo{constructor(e,t){l(this,$r);l(this,rt);l(this,Oe);l(this,nt);l(this,Bt);a(this,rt,t.context),a(this,Oe,!!t.context._devvitContext?.debug.realtime),a(this,Bt,e),a(this,nt,t.invalidate);let r=t.context.meta[S.App]?.values[0];if(!r)throw Error("useChannel missing app ID metadata");let s=t.context.meta[S.Installation]?.values[0];if(!s)throw Error("useChannel missing install ID from metadata");let o=`${r}:${s}:${e.name}`;if(Object.values(n(this,rt)._hooks).filter(c=>c instanceof uo).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 Yl.REALTIME_SUBSCRIBED:n(this,Oe)&&console.debug(`[realtime] "${this.state.channel}" connected`),this.state.connected=!0,n(this,nt).call(this),await n(this,Bt).onSubscribed?.();break;case Yl.REALTIME_UNSUBSCRIBED:n(this,Oe)&&console.debug(`[realtime] "${this.state.channel}" disconnected`),this.state.connected=!1,n(this,nt).call(this),await n(this,Bt).onUnsubscribed?.();break;default:n(this,Oe)&&console.debug(`[realtime] "${this.state.channel}" received message: ${JSON.stringify(e,void 0,2)}`),n(this,Bt).onMessage(t.event?.data?.msg);break}}async send(e){if(n(this,Oe)&&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,rt).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,Oe)&&console.debug(`[realtime] "${this.state.channel}" subscribed`),this.state.subscribed=!0,n(this,nt).call(this),h(this,$r,Aa).call(this))}unsubscribe(){this.state.subscribed&&(n(this,Oe)&&console.debug(`[realtime] "${this.state.channel}" unsubscribed`),this.state.subscribed=!1,n(this,nt).call(this),h(this,$r,Aa).call(this))}};rt=new WeakMap,Oe=new WeakMap,nt=new WeakMap,Bt=new WeakMap,$r=new WeakSet,Aa=function(){let e=Object.values(n(this,rt)._hooks).filter(t=>t instanceof uo&&t.state.subscribed).map(t=>t.state.channel);n(this,rt).emitEffect(this.state.channel,{type:Op.EFFECT_REALTIME_SUB,realtimeSubscriptions:{subscriptionIds:e}})};var xa=uo;function Ia(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 me({id:e,namespace:e,initializer:t=>new xa(i,t)})}import{EffectType as Ea}from"@devvit/protos";function eu(i){return typeof i=="object"&&i!==null&&"__deleted"in i}var Dt,st,Ai=class Ai{constructor(e,t){l(this,Dt);this._segments=[];l(this,st,{});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,Dt,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,Dt).__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,st)).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,st)}set _hooks(e){this._prevHooks=n(this,st),a(this,st,e)}get _state(){return n(this,Dt)}set _state(e){a(this,Dt,e)}push(e){this._segments.push({...e,next:0})}pop(){this._segments.pop()}addUndeliveredEventHandler(e,t){this._undeliveredHandlers[e]=t}addGlobalUndeliveredEventHandler(e,t){Ai.addGlobalUndeliveredEventHandler(e,t)}getHook(e){return n(this,st)[e.id]}static addGlobalUndeliveredEventHandler(e,t){Ai._staticUndeliveredHandlers[e]=t}async handleUndeliveredEvent(e){let t={...Ai._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()}}};Dt=new WeakMap,st=new WeakMap,Ai._staticUndeliveredHandlers={};var Ii=Ai;var ot={};Ii.addGlobalUndeliveredEventHandler("intervals",async(i,e)=>{i.timer&&i.hook&&(delete ot[i.hook],e.emitEffect("timers",{type:Ea.EFFECT_SET_INTERVALS,interval:{intervals:ot}}))});var at,Ei,Kr,Ti,Ta=class{constructor(e,t,r){l(this,at);l(this,Ei);l(this,Kr);l(this,Ti);this.state={duration:{seconds:0,nanos:0},running:!1};a(this,Ei,r.invalidate),a(this,at,r.hookId),a(this,Kr,e),a(this,Ti,r.context);let s=Math.floor(t/1e3),o=t%1e3*1e6;this.state.duration={seconds:s,nanos:o}}onStateLoaded(){this.state.running?ot[n(this,at)]={duration:this.state.duration}:delete ot[n(this,at)]}async onUIEvent(e){await n(this,Kr).call(this)}start(){ot[n(this,at)]={duration:this.state.duration},this.state.running=!0,n(this,Ei).call(this),n(this,Ti).emitEffect("timers",{type:Ea.EFFECT_SET_INTERVALS,interval:{intervals:ot}})}stop(){delete ot[n(this,at)],this.state.running=!1,n(this,Ei).call(this),n(this,Ti).emitEffect("timers",{type:Ea.EFFECT_SET_INTERVALS,interval:{intervals:ot}})}};at=new WeakMap,Ei=new WeakMap,Kr=new WeakMap,Ti=new WeakMap;function Ra(i,e){let t=me({namespace:"useInterval",initializer:r=>new Ta(i,e,r)});return{start:()=>t.start(),stop:()=>t.stop()}}import{UIEventScope as Up}from"@devvit/protos";var Nt=class extends Error{};import{UIEventScope as tu}from"@devvit/protos";function Ma(i){if(i instanceof Error){if(i.message===va)throw i;return console.error(i),{message:i.message,details:i.stack??""}}else return console.error(i),{message:"Unknown error",details:et.caughtToString(i)}}var Ae,Me,Ri,Zr,Oi,Oa=class{constructor(e,t,r){l(this,Ae);l(this,Me);l(this,Ri);l(this,Zr);l(this,Oi);a(this,Ae,!!r.context.devvitContext.debug.useAsync),n(this,Ae)&&console.debug("[useAsync] v1",t),this.state={data:null,load_state:"initial",error:null,depends:null},a(this,Me,r.hookId),this.initializer=e,a(this,Ri,r.invalidate),a(this,Zr,r.context),this.localDepends=t.depends??null,a(this,Oi,t)}onStateLoaded(){if(n(this,Ae)&&console.debug("[useAsync] async onLoad ",n(this,Me),this.state),n(this,Ae)&&console.debug("[useAsync] async onLoad have ",this.localDepends,"and",this.state.depends),!Ut(this.localDepends,this.state.depends)||this.state.load_state==="initial"){n(this,Ae)&&console.debug("[useAsync] attempting to resolve for hookId",n(this,Me)),this.state.load_state="loading",this.state.depends=this.localDepends,n(this,Ri).call(this);let e={scope:tu.ALL,hook:n(this,Me),async:!0,asyncRequest:{requestId:n(this,Me)+"-"+JSON.stringify(this.state.depends)}};n(this,Ae)&&console.debug("[useAsync] onLoad requeue"),n(this,Zr).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=Ma(o)}let s={scope:tu.ALL,asyncResponse:r,hook:n(this,Me)};n(this,Ae)&&console.debug("[useAsync] onReq requeue"),t.addToRequeueEvents(s)}else if(e.asyncResponse){let r=n(this,Me)+"-"+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,Oi).finally&&await n(this,Oi).finally(this.state.data,this.state.error?new Error(this.state.error?.message??"Unknown error"):null),n(this,Ri).call(this)):n(this,Ae)&&console.debug("[useAsync] onResp skip, stale event",e.asyncResponse.requestId," !== ",r)}else throw new Error("Unknown event type")}};Ae=new WeakMap,Me=new WeakMap,Ri=new WeakMap,Zr=new WeakMap,Oi=new WeakMap;function Mp(i,e={}){let t=me({namespace:"useAsync",initializer:r=>new Oa(i,e,r)});return{data:t.state.data,error:t.state.error,loading:t.state.load_state==="loading"}}var je,Mi,Lt,dt,Ua=class{constructor(e,t){this.state={value:null,load_state:"initial",error:null};l(this,je);l(this,Mi);l(this,Lt);l(this,dt);a(this,Lt,e),a(this,dt,t.hookId),a(this,je,t.invalidate),a(this,Mi,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=Ma(e)}n(this,je).call(this)}else console.warn(`Invalid state for hook (${n(this,dt)}):`,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,je).call(this)}onStateLoaded(){if(this._promise=n(this,Mi)._prevHooks[n(this,dt)]?._promise,this.state.load_state==="loading")throw new Nt;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,Lt)instanceof Function?n(this,Lt).call(this):n(this,Lt)}catch(t){console.log("error in loading async",t),this.state.load_state="error",n(this,je).call(this);return}if(e instanceof Promise){this._promise=e,this.state.load_state="loading";let t={scope:Up.ALL,asyncRequest:{requestId:n(this,dt)},hook:n(this,dt)};throw n(this,Mi).addToRequeueEvents(t),n(this,je).call(this),new Nt}else this.state.value=e,this.state.load_state="loaded";n(this,je).call(this)}}};je=new WeakMap,Mi=new WeakMap,Lt=new WeakMap,dt=new WeakMap;function Ba(i){let e=me({namespace:"useState",initializer:t=>new Ua(i,t)});return[e.state.value,e.setter.bind(e)]}var co=class{buildContext(e,t,r){let s=new gi(r),o=new mi(r),d=new bi(r),c=new fi(r),m=new vi(r),y=new ki(r),v=new oo(e),f=new pi(r),P=new ui,b=new hi(r),L=Kl(d,e._state),A={modLog:s,kvStore:o,redis:d,reddit:c,scheduler:m,settings:y,media:f,assets:P,realtime:b,ui:v,useState:Ba,useChannel:Ia,useInterval:Ra,useForm:Fa,cache:L,dimensions:t.env?.dimensions,uiEnvironment:{timezone:r[S.Timezone]?.values[0],locale:r[S.Language]?.values[0],dimensions:t.env?.dimensions,colorScheme:t.env?.colorScheme}},V=se(r,t.props?.postId);return V.debug.effects=e,{...V,...A}}};var pe=null;function iu(i){return JSON.parse(JSON.stringify(i))}function Dp(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 me({initializer:i,...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.");Dp(e.namespace);let t=pe.nextHookId(e),r=pe,s={hookId:t,invalidate:()=>{r._changed[t]=!0,r._state[t]=r?._hooks[t]?.state},context:pe},o=pe._state[t]===void 0||eu(pe._state[t]);pe._hooks[t]=pe._hooks[t]??i(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 Np=null,mo=128,Ui,ho,Xr,F,oe,po,ru,Da,nu,Na,La,go,_a,su,_t=class{constructor(e){l(this,F);l(this,Ui);l(this,ho,new co);l(this,Xr,new Fi(()=>this._latestRenderContext?.devvitContext?.assets));this._latestRenderContext=null;n(this,F,oe)&&console.debug("[blocks] BlocksHandler v1"),a(this,Ui,e),Np=this}async handle(e,t){let r=new Ii(e,t),s=n(this,ho).buildContext(r,e,t);r.devvitContext=s;let o,d=e.events.length-mo,c=e.events;if(d>0){c=[];{let A=0;for(let V of e.events)A<d&&V.realtimeEvent?A++:c.push(V)}for(;c.length>mo;)c.shift();console.warn(`dropped ${d} events`)}let y=!c.length||c.some(A=>!A.async),v=c.some(A=>A.blocking),f,P,b=[...c];c.length===0&&c.push({scope:Bp.ALL}),n(this,F,oe)&&console.debug("[blocks] starting processing events");let L=0;for(;c.length>0;){if(L++>mo)throw new Error(`Exceeded maximum iterations of ${mo}`);n(this,F,oe)&&console.debug("[blocks] processing events loop iteration",c.length);let A=[];if(!c[0].async)A.push(c.shift());else for(;c[0]?.async;)A.push(c.shift());if(!A.length)throw Error("batch must have at least one event");try{if(A[0].async){let U=iu(r._state);await h(this,F,ru).call(this,r,...A),r._state=U}else await h(this,F,nu).call(this,r,...A)}catch(U){if(!io(U))throw U;if(n(this,F,oe)&&console.debug("[blocks] caught in handler",U),r._latestRenderContent=void 0,P){r._state=P._state,r._changed=f,r._effects=P._effects;let ri=b.map(rd=>{let nd={...rd};return nd.retry=!0,nd});r.addToRequeueEvents(...ri);break}else throw io(U)||console.error("[blocks] unhandled error in handler",U),U}n(this,F,oe)&&console.debug("[blocks] remaining events",r._requeueEvents);let V=[];for(let U of r._requeueEvents){if(!y&&!U.async){n(this,F,oe)&&console.debug("[blocks] NOT reprocessing event in BlocksHandler, sync mismatch A",U),V.push(U);continue}if(y&&U.async&&!v){n(this,F,oe)&&console.debug("[blocks] NOT reprocessing event in BlocksHandler, sync mismatch B",U),V.push(U);continue}n(this,F,oe)&&console.debug("[blocks] reprocessing event in BlocksHandler",U),c.push(U)}r._requeueEvents=V,c.length>0&&(f={...r._changed},P={_state:iu(r._state),_effects:{...r._effects}},b=[...c])}if(y){r._latestRenderContent||(r._latestRenderContent=h(this,F,Na).call(this,n(this,Ui),r.request.props??{},r));let A=r._latestRenderContent;A&&(o=n(this,Xr).createBlocksElementOrThrow(A),o=n(this,Xr).ensureRootBlock(o))}return{state:r._changedState,effects:r.effects,blocks:o,events:r._requeueEvents}}};Ui=new WeakMap,ho=new WeakMap,Xr=new WeakMap,F=new WeakSet,oe=function(){return!!this._latestRenderContext?.devvitContext.debug.blocks},po=function(e,...t){e._hooks={},h(this,F,Na).call(this,n(this,Ui),e.request.props??{},e)},ru=async function(e,...t){h(this,F,po).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,F,Da).call(this,e,r)}))},Da=async function(e,t){let r=e._hooks[t.hook];if(r?.onUIEvent)try{await r.onUIEvent(t,e)}catch(s){throw io(s)?n(this,F,oe)&&console.error("Server call required",s):console.error("Error in event handler",s),s}else await e.handleUndeliveredEvent(t)},nu=async function(e,...t){for(let r of t)n(this,F,oe)&&console.log("[blocks] handling main queue event",r),n(this,F,oe)&&console.log("[blocks] before",e._state),h(this,F,po).call(this,e,r),await h(this,F,Da).call(this,e,r),n(this,F,oe)&&console.log("[blocks] after",e._state);h(this,F,po).call(this,e)},Na=function(e,t,r){n(this,F,oe)&&console.debug("[blocks] renderRoot"),r._generated={},pe=r,this._latestRenderContext=r;try{let s=h(this,F,La).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 Nt)return;throw s}finally{pe=null}},La=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,F,_a).call(this,s,r)}finally{r.pop()}},go=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,F,_a).call(this,r,t)))},_a=function(e,t){if(Array.isArray(e))return h(this,F,go).call(this,e,t);if(Lp(e))if(e.type===void 0)try{return t.push({namespace:"fragment",...e.props}),h(this,F,go).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,F,La).call(this,e.type,r,t)}else try{t.push({namespace:e.type,...e.props});let r=h(this,F,go).call(this,e.children,t),s=h(this,F,su).call(this,e.props??{});return[{type:e.type,children:r,props:s}]}finally{t.pop()}else return[(e??"").toString()]},su=function(e){let t={};for(let r in e)if(!(typeof e[r]>"u"))if(typeof e[r]=="function"){let s=me({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){let c=d.webView.postMessage.jsonString?JSON.parse(d.webView.postMessage.jsonString):d.webView.postMessage.message;return e[r](c)}}})});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 Lp(i){return typeof i=="object"&&i!=null&&"type"in i}var ou=i=>{let e=Number(i.trim().split(".").pop());return isNaN(e)?void 0:e},au=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=ou(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=ou(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)},du=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),_p=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}`)}},Hp=({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=_p(i);t?e.ui.navigateTo(t):console.warn("No upgrade link found for platform:",i)}},"Upgrade"))))),lu=i=>()=>u.createElement(Hp,{platform:i});var jp=()=>u.createElement("vstack",{alignment:"center middle",width:"100%",height:"100%"},u.createElement("text",null,"This feature is not available yet")),Vp=[[fo,fo.methods.renderPostContent,(i,e)=>u.customPostType?.render(e)??null],[fo,fo.methods.renderPostComposer,(i,e)=>u.createElement(jp,null)]];function Wp(i){return async(e,t)=>{let r=au(t["devvit-user-agent"]?.values?.[0]??"");if(r&&du(r)){let o=new _t(lu(r.platform));return uu.fromJSON(await o.handle(e,t))}let s=new _t(i);return uu.fromJSON(await s.handle(e,t))}}function cu(i){for(let[e,t,r]of Vp)i.provides(e),O(t.name,Wp(r))}var lt,Qr,ut,Ht,jt,ct,Bi,Vt,mt,Yr,en,Wt,H,B=class B extends _s{static configure(e){a(this,ut,{...n(this,ut),...e}),Se(e.http)&&this.use(k.HTTPDefinition),(e.redis===void 0||Se(e.kvStore)||Se(e.redis))&&(this.use(k.KVStoreDefinition),this.use(k.RedisAPIDefinition)),Se(e.media)&&this.use(k.MediaServiceDefinition),Se(e.modLog)&&this.use(k.ModlogDefinition),Se(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)),Se(e.realtime)&&this.use(k.RealtimeDefinition),Se(e.userActions)&&this.use(k.UserActionsDefinition)}static addMenuItem(e){n(this,Bi).push(e)}static addCustomPostType(e){a(this,Ht,e)}static createForm(e,t){let r=`form.${n(this,jt).size}`;return n(this,jt).set(r,{form:e,onSubmit:t}),r}static addSchedulerJob(e){if(n(this,H)[k.SchedulerDefinition.fullName]||this.use(k.SchedulerDefinition),n(this,Vt).has(e.name))throw new Error(`Job ${e.name} is already defined`);n(this,Vt).set(e.name,e.onRun)}static addSettings(e){let t=Array.isArray(e)?e:[e],r=t.filter(o=>o.type==="group"||!o.scope||o.scope==="installation"),s=t.filter(o=>o.type!=="group"&&o.scope==="app");r.length>0&&(n(this,ct)??a(this,ct,[]),n(this,ct).push(...r)),s.length>0&&(n(this,lt)??a(this,lt,[]),n(this,lt).push(...s)),Tt([...n(this,ct)??[],...n(this,lt)??[]]),n(this,H)[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,mt).has(e.event)?n(this,mt).get(e.event)?.push(e.onEvent):n(this,mt).set(e.event,[e.onEvent]),B}static provide(e){n(this,en).push(e)}static use(e,t){n(this,Wt)[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,Wt)[e.fullName].handler?.[s.name]?.(s.requestType?.fromPartial(o??{}),d);return n(this,H)[e.fullName]=r,r}static get redditAPIPlugins(){if(!Se(n(this,ut).redditAPI))throw new Error("Reddit API is not enabled. You can enable it by passing `redditAPI: true` to `Devvit.configure`.");return{Flair:n(this,H)[k.FlairDefinition.fullName],GraphQL:n(this,H)[k.GraphQLDefinition.fullName],LinksAndComments:n(this,H)[k.LinksAndCommentsDefinition.fullName],Listings:n(this,H)[k.ListingsDefinition.fullName],Moderation:n(this,H)[k.ModerationDefinition.fullName],ModNote:n(this,H)[k.ModNoteDefinition.fullName],NewModmail:n(this,H)[k.NewModmailDefinition.fullName],PrivateMessages:n(this,H)[k.PrivateMessagesDefinition.fullName],Subreddits:n(this,H)[k.SubredditsDefinition.fullName],Users:n(this,H)[k.UsersDefinition.fullName],Widgets:n(this,H)[k.WidgetsDefinition.fullName],Wiki:n(this,H)[k.WikiDefinition.fullName]}}static get modLogPlugin(){let e=n(this,H)[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,H)[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,H)[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,H)[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,H)[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,H)[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,H)[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 userActionsPlugin(){if(!(Se(n(this,ut).userActions)&&Se(n(this,ut).redditAPI)))throw new Error("UserActions is not enabled. You can enable it by passing both `userActions: true` and `redditAPI: true` to `Devvit.configure`");return n(this,H)[k.UserActionsDefinition.fullName]}static get menuItems(){return n(this,Bi)}static get customPostType(){return n(this,Ht)}static get formDefinitions(){return n(this,jt)}static get scheduledJobHandlers(){return n(this,Vt)}static get installationSettings(){return n(this,ct)}static get appSettings(){return n(this,lt)}static get triggerOnEventHandlers(){return n(this,mt)}static get assets(){return n(this,Qr)}static get webViewAssets(){return n(this,Yr)}constructor(e){super(e),a(B,Qr,e.assets??{}),a(B,Yr,e.webviewAssets??{});for(let t in n(B,Wt)){let r=n(B,Wt)[t];r.handler=e.use(r.def,r.options)}n(B,Bi).length>0&&yl(e),n(B,Vt).size>0&&bl(e),n(B,Ht)&&(cl(e),cu(e)),(n(B,Ht)||n(B,jt).size>0)&&Nl(e),n(B,ct)&&ml(e),n(B,lt)&&zd(e),n(B,mt).size>0&&vl(e);for(let t of n(B,en))e.provides(t)}};lt=new WeakMap,Qr=new WeakMap,ut=new WeakMap,Ht=new WeakMap,jt=new WeakMap,ct=new WeakMap,Bi=new WeakMap,Vt=new WeakMap,mt=new WeakMap,Yr=new WeakMap,en=new WeakMap,Wt=new WeakMap,H=new WeakMap,B.debug={},l(B,lt),l(B,Qr,{}),l(B,ut,{}),l(B,Ht),l(B,jt,new Map),l(B,ct),l(B,Bi,[]),l(B,Vt,new Map),l(B,mt,new Map),l(B,Yr,{}),l(B,en,[]),l(B,Wt,{}),l(B,H,{});var u=B;(e=>{function i(t,r,...s){return{type:t,props:r,children:s}}e.createElement=i})(u||(u={}));function Z(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 Ha;(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"})(Ha||(Ha={}));var mu="text",pu="raw",gu="br",hu="link",fu="c/",yu="p/",bu="r/",vu="u/",ku="@",Cu="spoilertext",Pu="par",Su="h",wu="hr",Fu="blockquote",xu="code",Au="li",Iu="list",Eu="L",Tu="R",Ru="C",Ou="table",Mu="embed",Uu="img",Bu="gif",Du="video";function Nu(i){return{e:Bu,id:i.mediaId,...i.caption&&{c:i.caption},...i.blur&&{o:i.blur}}}function Lu(i,e){let t={},r=[];return Object.assign(t,tn(t,r),rn(t,r),nn(t,r),an(t,r),dn(t,r),ln(t,r)),e(t),{e:Fu,c:r,...i.author&&{a:i.author}}}function _u(i,e){let t={},r=[];return Object.assign(t,Va(t,r)),e(t),{e:xu,c:r,...i.language&&{l:i.language}}}function Hu(i){return{e:fu,t:i.permalink}}function ju(i,e){let t={},r=[];return Object.assign(t,Va(t,r),on(t,r)),e(t),{e:Su,l:i.level,c:r}}function Vu(i){return{e:Mu,u:i.sourceUrl,c:i.contentUrl,x:i.width,y:i.height}}function Wu(){return{e:wu}}function Gu(i){return{e:Uu,id:i.mediaId,...i.caption&&{c:i.caption},...i.blur&&{o:i.blur}}}function Ju(){return{e:gu}}function zu(i){return{e:hu,t:i.text,u:i.url,...i.formatting&&{f:i.formatting},...i.tooltip&&{a:i.tooltip}}}function qu(i,e){let t={},r=[];return Object.assign(t,lc(t,r)),e(t),{e:Iu,o:i.ordered,c:r}}function $u(i){let e={},t=[];return Object.assign(e,tn(e,t),rn(e,t),nn(e,t),yo(e,t),an(e,t),dn(e,t),ln(e,t)),i(e),{e:Au,c:t}}function Ku(i){let e={},t=[];return Object.assign(e,bo(e,t),on(e,t),ja(e,t),Wa(e,t),sn(e,t)),i(e),{e:Pu,c:t}}function Zu(i){return{e:yu,t:i.permalink}}function Xu(i){return{e:pu,t:i}}function Qu(i){let e={},t=[];return Object.assign(e,bo(e,t),on(e,t),ja(e,t)),i(e),{e:Cu,c:t}}function Yu(i){return{e:bu,t:i.subredditName,l:i.showPrefix}}function ec(i){let e={},t=[],r=[];return Object.assign(e,uc(e,t,r)),i(e),{e:Ou,h:t,c:r}}function tc(i){let[e,t]=dc();return i(e),{c:t}}function ic(i,e){let[t,r]=dc();e(t);let s;switch(i.columnAlignment){case"left":s=Eu;break;case"right":s=Tu;break;case"center":s=Ru;break}return{...s&&{a:s},...r&&{c:r}}}function rc(i){let e={},t=[];return Object.assign(e,cc(e,t)),i(e),t}function nc(i){return{e:mu,t:i.text,...i.formatting&&{f:i.formatting}}}function sc(i){return{e:vu,t:i.username,l:i.showPrefix}}function oc(i){return{e:ku,t:i.username,l:i.showPrefix}}function ac(i){return{e:Du,id:i.mediaId,...i.caption&&{c:i.caption},...i.blur&&{o:i.blur},...i.thumbnail&&{p:i.thumbnail},...i.convertToGif&&{gifify:i.convertToGif}}}function dc(){let i={},e=[];return Object.assign(i,bo(i,e),on(i,e),Wa(i,e),sn(i,e)),[i,e]}function tn(i,e){return{blockQuote(t,r){return e.push(Lu(t,r)),i}}}function rn(i,e){return{codeBlock(t,r){return e.push(_u(t,r)),i}}}function mc(i,e){return{embed(t){return e.push(Vu(t)),i}}}function nn(i,e){return{heading(t,r){return e.push(ju(t,r)),i}}}function yo(i,e){return{horizontalRule(){return e.push(Wu()),i}}}function sn(i,e){return{image(t){return e.push(Gu(t)),i},animatedImage(t){return e.push(Nu(t)),i}}}function ja(i,e){return{linebreak(){return e.push(Ju()),i}}}function on(i,e){return{link(t){return e.push(zu(t)),i},commentLink(t){return e.push(Hu(t)),i},postLink(t){return e.push(Zu(t)),i},subredditLink(t){return e.push(Yu(t)),i},userLink(t){return e.push(sc(t)),i},userMention(t){return e.push(oc(t)),i}}}function an(i,e){return{list(t,r){return e.push(qu(t,r)),i}}}function lc(i,e){return{item(t){return e.push($u(t)),i}}}function dn(i,e){return{paragraph(t){return e.push(Ku(t)),i}}}function Va(i,e){return{rawText(t){return e.push(Xu(t)),i}}}function Wa(i,e){return{spoiler(t){return e.push(Qu(t)),i}}}function uc(i,e,t){return{headerCell(r,s){return e.push(ic(r,s)),i},row(r){return t.push(rc(r)),i}}}function ln(i,e){return{table(t){return e.push(ec(t)),i}}}function cc(i,e){return{cell(t){return e.push(tc(t)),i}}}function bo(i,e){return{text(t){return e.push(nc(t)),i}}}function pc(i,e){return{video(t){return e.push(ac(t)),i}}}var Gp=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},Jp=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)},vo,Gt=class{constructor(){vo.set(this,void 0);let e=[];Object.assign(this,dn(this,e),nn(this,e),yo(this,e),tn(this,e),rn(this,e),mc(this,e),an(this,e),ln(this,e),sn(this,e),pc(this,e)),Gp(this,vo,{document:e},"f")}build(){return JSON.stringify(Jp(this,vo,"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}};vo=new WeakMap;function Di(i){let e;return i instanceof Gt?e=i.build():typeof i=="object"?e=JSON.stringify(i):e=i,e}var gc=100,hc=1/0,Jt,zt,pt,Ni,Li,ko,W=class{constructor(e){l(this,Li);l(this,Jt);l(this,zt);l(this,pt);l(this,Ni,!1);this.pageSize=gc;this.limit=hc;this.children=[];Z(this),this._fetch=e.fetch,this.pageSize=e.pageSize??gc,this.limit=e.limit??hc,a(this,zt,e.after),a(this,Jt,e.before),a(this,pt,e.more),e.children&&(this.children=e.children)}get hasMore(){return!n(this,Ni)||!!(n(this,zt)||n(this,Jt)||n(this,pt))}async*[Symbol.asyncIterator](){let e=0;for(;;){if(e===this.children.length)if(this.hasMore){if((await h(this,Li,ko).call(this)).length===0)break}else break;if(yield this.children[e],e++,e===this.limit)break}}setMore(e){a(this,pt,e)}preventInitialFetch(){a(this,Ni,!0)}async all(){for(;this.hasMore&&this.children.length<this.limit;)await h(this,Li,ko).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,Li,ko).call(this);return this.children.slice(0,t)}};Jt=new WeakMap,zt=new WeakMap,pt=new WeakMap,Ni=new WeakMap,Li=new WeakSet,ko=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,Jt),after:n(this,zt),limit:this.pageSize,more:n(this,pt)});return this.children.push(...e),a(this,Jt,t),a(this,zt,r),a(this,pt,s),a(this,Ni,!0),e};var un,Ga,ke=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,un,Ga).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,un,Ga).call(this,s.created)}static async addRemovalNote(e,t){await u.redditAPIPlugins.ModNote.PostRemovalNote(e,t)}};un=new WeakSet,Ga=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:K(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?ye(e.userNoteData?.redditId):void 0,label:e.userNoteData?.label},type:e.type}},l(ke,un);var Y=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 fc=["all","wiki","posts","access","mail","config","flair","channels","chat_config","chat_operator","community_chat"];function zp(i,e){return e.map(t=>(i.includes(t)?"+":"-")+t).join(",")}function Ja(i){return zp(i,fc)}function yc(i){return i.filter(e=>fc.includes(e))}import"@devvit/protos";var qp=(t=>(t.User="USER_FLAIR",t.Post="LINK_FLAIR",t))(qp||{}),qt,_i,Hi,ji,Vi,Wi,Gi,Ji,zi,qi,$i,Co,Ie=class Ie{constructor(e,t,r){l(this,qt);l(this,_i);l(this,Hi);l(this,ji);l(this,Vi);l(this,Wi);l(this,Gi);l(this,Ji);l(this,zi);l(this,qi);Z(this),p(e.id),p(e.text),a(this,qt,e.id),a(this,_i,t),a(this,Hi,e.text),a(this,ji,$p(e.textColor)),a(this,Vi,Kp(e.backgroundColor)),a(this,Wi,Zp(e.allowableContent)),a(this,Gi,e.modOnly),a(this,Ji,e.maxEmojis),a(this,zi,e.textEditable),a(this,qi,r)}get id(){return n(this,qt)}get text(){return n(this,Hi)}get textColor(){return n(this,ji)}get backgroundColor(){return n(this,Vi)}get allowableContent(){return n(this,Wi)}get modOnly(){return n(this,Gi)}get maxEmojis(){return n(this,Ji)}get allowUserEdits(){return n(this,zi)}async delete(){return Ie.deleteFlairTemplate(n(this,qt),n(this,_i),n(this,qi))}async edit(e){return Ie.editFlairTemplate({id:n(this,qt),subredditName:n(this,_i),text:e.text??n(this,Hi),allowableContent:e.allowableContent??n(this,Wi),backgroundColor:e.backgroundColor??n(this,Vi),maxEmojis:e.maxEmojis??n(this,Ji),modOnly:e.modOnly??n(this,Gi),textColor:e.textColor??n(this,ji),allowUserEdits:e.allowUserEdits??n(this,zi)},n(this,qi))}static async createPostFlairTemplate(e,t){var r;return h(r=Ie,$i,Co).call(r,{...e,flairType:"LINK_FLAIR"},t)}static async createUserFlairTemplate(e,t){var r;return h(r=Ie,$i,Co).call(r,{...e,flairType:"USER_FLAIR"},t)}static async editFlairTemplate(e,t){var r;return h(r=Ie,$i,Co).call(r,e,t)}static async getPostFlairTemplates(e,t){return(await u.redditAPIPlugins.Flair.LinkFlair({subreddit:e},t)).flair?.map(o=>new Ie(o,e,t))||[]}static async getUserFlairTemplates(e,t){return(await u.redditAPIPlugins.Flair.UserFlair({subreddit:e},t)).flair?.map(o=>new Ie(o,e,t))||[]}static async deleteFlairTemplate(e,t,r){await u.redditAPIPlugins.Flair.DeleteFlairTemplate({subreddit:e,flairTemplateId:t},r)}};qt=new WeakMap,_i=new WeakMap,Hi=new WeakMap,ji=new WeakMap,Vi=new WeakMap,Wi=new WeakMap,Gi=new WeakMap,Ji=new WeakMap,zi=new WeakMap,qi=new WeakMap,$i=new WeakSet,Co=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:P=""}=e;if(m&&f)throw new Error("Cannot have a mod only flair that is editable by users");let L=await u.redditAPIPlugins.Flair.FlairTemplate({subreddit:r,allowableContent:s,backgroundColor:o,flairType:d,maxEmojis:c,modOnly:m,text:y,textColor:v,textEditable:f,flairTemplateId:P,cssClass:"",overrideCss:!1},t);return new Ie(L,r,t)},l(Ie,$i);var ne=Ie;function cn(i){return{flairCssClass:i.flairCssClass,user:i.user,flairText:i.flairText}}var Ue,za,bc,qa,gt=class gt{static async getUserFlairBySubreddit(e,t){return u.redditAPIPlugins.Flair.FlairList(e,t)}static setUserFlair(e,t){var r;return h(r=gt,Ue,za).call(r,e,t)}static setUserFlairBatch(e,t,r){var s;return h(s=gt,Ue,bc).call(s,e,t,r)}static setPostFlair(e,t){var r;return h(r=gt,Ue,za).call(r,{...e,postId:de(e.postId)},t)}static async removePostFlair(e,t,r){var s;return h(s=gt,Ue,qa).call(s,e,t,void 0,r)}static async removeUserFlair(e,t,r){var s;return h(s=gt,Ue,qa).call(s,e,void 0,t,r)}};Ue=new WeakSet,za=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)},bc=async function(e,t,r){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(y=>{for(let v in y)if(y[v]?.includes(o))throw new Error(`Unexpected input: ${v} cannot contain the "," character`);return[y.username,y.text||"",y.cssClass||""].join(o)}).join(`
|
|
4
|
-
`);return(await u.redditAPIPlugins.Flair.FlairCsv({subreddit:e,flairCsv:d},r)).result},qa=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(gt,Ue);var ce=gt;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 Kp(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 Zp(i){if(i==="all"||i==="text"||i==="emoji")return i;throw new Error(`Invalid allowable content: ${i}`)}import{Block as Pc,UIResponse as sg}from"@devvit/protos";var Za=ad(Cc(),1);var Ka=i=>"text"in i?i.text:ng(i.richtext),ng=i=>i instanceof Gt?i.build():typeof i=="object"?JSON.stringify(i):i;var og={NONE:0,BLOCKS:1,UNRECOGNIZED:-1},fC={UNKNOWN:0,VALID:1,FAILED:2},Ki,pn,Kt,gn,Zi,hn,fn,yn,Zt,bn,vn,kn,Cn,Pn,Sn,ht,wn,Fn,Xt,Xi,ft,Qi,Yi,er,yt,bt,vt,tr,kt,Ct,Pt,Ve,xn,An,ir,rr,nr,M,D=class D{constructor(e,t){l(this,Ki);l(this,pn);l(this,Kt);l(this,gn);l(this,Zi);l(this,hn);l(this,fn);l(this,yn);l(this,Zt);l(this,bn);l(this,vn);l(this,kn);l(this,Cn);l(this,Pn);l(this,Sn);l(this,ht);l(this,wn);l(this,Fn);l(this,Xt);l(this,Xi);l(this,ft);l(this,Qi);l(this,Yi);l(this,er);l(this,yt);l(this,bt);l(this,vt);l(this,tr);l(this,kt);l(this,Ct);l(this,Pt);l(this,Ve);l(this,xn);l(this,An);l(this,ir);l(this,rr);l(this,nr);l(this,M);Z(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,Ki,de(`t3_${e.id}`)),a(this,Kt,e.author),a(this,pn,e.authorFullname?te(e.authorFullname):void 0),a(this,Zi,K(e.subredditId)),a(this,hn,e.subreddit),a(this,kn,e.score??0),a(this,Cn,e.numComments??0),a(this,Pn,e.numReports??0);let r=new Date(0);r.setUTCSeconds(e.createdUtc),a(this,gn,r),a(this,yn,e.title),a(this,Zt,e.selftext),a(this,bn,e.selftextHtml),a(this,vn,e.url),a(this,fn,e.permalink),e.thumbnail&&e.thumbnail!=="self"&&e.thumbnail!=="nsfw"&&e.thumbnailHeight!=null&&e.thumbnailWidth!=null&&a(this,Sn,{url:e.thumbnail,height:e.thumbnailHeight,width:e.thumbnailWidth}),a(this,ht,e.approved??!1),a(this,wn,e.approvedAtUtc??0),a(this,Fn,e.bannedAtUtc??0),a(this,ft,e.removed??!1),a(this,Qi,e.removedBy),a(this,Yi,e.removedByCategory),a(this,Xt,e.spam??!1),a(this,Xi,e.stickied??!1),a(this,er,e.archived??!1),a(this,yt,e.edited??!1),a(this,bt,e.locked??!1),a(this,vt,e.over18??!1),a(this,tr,e.quarantine??!1),a(this,kt,e.spoiler),a(this,Ct,e.hidden??!1),a(this,Pt,e.ignoreReports??!1),a(this,Ve,e.distinguished),a(this,An,e.secureMedia),a(this,ir,(e.modReports??[]).map(([s])=>s)),a(this,rr,(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,xn,{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}),e.gallery?a(this,nr,e.gallery.map(s=>({status:s.status,url:s.url,height:s.height,width:s.width}))):a(this,nr,[])}get id(){return n(this,Ki)}get authorId(){return n(this,pn)}get authorName(){return n(this,Kt)}get subredditId(){return n(this,Zi)}get subredditName(){return n(this,hn)}get permalink(){return n(this,fn)}get title(){return n(this,yn)}get body(){return n(this,Zt)}get bodyHtml(){return n(this,bn)}get url(){return n(this,vn)}get thumbnail(){return n(this,Sn)}get createdAt(){return n(this,gn)}get score(){return n(this,kn)}get numberOfComments(){return n(this,Cn)}get numberOfReports(){return n(this,Pn)}get approved(){return n(this,ht)}get approvedAtUtc(){return n(this,wn)}get bannedAtUtc(){return n(this,Fn)}get spam(){return n(this,Xt)}get stickied(){return n(this,Xi)}get removed(){return n(this,ft)}get removedBy(){return n(this,Qi)}get removedByCategory(){return n(this,Yi)}get archived(){return n(this,er)}get edited(){return n(this,yt)}get locked(){return n(this,bt)}get nsfw(){return n(this,vt)}get quarantined(){return n(this,tr)}get spoiler(){return n(this,kt)}get hidden(){return n(this,Ct)}get ignoringReports(){return n(this,Pt)}get distinguishedBy(){return n(this,Ve)}get comments(){return Q.getComments({postId:this.id},n(this,M))}get flair(){return n(this,xn)}get secureMedia(){return n(this,An)}get userReportReasons(){return n(this,rr)}get modReportReasons(){return n(this,ir)}get gallery(){return n(this,nr)}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,Qi),removedByCategory:n(this,Yi),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,ir),userReportReasons:n(this,rr)}}isApproved(){return n(this,ht)}isSpam(){return n(this,Xt)}isStickied(){return n(this,Xi)}isRemoved(){return n(this,ft)}isArchived(){return n(this,er)}isEdited(){return n(this,yt)}isLocked(){return n(this,bt)}isNsfw(){return n(this,vt)}isQuarantined(){return n(this,tr)}isSpoiler(){return n(this,kt)}isHidden(){return n(this,Ct)}isIgnoringReports(){return n(this,Pt)}isDistinguishedBy(){return n(this,Ve)}async edit(e){let t=await D.edit({id:this.id,...e},n(this,M));a(this,Zt,t.body),a(this,yt,t.edited)}async setSuggestedCommentSort(e){await D.setSuggestedCommentSort({id:this.id,subredditId:n(this,Zi),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,Zt,t.body),a(this,yt,t.edited)}async addComment(e){return Q.submit({id:this.id,...e},n(this,M))}async delete(){p(n(this,M));let e=n(this,M)?.[S.App]?.values[0];if(e!==n(this,Kt))throw new Error(`App '${e}' is not the author of Post ${this.id}, delete not allowed.`);return D.delete(this.id,n(this,M))}async approve(){await D.approve(this.id,n(this,M)),a(this,ht,!0),a(this,ft,!1)}async remove(e=!1){await D.remove(this.id,e,n(this,M)),a(this,ft,!0),a(this,Xt,e),a(this,ht,!1)}async lock(){await D.lock(this.id,n(this,M)),a(this,bt,!0)}async unlock(){await D.unlock(this.id,n(this,M)),a(this,bt,!1)}async hide(){await D.hide(this.id,n(this,M)),a(this,Ct,!0)}async unhide(){await D.unhide(this.id,n(this,M)),a(this,Ct,!1)}async markAsNsfw(){await D.markAsNsfw(this.id,n(this,M)),a(this,vt,!0)}async unmarkAsNsfw(){await D.unmarkAsNsfw(this.id,n(this,M)),a(this,vt,!1)}async markAsSpoiler(){await D.markAsSpoiler(this.id,n(this,M)),a(this,kt,!0)}async unmarkAsSpoiler(){await D.unmarkAsSpoiler(this.id,n(this,M)),a(this,kt,!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,Ve,e)}async distinguishAsAdmin(){let{distinguishedBy:e}=await D.distinguish(this.id,!0,n(this,M));a(this,Ve,e)}async undistinguish(){let{distinguishedBy:e}=await D.undistinguish(this.id,n(this,M));a(this,Ve,e)}async ignoreReports(){await D.ignoreReports(this.id,n(this,M)),a(this,Pt,!0)}async unignoreReports(){await D.unignoreReports(this.id,n(this,M)),a(this,Pt,!1)}async getAuthor(){return C.getByUsername(n(this,Kt),n(this,M))}async crosspost(e){return D.crosspost({...e,postId:this.id},n(this,M))}addRemovalNote(e){return ke.addRemovalNote({itemIds:[n(this,Ki)],...e},n(this,M))}async getEnrichedThumbnail(){return ag({id:this.id},n(this,M))}static async getById(e,t){let r=u.redditAPIPlugins.LinksAndComments,s=Et(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{runAs:r="APP"}=e,s=fe[r],o=s===fe.USER?u.userActionsPlugin:u.redditAPIPlugins.LinksAndComments,d;if("preview"in e){p(t,"Missing metadata in `SubmitPostOptions`"),s===fe.USER&&p(e.userGeneratedContent,"userGeneratedContent must be set in `SubmitPostOptions` when RunAs=USER for experience posts");let y=await new _e(()=>e.preview,void 0,{},t,void 0).buildBlocksUI(),v=Pc.encode(y).finish(),{textFallback:f,...P}=e,b=f?Ka(f):"",L=e.userGeneratedContent?{text:e.userGeneratedContent.text??"",imageUrls:e.userGeneratedContent.imageUrls??[]}:void 0,A={kind:"custom",sr:e.subredditName,richtextJson:(0,Za.fromByteArray)(v),richtextFallback:b,...P,userGeneratedContent:L,runAs:s};d=await o.SubmitCustomPost(A,t)}else d=await o.Submit({kind:"kind"in e?e.kind:"url"in e?"link":"self",sr:e.subredditName,richtextJson:"richtext"in e?Di(e.richtext):void 0,...e,runAs:s},t);if("kind"in e&&["image","video","videogif"].includes(e.kind)&&!d.json?.data?.id){if(e.kind==="image"&&"imageUrls"in e)throw new Error(`Image post type with ${e.imageUrls} is being created asynchronously and should be updated in the subreddit soon.`);if("videoPosterUrl"in e)throw new Error(`Post of ${e.kind} type with ${e.videoPosterUrl} is being created asynchronously and should be updated in the subreddit soon.`)}if(!d.json?.data?.id||d.json?.errors?.length)throw new Error(`failed to submit post - either post ID is empty or request failed with errors: ${d.json?.errors}`);return D.getById(`t3_${d.json.data.id}`,t)}static async crosspost(e,t){let{runAs:r="APP"}=e,s=fe[r],o=s===fe.USER?u.userActionsPlugin:u.redditAPIPlugins.LinksAndComments,{postId:d,subredditName:c,...m}=e,y=await o.Submit({kind:"crosspost",sr:c,crosspostFullname:de(d),...m,runAs:s},t);if(!y.json?.data?.id||y.json?.errors?.length)throw new Error("failed to crosspost post");return D.getById(`t3_${y.json.data.id}`,t)}static async edit(e,t){let r=u.redditAPIPlugins.LinksAndComments,{id:s}=e,o;if("richtext"in e&&(o=Di(e.richtext)),(await r.EditUserText({thingId:s,text:"text"in e?e.text:"",richtextJson:o,runAs:fe.APP},t)).json?.errors?.length)throw new Error("Failed to edit post");return D.getById(s,t)}static async setSuggestedCommentSort(e,t){if(!(await Y.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 _t(e.ui),d=sg.fromJSON(await s.handle({events:[]},t)).blocks,c=(0,Za.fromByteArray)(Pc.encode(d).finish());await r.SetCustomPostPreview({thingId:e.id,bodyType:og.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=Ka(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 mn(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 mn(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 mn(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 mn(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 mn(o,t)}})}};Ki=new WeakMap,pn=new WeakMap,Kt=new WeakMap,gn=new WeakMap,Zi=new WeakMap,hn=new WeakMap,fn=new WeakMap,yn=new WeakMap,Zt=new WeakMap,bn=new WeakMap,vn=new WeakMap,kn=new WeakMap,Cn=new WeakMap,Pn=new WeakMap,Sn=new WeakMap,ht=new WeakMap,wn=new WeakMap,Fn=new WeakMap,Xt=new WeakMap,Xi=new WeakMap,ft=new WeakMap,Qi=new WeakMap,Yi=new WeakMap,er=new WeakMap,yt=new WeakMap,bt=new WeakMap,vt=new WeakMap,tr=new WeakMap,kt=new WeakMap,Ct=new WeakMap,Pt=new WeakMap,Ve=new WeakMap,xn=new WeakMap,An=new WeakMap,ir=new WeakMap,rr=new WeakMap,nr=new WeakMap,M=new WeakMap;var G=D;function mn(i,e){if(!i.data?.children)throw new Error("Listing response is missing children");return{children:i.data.children.map(r=>new G(r.data,e)),before:i.data.before,after:i.data.after}}async function ag(i,e){let o=(await Y.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 dg=(_=>(_.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",_))(dg||{}),In,sr,En,Tn,Rn,On,Mn,St,Un,Bn,Dn,De,Qt=class Qt{constructor(e,t){l(this,In);l(this,sr);l(this,En);l(this,Tn);l(this,Rn);l(this,On);l(this,Mn);l(this,St,new Map);l(this,Un);l(this,Bn);l(this,Dn);l(this,De);Z(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,In,te(Ls(e.id)?e.id:`t2_${e.id}`)),a(this,sr,e.name),a(this,On,e.over18??!1),a(this,Mn,e.isEmployee??!1);let r=new Date(0);if(r.setUTCSeconds(e.createdUtc),a(this,En,r),a(this,Tn,e.linkKarma??0),a(this,Rn,e.commentKarma??0),e.modPermissions)for(let[s,o]of Object.entries(e.modPermissions))n(this,St).set(s,yc(o));a(this,Un,new URL(e.subreddit?.url??"","https://www.reddit.com").toString()),a(this,Bn,e.subreddit?.url??""),a(this,Dn,e.hasVerifiedEmail??!1),a(this,De,t)}get id(){return n(this,In)}get username(){return n(this,sr)}get createdAt(){return n(this,En)}get linkKarma(){return n(this,Tn)}get commentKarma(){return n(this,Rn)}get nsfw(){return n(this,On)}get isAdmin(){return n(this,Mn)}get modPermissions(){return n(this,St)}get url(){return n(this,Un)}get permalink(){return n(this,Bn)}get hasVerifiedEmail(){return n(this,Dn)}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,St).has(e))return n(this,St).get(e);let t=await Qt.getSubredditUsersByType({subredditName:e,type:"moderators",username:this.username},n(this,De)).all();if(t.length===0)return[];let r=t[0].modPermissions.get(e)??[];return r.length>0&&n(this,St).set(e,r),r}getComments(e){return Q.getCommentsByUser({username:this.username,...e},n(this,De))}getPosts(e){return G.getPostsByUser({username:this.username,...e},n(this,De))}async getUserFlairBySubreddit(e){let t=await ce.getUserFlairBySubreddit({subreddit:e,name:n(this,sr)},n(this,De));return t.users[0]?cn(t.users[0]):void 0}getSnoovatarUrl(){return Qt.getSnoovatarUrl(this.username,n(this,De))}async getSocialLinks(){let r=await Y.query("GetUserSocialLinks","2aca18ef5f4fc75fb91cdaace3e9aeeae2cb3843b5c26ad511e6f01b8521593a",{name:this.username},n(this,De));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 Sc(e,t);return r==null?void 0:Qt.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 Qt(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?Qt.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 ug(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?Ja(c):void 0,...m},t);if(y.json?.errors?.length)throw new Error(y.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,
|
|
6
|
-
`))}static async getSnoovatarUrl(e,t){return(await Y.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 lg(o,t)}})}};In=new WeakMap,sr=new WeakMap,En=new WeakMap,Tn=new WeakMap,Rn=new WeakMap,On=new WeakMap,Mn=new WeakMap,St=new WeakMap,Un=new WeakMap,Bn=new WeakMap,Dn=new WeakMap,De=new WeakMap;var C=Qt;function lg(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 G(r.data,e);if(r.kind==="t1")return new Q(r.data,e);throw new Error(`Type ${r.kind} is not supported`)}),before:i.data.before,after:i.data.after}}async function ug(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 P=m[f];return p(P,"User data is missing from response"),new C({id:f,name:P.name,linkKarma:P.linkKarma,commentKarma:P.commentKarma,createdUtc:P.createdUtc,over18:P.profileOver18,snoovatarSize:[],modPermissions:{[e]:v.data?.modPermissions??[]}},t)}),before:i.data.before,after:i.data.after}}async function Sc(i,e){return(await u.redditAPIPlugins.Users.UserDataByAccountIds({ids:i},e))?.users?.[i]?.name}async function Md(i){p(i);let e=i?.[S.Username]?.values[0];if(e)return e;let t=i?.[S.User]?.values[0];if(t)return Sc(t,i)}var Yt,Nn,or,ar,Ln,_n,dr,Hn,jn,lr,wt,Vn,Wn,ei,Ft,xt,We,ti,Ge,Gn,Jn,zn,qn,$n,Kn,Zn,At,X,Ne,So,wo,j=class j{constructor(e,t){l(this,Yt);l(this,Nn);l(this,or);l(this,ar);l(this,Ln);l(this,_n);l(this,dr);l(this,Hn);l(this,jn);l(this,lr);l(this,wt);l(this,Vn);l(this,Wn);l(this,ei);l(this,Ft);l(this,xt);l(this,We);l(this,ti);l(this,Ge);l(this,Gn);l(this,Jn);l(this,zn);l(this,qn);l(this,$n);l(this,Kn);l(this,Zn);l(this,At);l(this,X);var s;Z(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,Yt,si(`t1_${e.id}`)),a(this,Nn,e.authorFullname?te(e.authorFullname):void 0),a(this,or,e.author),a(this,ar,e.body),a(this,Hn,K(e.subredditId)),a(this,jn,e.subreddit),a(this,_n,jo(e.parentId)?si(e.parentId):de(e.parentId)),a(this,dr,de(e.linkId)),a(this,ei,e.edited??!1),a(this,Ft,e.locked??!1),a(this,xt,e.removed??!1),a(this,We,e.stickied??!1),a(this,wt,e.approved??!1),a(this,Vn,e.approvedAtUtc??0),a(this,Wn,e.bannedAtUtc??0),a(this,ti,e.spam??!1),a(this,Ge,e.distinguished),a(this,Gn,e.numReports??0),a(this,Jn,e.collapsedBecauseCrowdControl??!1),a(this,zn,e.score??0),a(this,qn,e.permalink),a(this,Zn,new URL(e.permalink??"","https://www.reddit.com/").toString()),a(this,At,e.ignoreReports??!1),a(this,$n,(e.modReports??[]).map(([o])=>o)),a(this,Kn,(e.userReports??[]).map(([o])=>o));let r=new Date(0);r.setUTCSeconds(e.createdUtc),a(this,Ln,r),a(this,lr,h(s=j,Ne,So).call(s,{postId:n(this,dr),commentId:n(this,Yt)},t)),a(this,X,t)}get id(){return n(this,Yt)}get authorId(){return n(this,Nn)}get authorName(){return n(this,or)}get subredditId(){return n(this,Hn)}get subredditName(){return n(this,jn)}get body(){return n(this,ar)}get createdAt(){return n(this,Ln)}get parentId(){return n(this,_n)}get postId(){return n(this,dr)}get replies(){return n(this,lr)}get distinguishedBy(){return n(this,Ge)}get locked(){return n(this,Ft)}get stickied(){return n(this,We)}get removed(){return n(this,xt)}get approved(){return n(this,wt)}get approvedAtUtc(){return n(this,Vn)}get bannedAtUtc(){return n(this,Wn)}get spam(){return n(this,ti)}get edited(){return n(this,ei)}get numReports(){return n(this,Gn)}get collapsedBecauseCrowdControl(){return n(this,Jn)}get score(){return n(this,zn)}get permalink(){return n(this,qn)}get userReportReasons(){return n(this,Kn)}get modReportReasons(){return n(this,$n)}get url(){return n(this,Zn)}get ignoringReports(){return n(this,At)}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,Ft)}isApproved(){return n(this,wt)}isRemoved(){return n(this,xt)}isSpam(){return n(this,ti)}isStickied(){return n(this,We)}isDistinguished(){return!!n(this,Ge)}isEdited(){return n(this,ei)}isIgnoringReports(){return n(this,At)}async delete(){return j.delete(this.id,n(this,X))}async edit(e){let t=await j.edit({id:this.id,...e},n(this,X));return a(this,ar,t.body),a(this,ei,t.edited),this}async approve(){await j.approve(this.id,n(this,X)),a(this,wt,!0),a(this,xt,!1)}async remove(e=!1){await j.remove(this.id,e,n(this,X)),a(this,xt,!0),a(this,ti,e),a(this,wt,!1)}async lock(){await j.lock(this.id,n(this,X)),a(this,Ft,!0)}async unlock(){await j.unlock(this.id,n(this,X)),a(this,Ft,!1)}async reply(e){return j.submit({id:this.id,...e},n(this,X))}async getAuthor(){return C.getByUsername(n(this,or),n(this,X))}async distinguish(e=!1){let{distinguishedBy:t,stickied:r}=await j.distinguish(this.id,e,!1,n(this,X));a(this,Ge,t),a(this,We,r)}async distinguishAsAdmin(e=!1){let{distinguishedBy:t,stickied:r}=await j.distinguish(this.id,e,!0,n(this,X));a(this,Ge,t),a(this,We,r)}async undistinguish(){let{distinguishedBy:e,stickied:t}=await j.undistinguish(this.id,n(this,X));a(this,Ge,e),a(this,We,t)}async ignoreReports(){await j.ignoreReports(this.id,n(this,X)),a(this,At,!0)}async unignoreReports(){await j.unignoreReports(this.id,n(this,X)),a(this,At,!1)}addRemovalNote(e){return ke.addRemovalNote({itemIds:[n(this,Yt)],...e},n(this,X))}static async getById(e,t){let r=u.redditAPIPlugins.LinksAndComments,s=Je(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 j(o.data.children[0].data,t)}static getComments(e,t){var d;let{postId:r,commentId:s,...o}=e;return h(d=j,Ne,So).call(d,{postId:de(r),commentId:s?si(s):void 0,...o},t)}static async edit(e,t){let r=u.redditAPIPlugins.LinksAndComments,{id:s}=e,o;"richtext"in e&&(o=Di(e.richtext));let d=await r.EditUserText({thingId:s,text:"text"in e?e.text:"",richtextJson:o,runAs:fe.APP},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 j(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{runAs:r="APP"}=e,s=fe[r],o=s===fe.USER?u.userActionsPlugin:u.redditAPIPlugins.LinksAndComments,{id:d}=e,c;"richtext"in e&&(c=Di(e.richtext));let m=await o.Comment({thingId:d,text:"text"in e?e.text:"",richtextJson:c,runAs:s},t);if(m.json?.errors?.length)throw new Error("failed to reply to comment");let y=m.json?.data?.things?.[0]?.data;return p(y),new j(y,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 j(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)}};Yt=new WeakMap,Nn=new WeakMap,or=new WeakMap,ar=new WeakMap,Ln=new WeakMap,_n=new WeakMap,dr=new WeakMap,Hn=new WeakMap,jn=new WeakMap,lr=new WeakMap,wt=new WeakMap,Vn=new WeakMap,Wn=new WeakMap,ei=new WeakMap,Ft=new WeakMap,xt=new WeakMap,We=new WeakMap,ti=new WeakMap,Ge=new WeakMap,Gn=new WeakMap,Jn=new WeakMap,zn=new WeakMap,qn=new WeakMap,$n=new WeakMap,Kn=new WeakMap,Zn=new WeakMap,At=new WeakMap,X=new WeakMap,Ne=new WeakSet,So=function(e,t,r=0){return new W({limit:e.limit,pageSize:e.pageSize,fetch:async s=>{var P,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 L=s.more;(!o||o>100)&&(o=100);let A=L.children.splice(0,o),V=await c.MoreChildren({linkId:e.postId,children:A,sort:e.sort},t);if(!V.json?.data?.things?.length)return{children:[]};let{children:U}=h(P=j,Ne,wo).call(P,V.json.data.things,e.postId,e,t);return{children:U,more:L.children.length?L: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=j,Ne,wo).call(b,v,m??e.postId,e,t,r)}})},wo=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 P=f.data.parentId?m[f.data.parentId]:void 0;if(f.kind==="t1"){if(f.data.name===t)continue;let b=new j(f.data,s);if(m[b.id]=b,a(b,lr,h(y=j,Ne,So).call(y,{...r,postId:b.postId,commentId:b.id},s,o)),"replyList"in f.data&&f.data.replyList?.data){let{children:L,more:A}=h(v=j,Ne,wo).call(v,f.data.replyList.data.children,b.id,r,s,o);L.length&&b.replies.children.push(...L),A&&b.replies.setMore(A)}b.replies.preventInitialFetch(),P?P.replies.children.push(b):d.push(b)}else if(f.kind==="more"&&f.data.parentId&&f.data.depth!=null){let b={parentId:jo(f.data.parentId)?si(f.data.parentId):de(f.data.parentId),children:f.data.children??[],depth:f.data.depth};P?P.replies.setMore(b):b.parentId===t&&(c=b)}}return{children:d,more:c}},l(j,Ne);var Q=j;function Vs(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 cg(s)}})}function cg(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:P,targetAuthor:b,targetBody:L,targetFullname:A,targetPermalink:V,targetTitle:U}=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 ri=new Date(0);return ri.setUTCSeconds(d),{id:r,type:y,moderatorName:s,moderatorId:`t2_${o}`,createdAt:ri,subredditName:c,subredditId:`t5_${v}`,description:f,details:P,target:A?{id:A,author:b,body:L,permalink:V,title:U}:void 0}}),after:i.data.after,before:i.data.before}}import"@devvit/protos";var mg=(d=>(d.New="New",d.InProgress="InProgress",d.Archived="Archived",d.Appeals="Appeals",d.JoinRequests="JoinRequests",d.Filtered="Filtered",d))(mg||{}),pg={0:"New",1:"InProgress",2:"Archived",3:"Appeals",4:"JoinRequests",5:"Filtered"},gg=(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))(gg||{}),hg={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,J,re,wc,Fc,Ws=class{constructor(e){l(this,J);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,J,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,J,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,J,re).call(this,{protoConversation:r.conversation,protoMessages:r.messages,protoModActions:r.modActions}),user:r.user}}async createModDiscussionConversation(e){return Xa({subject:e.subject,bodyMarkdown:e.bodyMarkdown,subredditId:K(e.subredditId),isInternal:!0,participantType:"MODERATOR",conversationType:"INTERNAL"},n(this,N))}async createModInboxConversation(e){return Xa({subject:e.subject,bodyMarkdown:e.bodyMarkdown,subredditId:K(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}`),Xa({subject:t,bodyMarkdown:e.bodyMarkdown,subredditId:K(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,J,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,J,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,J,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,J,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,J,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,J,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,J,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,J,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,J,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,J,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,J,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,J=new WeakSet,re=function({protoConversation:e,protoMessages:t,protoModActions:r}){return{...e,state:pg[e.state],messages:h(this,J,wc).call(this,e,t),modActions:h(this,J,Fc).call(this,e,r)}},wc=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},Fc=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:hg[d.actionTypeId]})}return r};async function Xa(i,e){let t=e[S.AppUser]?.values[0],o=await Y.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 ur,cr,Xn,Qn,Yn,es,Qa=class Qa{constructor(e,t){l(this,ur);l(this,cr);l(this,Xn);l(this,Qn);l(this,Yn);l(this,es);if(Z(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,ur,ye(e.name)),e.author!=null)a(this,cr,{type:"user",username:e.author,id:e.authorFullname?te(e.authorFullname):void 0});else if(e.subreddit!=null)a(this,cr,{type:"subreddit",name:e.subreddit,id:e.subredditId?K(e.subredditId):void 0});else throw new Error("PrivateMessage: Invalid data, no author or subreddit");a(this,Xn,e.body??""),a(this,Qn,e.bodyHtml??"");let r=new Date(0);r.setUTCSeconds(e.createdUtc),a(this,Yn,r),a(this,es,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,ur)}get from(){return n(this,cr)}get body(){return n(this,Xn)}get bodyHtml(){return n(this,Qn)}get created(){return n(this,Yn)}async markAsRead(){await u.redditAPIPlugins.PrivateMessages.ReadMessage({id:n(this,ur)},n(this,es))}};ur=new WeakMap,cr=new WeakMap,Xn=new WeakMap,Qn=new WeakMap,Yn=new WeakMap,es=new WeakMap;var Rt=Qa;var Ud=(o=>(o.Reports="reports",o.Spam="spam",o.Modqueue="modqueue",o.Unmoderated="unmoderated",o.Edited="edited",o))(Ud||{}),xc=class{},Ac=class{},Ic=class{},Ec=class{},mr,x,ts,is,rs,ns,ss,os,as,ds,ls,pr,R,Ee=class Ee{constructor(e,t){l(this,mr);l(this,x);l(this,ts);l(this,is);l(this,rs);l(this,ns);l(this,ss);l(this,os);l(this,as);l(this,ds);l(this,ls);l(this,pr);l(this,R);Z(this),p(e.id,"Subreddit id is missing or undefined"),p(e.displayName,"Subreddit name is missing or undefined"),a(this,mr,K(`t5_${e.id}`)),a(this,x,e.displayName),p(e.createdUtc,"Subreddit is missing created date");let r=new Date(0);r.setUTCSeconds(e.createdUtc),a(this,ts,r),a(this,is,fg(e.subredditType)),a(this,rs,e.title),a(this,ns,e.description),p(e.lang,"Subreddit is missing language"),a(this,ss,e.lang),a(this,os,e.subscribers??0),a(this,as,e.activeUserCount??0),a(this,ds,e.over18??!1),a(this,pr,e.url??""),a(this,ls,{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:yg(e.submissionType),allowedMediaInComments:(e.allowedMediaInComments??[]).map(bg),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,pr),"https://www.reddit.com").toString()}),a(this,R,t)}get id(){return n(this,mr)}get name(){return n(this,x)}get createdAt(){return n(this,ts)}get type(){return n(this,is)}get title(){return n(this,rs)}get description(){return n(this,ns)}get language(){return n(this,ss)}get numberOfSubscribers(){return n(this,os)}get numberOfActiveUsers(){return n(this,as)}get nsfw(){return n(this,ds)}get settings(){return n(this,ls)}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,pr)}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,x)};return G.submit(t,n(this,R))}getControversialPosts(e={}){if(!n(this,x))throw new Error("subreddit missing displayName - it might not have been fetched");return G.getControversialPosts({...e,subredditName:n(this,x)},n(this,R))}getTopPosts(e={}){if(!n(this,x))throw new Error("subreddit missing displayName - it might not have been fetched");return G.getTopPosts({...e,subredditName:n(this,x)},n(this,R))}getApprovedUsers(e={}){return C.getSubredditUsersByType({type:"contributors",subredditName:n(this,x),...e},n(this,R))}approveUser(e){return C.createRelationship({username:e,subredditName:n(this,x),type:"contributor"},n(this,R))}removeUser(e){return C.removeRelationship({username:e,subredditName:n(this,x),type:"contributor"},n(this,R))}getWikiContributors(e={}){return C.getSubredditUsersByType({type:"wikicontributors",subredditName:n(this,x),...e},n(this,R))}addWikiContributor(e){return C.createRelationship({username:e,subredditName:n(this,x),type:"wikicontributor"},n(this,R))}removeWikiContributor(e){return C.removeRelationship({username:e,subredditName:n(this,x),type:"wikicontributor"},n(this,R))}getBannedUsers(e={}){return C.getSubredditUsersByType({type:"banned",subredditName:n(this,x),...e},n(this,R))}banUser(e){return C.createRelationship({username:e.username,subredditName:n(this,x),type:"banned",banReason:e.reason,banMessage:e.message,note:e.note,duration:e.duration,banContext:e.context},n(this,R))}unbanUser(e){return C.removeRelationship({username:e,subredditName:n(this,x),type:"banned"},n(this,R))}getBannedWikiContributors(e={}){return C.getSubredditUsersByType({type:"wikibanned",subredditName:n(this,x),...e},n(this,R))}banWikiContributor(e){return C.createRelationship({username:e.username,subredditName:n(this,x),type:"wikibanned",banReason:e.reason,note:e.note,duration:e.duration},n(this,R))}unbanWikiContributor(e){return C.removeRelationship({username:e,subredditName:n(this,x),type:"wikibanned"},n(this,R))}getModerators(e={}){return C.getSubredditUsersByType({type:"moderators",subredditName:n(this,x),...e},n(this,R))}inviteModerator(e,t){return C.createRelationship({type:"moderator_invite",subredditName:n(this,x),username:e,permissions:t??[]},n(this,R))}revokeModeratorInvite(e){return C.removeRelationship({username:e,subredditName:n(this,x),type:"moderator_invite"},n(this,R))}removeModerator(e){return C.removeRelationship({type:"moderator",subredditName:n(this,x),username:e},n(this,R))}setModeratorPermissions(e,t){return C.setModeratorPermissions(e,n(this,x),t,n(this,R))}getMutedUsers(e={}){return C.getSubredditUsersByType({type:"muted",subredditName:n(this,x),...e},n(this,R))}muteUser(e,t){return C.createRelationship({username:e,subredditName:n(this,x),type:"muted",note:t},n(this,R))}unmuteUser(e){return C.removeRelationship({username:e,subredditName:n(this,x),type:"muted"},n(this,R))}getModerationLog(e){return Vs({subredditName:n(this,x),...e},n(this,R))}getUserFlairTemplates(){return ne.getUserFlairTemplates(n(this,x),n(this,R))}getPostFlairTemplates(){return ne.getPostFlairTemplates(n(this,x),n(this,R))}createPostFlairTemplate(e){return ne.createPostFlairTemplate({subredditName:n(this,x),...e},n(this,R))}createUserFlairTemplate(e){return ne.createUserFlairTemplate({subredditName:n(this,x),...e},n(this,R))}async getUserFlair(e){if(e?.usernames!==void 0)return{users:await Promise.all(e.usernames.map(async r=>{let s=await ce.getUserFlairBySubreddit({subreddit:n(this,x),name:r},n(this,R));return cn(s.users[0])}))};{let t=await ce.getUserFlairBySubreddit({...e,subreddit:n(this,x)},n(this,R));return{next:t.next,prev:t.prev,users:t.users.map(r=>cn(r))}}}getModQueue(e={type:"all"}){return Ee.aboutLocation({...e,location:"modqueue",subreddit:n(this,x)},n(this,R))}getReports(e={type:"all"}){return Ee.aboutLocation({...e,location:"reports",subreddit:n(this,x)},n(this,R))}getSpam(e={type:"all"}){return Ee.aboutLocation({...e,location:"spam",subreddit:n(this,x)},n(this,R))}getUnmoderated(e={type:"all"}){return Ee.aboutLocation({...e,location:"unmoderated",subreddit:n(this,x)},n(this,R))}getEdited(e={type:"all"}){return Ee.aboutLocation({...e,location:"edited",subreddit:n(this,x)},n(this,R))}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 Tc(d,t)}})}getCommentsAndPostsByIds(e){let t=u.redditAPIPlugins.LinksAndComments;return new W({fetch:async()=>{let r=await t.Info({thingIds:e,subreddits:[n(this,mr)]},n(this,R));return Tc(r,n(this,R))}})}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?.[S.SubredditName]?.values[0];if(t)return Ee.getByName(t,e);let r=e?.[S.Subreddit]?.values[0];return p(r),Ee.getById(K(r),e)}static async getById(e,t){let r=await $o(e,t);if(r)return Ee.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 Ee(s.data,t)}};mr=new WeakMap,x=new WeakMap,ts=new WeakMap,is=new WeakMap,rs=new WeakMap,ns=new WeakMap,ss=new WeakMap,os=new WeakMap,as=new WeakMap,ds=new WeakMap,ls=new WeakMap,pr=new WeakMap,R=new WeakMap;var le=Ee;async function Bd(i,e){let o=(await Y.query("GetSubredditInfoById","315a9b75c22a017d526afdf2d274616946156451aacfd56dfb91e7ad3f7a2fde",{id:i},e)).data?.subredditInfoById;if(!o)throw new Error("subreddit info not found");return o}async function Dd(i,e){let o=(await Y.query("GetSubredditInfoByName","4aa69726c7e3f5d33ab2bee22b3d74fce645824fddd5ea3ec6dfe30bdb4295cb",{name:i},e)).data?.subredditInfoByName;if(!o)throw new Error("subreddit info not found");return o}async function Nd(i,e){let o=(await Y.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 Ld(i,e){let o=(await Y.query("GetSubredditStyles","d491d17ea8858f563ea578b26b9595d64adecf4bf34557d567c7e53c470f5f22",{id:i},e)).data?.subredditInfoById?.styles;if(!o)throw new Error("subreddit styles not found");return o}function fg(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 yg(i){if(i==="any"||i==="link"||i==="self")return i;throw new Error(`invalid allowed post type: ${i}`)}function bg(i){if(i==="animated"||i==="giphy"||i==="static"||i==="expression")return i;throw new Error(`invalid comment media type: ${i}`)}function Tc(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 G(d.data,e)}catch{return null}}function o(d){try{return new Q(d.data,e)}catch{return null}}}async function $o(i,e){return(await u.redditAPIPlugins.LinksAndComments.Info({thingIds:[i],subreddits:[]},e)).data?.children[0]?.data?.displayName}async function _d(i,e){return Rc("GetVaultContactByAddress","3e2f7966a5c120e64fd2795d06a46595c52d988185be98d3ed71c3f81ae80d2e",{provider:"ethereum",address:i},e)}async function Hd(i,e){return Rc("GetVaultContactByUserId","a854ddc19d0e22c4f36ed917fdbd568f299f3571427e393aee5e2972080fffe9",{provider:"ethereum",userId:i},e)}async function Rc(i,e,t,r){let o=(await Y.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 vg,GetWidgetsResponse_WidgetItem as ae}from"@devvit/protos";var us,cs,ms,ps,ed=class ed{constructor(e,t,r){l(this,us);l(this,cs);l(this,ms);l(this,ps);Z(this),a(this,us,e.id),a(this,cs,e.shortName),a(this,ms,t),a(this,ps,r)}get id(){return n(this,us)}get name(){return n(this,cs)}get subredditName(){return n(this,ms)}toJSON(){return{id:this.id,name:this.name,subredditName:this.subredditName}}delete(){return ed.delete(this.subredditName,this.id,n(this,ps))}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 Fo(m,e,t));break;case"calendar":d.push(new xo(m,e,t));break;case"textarea":d.push(new Ao(m,e,t));break;case"button":d.push(new Io(m,e,t));break;case"community-list":d.push(new Eo(m,e,t));break;case"post-flair":d.push(new To(m,e,t));break;case"custom":d.push(new Ro(m,e,t));break;case"subreddit-rules":{let y=await u.redditAPIPlugins.Subreddits.SubredditAboutRules({subreddit:e},t);d.push(new Ya(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 Fo.create(e,t);case"calendar":return xo.create(e,t);case"textarea":return Ao.create(e,t);case"button":return Io.create(e,t);case"community-list":return Eo.create(e,t);case"post-flair":return To.create(e,t);case"custom":return Ro.create(e,t);default:throw new Error("Unknown widget type")}}};us=new WeakMap,cs=new WeakMap,ms=new WeakMap,ps=new WeakMap;var ie=ed,gs,Oo=class Oo extends ie{constructor(t,r,s){super(t,r,s);l(this,gs);a(this,gs,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,gs)}toJSON(){return{...super.toJSON(),images:this.images}}static async create(t,r){let o=await u.redditAPIPlugins.Widgets.AddImageWidget(t,r);return new Oo(ae.fromJSON(o),t.subreddit,r)}static async update(t,r){let o=await u.redditAPIPlugins.Widgets.UpdateImageWidget(t,r);return new Oo(ae.fromJSON(o),t.subreddit,r)}};gs=new WeakMap;var Fo=Oo,hs,fs,ys,Mo=class Mo extends ie{constructor(t,r,s){super(t,r,s);l(this,hs);l(this,fs);l(this,ys);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,hs,t.googleCalendarId),a(this,fs,t.configuration),a(this,ys,t.styles)}get googleCalendarId(){return n(this,hs)}get configuration(){return n(this,fs)}get styles(){return n(this,ys)}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 Mo(ae.fromJSON(o),t.subreddit,r)}static async update(t,r){let o=await u.redditAPIPlugins.Widgets.UpdateCalendarWidget(t,r);return new Mo(ae.fromJSON(o),t.subreddit,r)}};hs=new WeakMap,fs=new WeakMap,ys=new WeakMap;var xo=Mo,bs,vs,Uo=class Uo extends ie{constructor(t,r,s){super(t,r,s);l(this,bs);l(this,vs);p(t.text,"Textarea widget data is missing text"),p(t.styles,"Textarea widget data is missing styles"),a(this,bs,t.text),a(this,vs,t.styles)}get text(){return n(this,bs)}get styles(){return n(this,vs)}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 Uo(ae.fromJSON(o),t.subreddit,r)}static async update(t,r){let o=await u.redditAPIPlugins.Widgets.UpdateTextAreaWidget(t,r);return new Uo(ae.fromJSON(o),t.subreddit,r)}};bs=new WeakMap,vs=new WeakMap;var Ao=Uo,ks,Cs,Ps,Bo=class Bo extends ie{constructor(t,r,s){super(t,r,s);l(this,ks);l(this,Cs);l(this,Ps);p(t.styles,"Button widget data is missing styles"),a(this,ks,t.buttons),a(this,Cs,t.description??""),a(this,Ps,t.styles)}get buttons(){return n(this,ks)}get description(){return n(this,Cs)}get styles(){return n(this,Ps)}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 Bo(ae.fromJSON(o),t.subreddit,r)}static async update(t,r){let o=await u.redditAPIPlugins.Widgets.UpdateButtonWidget(t,r);return new Bo(ae.fromJSON(o),t.subreddit,r)}};ks=new WeakMap,Cs=new WeakMap,Ps=new WeakMap;var Io=Bo,Ss,ws,Do=class Do extends ie{constructor(t,r,s){super(t,r,s);l(this,Ss);l(this,ws);a(this,Ss,t.data.map(o=>vg.fromJSON(o))),p(t.styles,"Community list widget data is missing styles"),a(this,ws,t.styles)}get communities(){return n(this,Ss)}get styles(){return n(this,ws)}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 Do(ae.fromJSON(o),t.subreddit,r)}static async update(t,r){let o=await u.redditAPIPlugins.Widgets.UpdateCommunityListWidget(t,r);return new Do(ae.fromJSON(o),t.subreddit,r)}};Ss=new WeakMap,ws=new WeakMap;var Eo=Do,Fs,xs,As,No=class No extends ie{constructor(t,r,s){super(t,r,s);l(this,Fs);l(this,xs);l(this,As);if(p(t.styles,"Post flair widget data is missing styles"),a(this,Fs,t.styles),a(this,xs,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,As,t.display)}get styles(){return n(this,Fs)}get templates(){return n(this,xs)}get display(){return n(this,As)}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 No(ae.fromJSON(o),t.subreddit,r)}static async update(t,r){let o=await u.redditAPIPlugins.Widgets.UpdatePostFlairWidget(t,r);return new No(ae.fromJSON(o),t.subreddit,r)}};Fs=new WeakMap,xs=new WeakMap,As=new WeakMap;var To=No,Is,Es,Ts,Rs,Os,Lo=class Lo extends ie{constructor(t,r,s){super(t,r,s);l(this,Is);l(this,Es);l(this,Ts);l(this,Rs);l(this,Os);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,Is,t.imageData??[]),a(this,Es,t.text??""),a(this,Ts,t.stylesheetUrl),a(this,Rs,t.height),a(this,Os,t.css)}get images(){return n(this,Is)}get text(){return n(this,Es)}get stylesheetUrl(){return n(this,Ts)}get height(){return n(this,Rs)}get css(){return n(this,Os)}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 Lo(ae.fromJSON(o),t.subreddit,r)}static async update(t,r){let o=await u.redditAPIPlugins.Widgets.UpdateCustomWidget(t,r);return new Lo(ae.fromJSON(o),t.subreddit,r)}};Is=new WeakMap,Es=new WeakMap,Ts=new WeakMap,Rs=new WeakMap,Os=new WeakMap;var Ro=Lo,Ms,Ya=class extends ie{constructor(t,r,s,o){super(r,s,o);l(this,Ms);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,Ms,d)}get rules(){return n(this,Ms)}toJSON(){return{...super.toJSON(),rules:this.rules}}};Ms=new WeakMap;var kg=(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))(kg||{}),ge,he,gr,hr,fr,yr,br,vr,Te,xe=class xe{constructor(e,t,r,s){l(this,ge);l(this,he);l(this,gr);l(this,hr);l(this,fr);l(this,yr);l(this,br);l(this,vr);l(this,Te);Z(this),a(this,ge,e),a(this,he,t),a(this,gr,r.contentMd),a(this,hr,r.contentHtml),a(this,fr,r.revisionId),a(this,yr,new Date(r.revisionDate*1e3)),a(this,br,r.reason??""),a(this,vr,r.revisionBy?.data?new C(r.revisionBy.data,s):void 0),a(this,Te,s)}get name(){return n(this,ge)}get subredditName(){return n(this,he)}get content(){return n(this,gr)}get contentHtml(){return n(this,hr)}get revisionId(){return n(this,fr)}get revisionDate(){return n(this,yr)}get revisionReason(){return n(this,br)}get revisionAuthor(){return n(this,vr)}toJSON(){return{name:n(this,ge),subredditName:n(this,he),content:n(this,gr),contentHtml:n(this,hr),revisionId:n(this,fr),revisionDate:n(this,yr),revisionReason:n(this,br),revisionAuthor:n(this,vr)?.toJSON()}}async update(e,t){return xe.updatePage({subredditName:n(this,he),page:n(this,ge),content:e,reason:t},n(this,Te))}async getRevisions(e){return xe.getPageRevisions({subredditName:n(this,he),page:n(this,ge),...e},n(this,Te))}async revertTo(e){return xe.revertPage(n(this,he),n(this,ge),e,n(this,Te))}async getSettings(){return xe.getPageSettings(n(this,he),n(this,ge),n(this,Te))}async updateSettings(e){return xe.updatePageSettings({subredditName:n(this,he),page:n(this,ge),listed:e.listed,permLevel:e.permLevel},n(this,Te))}async addEditor(e){return xe.addEditor(n(this,he),n(this,ge),e,n(this,Te))}async removeEditor(e){return xe.removeEditor(n(this,he),n(this,ge),e,n(this,Te))}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 xe(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 xe.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),xe.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 Cg(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 _o(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 _o(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)}};ge=new WeakMap,he=new WeakMap,gr=new WeakMap,hr=new WeakMap,fr=new WeakMap,yr=new WeakMap,br=new WeakMap,vr=new WeakMap,Te=new WeakMap;var ue=xe,kr,Cr,Pr,Sr,wr,Fr,td=class{constructor(e,t){l(this,kr);l(this,Cr);l(this,Pr);l(this,Sr);l(this,wr);l(this,Fr);a(this,kr,e.id),a(this,Cr,e.page),a(this,Pr,new Date(e.timestamp)),p(e.author?.data,"Wiki page revision author details are missing"),a(this,Sr,new C(e.author.data,t)),a(this,wr,e.reason??""),a(this,Fr,e.revisionHidden??!1)}get id(){return n(this,kr)}get page(){return n(this,Cr)}get date(){return n(this,Pr)}get author(){return n(this,Sr)}get reason(){return n(this,wr)}get hidden(){return n(this,Fr)}toJSON(){return{id:n(this,kr),page:n(this,Cr),date:n(this,Pr),author:n(this,Sr).toJSON(),reason:n(this,wr),hidden:n(this,Fr)}}};kr=new WeakMap,Cr=new WeakMap,Pr=new WeakMap,Sr=new WeakMap,wr=new WeakMap,Fr=new WeakMap;var xr,Ar,Ir,_o=class{constructor(e,t){l(this,xr);l(this,Ar);l(this,Ir);a(this,xr,e.listed),a(this,Ar,e.permLevel),a(this,Ir,e.editors.map(r=>(p(r.data,"Wiki page editor details are missing"),new C(r.data,t))))}get listed(){return n(this,xr)}get permLevel(){return n(this,Ar)}get editors(){return n(this,Ir)}toJSON(){return{listed:n(this,xr),permLevel:n(this,Ar),editors:n(this,Ir).map(e=>e.toJSON())}}};xr=new WeakMap,Ar=new WeakMap,Ir=new WeakMap;function Cg(i,e){return p(i.data?.children,"Wiki page revision listing is missing children"),{children:i.data.children.map(r=>new td(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"],Sg=["border-image","border-image-source","behavior","expression","list-style-image","cursor","content"],wg=["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 Oc(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(`(${Sg.join("|")})\\s*:\\s*url\\s*\\((['"]?)(.*?)\\2\\)`,"gi"),r=new RegExp(`(${wg.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 YP(i,...e){let t="";return i.forEach((r,s)=>{t+=r;let o=e[s];o!==void 0&&(t+=`${o}`)}),t=Oc(t),t===void 0?"":`data:image/svg+xml;charset=UTF-8,${encodeURIComponent(t)}`}import{EffectType as Uc}from"@devvit/protos";import{WebViewVisibility as xg}from"@devvit/protos";var Mc=i=>i===null||typeof i!="object"?!1:"scope"in i&&i.scope===0&&"type"in i&&i.type==="devvit-internal";var Er,Us,Bs,Tr,ii,Ds,Ns,id=class{constructor(e,t){this.state={messageCount:0,isMounted:!1};l(this,Er);l(this,Us);l(this,Bs);l(this,Tr);l(this,ii);l(this,Ds);this.postMessage=e=>{try{let t=JSON.stringify(e);n(this,ii).emitEffect(`postMessage${this.state.messageCount++}`,{type:Uc.EFFECT_WEB_VIEW,webView:{postMessage:{webViewId:n(this,Er),app:{message:e,jsonString:t}}}})}catch(t){throw console.error(et.caughtToString(t)),Error("Something went wrong. Please check the contents of your postMessage.")}};this.mount=()=>{if(this.state.isMounted){console.warn("Webview is already mounted!");return}let t=(n(this,ii)?.devvitContext?.assets).getURL(n(this,Us),{webView:!0});if(!t)throw Error("useWebView fullscreen request failed; web view asset could not be found");n(this,Ns).call(this,!0,t)};this.unmount=()=>{n(this,Ns).call(this,!1,"")};l(this,Ns,(e,t)=>{n(this,ii).emitEffect("fullscreen",{type:Uc.EFFECT_WEB_VIEW,webView:{fullscreen:{id:n(this,Er),show:e,url:t}}})});a(this,Us,t.url??"index.html"),a(this,Er,e.hookId),a(this,Bs,t.onMessage),a(this,Tr,t.onUnmount),a(this,ii,e.context),a(this,Ds,e.invalidate)}onStateLoaded(){}async onUIEvent(e){if(e.webView?.fullScreen){let t=e.webView.fullScreen.visibility===xg.WEBVIEW_VISIBLE;this.state.isMounted=t,n(this,Ds).call(this),!t&&n(this,Tr)&&await n(this,Tr).call(this,this)}else if(e.webView?.postMessage){let t=e.webView.postMessage.jsonString?JSON.parse(e.webView.postMessage.jsonString):e.webView.postMessage.message;if(Mc(t))return;await n(this,Bs).call(this,t,this)}}};Er=new WeakMap,Us=new WeakMap,Bs=new WeakMap,Tr=new WeakMap,ii=new WeakMap,Ds=new WeakMap,Ns=new WeakMap;function Ag(i){let e=me({namespace:"useWebView",initializer:t=>new id(t,i)});return{postMessage:e.postMessage,mount:e.mount,unmount:e.unmount}}export{_g as ALL_ICON_NAMES,Ud as AboutLocations,Ic as AuthorFlairSettings,Io as ButtonWidget,xo as CalendarWidget,Q as Comment,Eo as CommunityListWidget,Ro as CustomWidget,Wg as DeletionReason,u as Devvit,Gg as EventSource,ce as Flair,ne as FlairTemplate,qp as FlairType,fC as GalleryMediaStatus,ze as Hook,Fo as ImageWidget,W as Listing,gg as ModMailActionType,mg as ModMailConversationState,Ws as ModMailService,ke as ModNote,G as Post,Ec as PostFlairSettings,To as PostFlairWidget,Rt as PrivateMessage,Gt as RichTextBuilder,fe as RunAs,Vo as SettingScope,dg as SocialLinkType,le as Subreddit,xc as SubredditDescription,Ya as SubredditRulesWidget,Ac as SubredditWikiSettings,Ao as TextAreaWidget,C as User,ie as Widget,ue as WikiPage,kg as WikiPagePermissionLevel,td as WikiPageRevision,_o as WikiPageSettings,cn as convertUserFlairProtoToAPI,Md as getCurrentUsernameFromMetadata,Vs as getModerationLog,Bd as getSubredditInfoById,Dd as getSubredditInfoByName,Nd as getSubredditLeaderboard,$o as getSubredditNameById,Ld as getSubredditStyles,_d as getVaultByAddress,Hd as getVaultByUserId,YP as svg,Mp as useAsync,Ia as useChannel,Fa as useForm,Ra as useInterval,Ba as useState,Ag as useWebView};
|
|
1
|
+
var Dc=Object.create;var od=Object.defineProperty;var Nc=Object.getOwnPropertyDescriptor;var Lc=Object.getOwnPropertyNames;var _c=Object.getPrototypeOf,Hc=Object.prototype.hasOwnProperty;var ad=r=>{throw TypeError(r)};var si=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var jc=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Lc(e))!Hc.call(r,s)&&s!==t&&od(r,s,{get:()=>e[s],enumerable:!(i=Nc(e,s))||i.enumerable});return r};var dd=(r,e,t)=>(t=r!=null?Dc(_c(r)):{},jc(e||!r||!r.__esModule?od(t,"default",{value:r,enumerable:!0}):t,r));var jo=(r,e,t)=>e.has(r)||ad("Cannot "+t);var n=(r,e,t)=>(jo(r,e,"read from private field"),t?t.call(r):e.get(r)),l=(r,e,t)=>e.has(r)?ad("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),a=(r,e,t,i)=>(jo(r,e,"write to private field"),i?i.call(r,t):e.set(r,t),t),h=(r,e,t)=>(jo(r,e,"access private method"),t);var ld=(r,e,t,i)=>({set _(s){a(r,e,s,t)},get _(){return n(r,e,i)}});var ya=si((gb,Pl)=>{var rp=Object.prototype.toString;Pl.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 dp(e)?"generatorfunction":"function";if(np(e))return"array";if(cp(e))return"buffer";if(up(e))return"arguments";if(op(e))return"date";if(sp(e))return"error";if(ap(e))return"regexp";switch(Cl(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(lp(e))return"generator";switch(t=rp.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 Cl(r){return typeof r.constructor=="function"?r.constructor.name:null}function np(r){return Array.isArray?Array.isArray(r):r instanceof Array}function sp(r){return r instanceof Error||typeof r.message=="string"&&r.constructor&&typeof r.constructor.stackTraceLimit=="number"}function op(r){return r instanceof Date?!0:typeof r.toDateString=="function"&&typeof r.getDate=="function"&&typeof r.setDate=="function"}function ap(r){return r instanceof RegExp?!0:typeof r.flags=="string"&&typeof r.ignoreCase=="boolean"&&typeof r.multiline=="boolean"&&typeof r.global=="boolean"}function dp(r,e){return Cl(r)==="GeneratorFunction"}function lp(r){return typeof r.throw=="function"&&typeof r.return=="function"&&typeof r.next=="function"}function up(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 cp(r){return r.constructor&&typeof r.constructor.isBuffer=="function"?r.constructor.isBuffer(r):!1}});var Fl=si((hb,wl)=>{"use strict";var Sl=Symbol.prototype.valueOf,mp=ya();function pp(r,e){switch(mp(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 yp(r);case"symbol":return bp(r);case"arraybuffer":return hp(r);case"float32array":case"float64array":case"int16array":case"int32array":case"int8array":case"uint16array":case"uint32array":case"uint8clampedarray":case"uint8array":return fp(r);case"regexp":return gp(r);case"error":return Object.create(r);default:return r}}function gp(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 hp(r){let e=new r.constructor(r.byteLength);return new Uint8Array(e).set(new Uint8Array(r)),e}function fp(r,e){return new r.constructor(r.buffer,r.byteOffset,r.length)}function yp(r){let e=r.length,t=Buffer.allocUnsafe?Buffer.allocUnsafe(e):Buffer.from(e);return r.copy(t),t}function bp(r){return Sl?Object(Sl.call(r)):{}}wl.exports=pp});var Al=si((fb,xl)=>{"use strict";xl.exports=function(e){return e!=null&&typeof e=="object"&&Array.isArray(e)===!1}});var Tl=si((yb,El)=>{"use strict";var vp=Al();function Il(r){return vp(r)===!0&&Object.prototype.toString.call(r)==="[object Object]"}El.exports=function(e){var t,i;return!(Il(e)===!1||(t=e.constructor,typeof t!="function")||(i=t.prototype,Il(i)===!1)||i.hasOwnProperty("isPrototypeOf")===!1)}});var Ol=si((bb,Rl)=>{"use strict";var kp=Fl(),Cp=ya(),Pp=Tl();function ba(r,e){switch(Cp(r)){case"object":return Sp(r,e);case"array":return wp(r,e);default:return kp(r)}}function Sp(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]=ba(r[i],e);return t}return r}function wp(r,e){let t=new r.constructor(r.length);for(let i=0;i<r.length;i++)t[i]=ba(r[i],e);return t}Rl.exports=ba});var Pc=si(So=>{"use strict";So.byteLength=Yp;So.toByteArray=tg;So.fromByteArray=ng;var Be=[],Fe=[],Qp=typeof Uint8Array<"u"?Uint8Array:Array,Ka="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Kt=0,kc=Ka.length;Kt<kc;++Kt)Be[Kt]=Ka[Kt],Fe[Ka.charCodeAt(Kt)]=Kt;var Kt,kc;Fe[45]=62;Fe[95]=63;function Cc(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 Yp(r){var e=Cc(r),t=e[0],i=e[1];return(t+i)*3/4-i}function eg(r,e,t){return(e+t)*3/4-t}function tg(r){var e,t=Cc(r),i=t[0],s=t[1],o=new Qp(eg(r,i,s)),d=0,c=s>0?i-4:i,m;for(m=0;m<c;m+=4)e=Fe[r.charCodeAt(m)]<<18|Fe[r.charCodeAt(m+1)]<<12|Fe[r.charCodeAt(m+2)]<<6|Fe[r.charCodeAt(m+3)],o[d++]=e>>16&255,o[d++]=e>>8&255,o[d++]=e&255;return s===2&&(e=Fe[r.charCodeAt(m)]<<2|Fe[r.charCodeAt(m+1)]>>4,o[d++]=e&255),s===1&&(e=Fe[r.charCodeAt(m)]<<10|Fe[r.charCodeAt(m+1)]<<4|Fe[r.charCodeAt(m+2)]>>2,o[d++]=e>>8&255,o[d++]=e&255),o}function ig(r){return Be[r>>18&63]+Be[r>>12&63]+Be[r>>6&63]+Be[r&63]}function rg(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(ig(i));return s.join("")}function ng(r){for(var e,t=r.length,i=t%3,s=[],o=16383,d=0,c=t-i;d<c;d+=o)s.push(rg(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("")}});var fe={APP:0,USER:1,UNSPECIFIED:2};function p(r,e){if(r==null)throw Error(e??"Expected nonnullish value.")}function It(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 Je(r){return r.startsWith(ee.COMMENT)}function _s(r){return r.startsWith(ee.ACCOUNT)}function Et(r){return r.startsWith(ee.LINK)}function ud(r){return r.startsWith(ee.MESSAGE)}function cd(r){return r.startsWith(ee.SUBREDDIT)}function md(r){return r.startsWith(ee.AWARD)}function Vc(r){It(Je(r),`Expected comment id to start with ${ee.COMMENT}, got ${r}}`)}function Wc(r){It(_s(r),`Expected account id to start with ${ee.ACCOUNT}, got ${r}}`)}function Gc(r){It(Et(r),`Expected link id to start with ${ee.LINK}, got ${r}}`)}function Jc(r){It(ud(r),`Expected message id to start with ${ee.MESSAGE}, got ${r}}`)}function zc(r){It(cd(r),`Expected subreddit id to start with ${ee.SUBREDDIT}, got ${r}}`)}function qc(r){It(md(r),`Expected award id to start with ${ee.AWARD}, got ${r}}`)}function oi(r){return Vc(r),r}function te(r){return Wc(r),r}function de(r){return Gc(r),r}function $c(r){return Jc(r),r}function K(r){return zc(r),r}function Kc(r){return qc(r),r}function ye(r){if(Je(r))return oi(r);if(_s(r))return te(r);if(Et(r))return de(r);if(ud(r))return $c(r);if(cd(r))return K(r);if(md(r))return Kc(r);throw new Error(`Expected thing id to start with ${Object.values(ee).join(", ")} got ${r}}`)}function Vo(r){return Je(r)}import*as k from"@devvit/protos";var Hs=class{constructor(e){}};var Wo=(t=>(t.Installation="installation",t.App="app",t))(Wo||{});function Tt(r,e=new Set){for(let t of r){if(t.type==="group"){Tt(t.fields,e);continue}let i=t.name;if(e.has(i))throw new Error(`Duplicate field name: ${i}`);e.add(i)}Zc(r)}function Zc(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 ze=Object.freeze({INTERVAL:0,FORM:1,STATE:2,CHANNEL:3,WEB_VIEW:4});var Hg=["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{DeletionReason as Gg,EventSource as Jg}from"@devvit/protos";import{AppSettingsDefinition as pm,GetFieldsResponse as gm}from"@devvit/protos";import{FormFieldType as be}from"@devvit/protos";function Le(r){return r.map(e=>{switch(e.type){case"string":return Xc(e);case"image":return Qc(e);case"paragraph":return Yc(e);case"number":return em(e);case"select":return tm(e);case"boolean":return im(e);case"group":return rm(e);default:throw new Error("Unknown field type.")}})}function Xc(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 Qc(r){return{disabled:r.disabled,fieldId:r.name,fieldType:be.IMAGE,helpText:r.helpText,label:r.label,required:r.required}}function Yc(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 em(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 tm(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 im(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 rm(r){return{fieldId:"",fieldType:be.GROUP,fieldConfig:{groupConfig:{fields:Le(r.fields)}},label:r.label,helpText:r.helpText}}function O(r,e){u.prototype[r]=e}import{ValidateFormResponse as mm}from"@devvit/protos";import{RealtimeSubscriptionStatus as gd}from"@devvit/protos";var S=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",UserSnoovatarUrl:"devvit-user-snoovatar-url",UserAgent:"devvit-user-agent",Version:"devvit-version",Language:"devvit-accept-language",Timezone:"devvit-accept-timezone",Traceparent:"traceparent",AppDependencies:"devvit-app-dependencies"});var pd;(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"})(pd||(pd={}));function hd(r){function e(t){let s=r.currentHookIndex,o=r.getCurrentComponentState(),d=r.getPreviousComponentState(),c=r.metadata[S.App]?.values[0];p(c,"useChannel - app is missing from Context");let m=r.metadata[S.Installation]?.values[0];p(m,"useChannel - installation is missing from Context");async function y(V){let B=o[s].channel;if(o[s].active)if(o[s].connected)await r.realtime.send(B,V);else throw Error(`Failed to send to channel '${B}'; it is active but not yet connected`);else throw Error(`Cannot send a message over inactive channel: ${B}`)}function v(){if(!o[s].active){let V=o[s].channel;o[s].active=!0,r.addRealtimeChannel(V)}}function f(){if(o[s].active){let V=o[s].channel;o[s].active=!1,r.removeRealtimeChannel(V)}}function P(V){return async()=>{let B;switch(V.status){case gd.REALTIME_SUBSCRIBED:o[s].connected=!0,B=t.onSubscribed?.();break;case gd.REALTIME_UNSUBSCRIBED:o[s].connected=!1,B=t.onUnsubscribed?.();break;default:B=t.onMessage(V.event?.data?.msg);break}await B}}let b={channel:`${c}:${m}:${t.name}`,active:!1,connected:!1,preventCallback:!1,type:ze.CHANNEL};s in o?b=o[s]:s in d&&(b=d[s]);let L=r.realtimeEvent;r.isInitialRender?b.active=!1:L&&b.active&&L.event.channel===b.channel&&(b.preventCallback||r.runHook(P(L)),r.rerenderIn(0)),o[s]=b,r.currentHookIndex++;let A=0;return b.active&&b.connected?A=2:b.active&&!b.connected?A=1:!b.active&&b.connected?A=3:!b.active&&!b.connected&&(A=4),{subscribe:v,unsubscribe:f,send:y,status:A}}return e}import{FormFieldType as ai}from"@devvit/protos";function Go(r){switch(r.fieldType){case ai.STRING:return r.stringValue;case ai.IMAGE:return r.stringValue;case ai.PARAGRAPH:return r.stringValue;case ai.NUMBER:return r.numberValue;case ai.BOOLEAN:return r.boolValue;case ai.SELECTION:return r.selectionValue?.values??[];default:return}}function qe(r){return Object.keys(r).reduce((e,t)=>{let i=Go(r[t]);return i!==void 0&&(e[t]=i),e},{})}function fd(r){function e(t,i){let s=r.currentHookIndex,o=r.getCurrentComponentKey(),d=r.getCurrentComponentState(),c=r.getPreviousComponentState(),m=`form.hook.${o}.${s}`,y={formKey:m,preventSubmit:!1,type:ze.FORM};s in d?y=d[s]:s in c&&(y=c[s]),d[s]=y,r.forms.set(m,t);let v=r.formSubmittedEvent;return v&&!y.preventSubmit&&v.formId===m&&r.runHook(async()=>{let f=i(qe(v.results));f&&f instanceof Promise&&await f,r.rerenderIn(0)}),d[s].preventSubmit=!1,r.currentHookIndex++,m}return e}function yd(r){function e(t,i){let s=r.currentHookIndex,o=r.getCurrentComponentState(),d=r.getPreviousComponentState(),c=100,m=Math.max(c,i),y={lastRun:void 0,running:!1,preventCallback:!1,type:ze.INTERVAL};s in o?y=o[s]:s in d&&(y=d[s]);function v(){i<c&&console.error(`useInterval delay must be at least ${c}ms. Your interval of ${i}ms was automatically extended.`);for(let[P,b]of Object.entries(o))if(P!==s.toString()&&b?.type===ze.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:ze.INTERVAL},r.rerenderIn(m)}function f(){o[s].running=!1,o[s].lastRun=void 0,o[s].preventCallback=!1}return r.isEffectRender&&y.running&&(y.preventCallback||(y.lastRun===void 0||y.lastRun+m<Date.now())&&r.runHook(async()=>{let P=t();P&&P instanceof Promise&&await P,y.lastRun=Date.now()}),r.rerenderIn(m)),y.preventCallback=!1,o[s]=y,r.currentHookIndex++,{start:v,stop:f}}return e}function bd(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 $o={now(){return new Date}};function vd(r){return`__autocache__${r}`}function kd(r){return`__lock__${r}`}var sm=300,om=1e3,js=5e3,Jo=3,Cd=.1,Pd=1e3,am=3e4;function Sd(r){if(r.error)throw new Error(r.error);return r.value}var $e,Ke,ve,di,z,wd,Fd,xd,zo,Ad,Id,qo,Ed,Vs=class{constructor(e,t,i=$o){l(this,z);l(this,$e);l(this,Ke,{});l(this,ve);l(this,di);a(this,$e,e),a(this,di,t),a(this,ve,i)}async cache(e,t){a(this,Ke,n(this,di).__cache=n(this,di).__cache??{}),h(this,z,Ed).call(this,t);let i=h(this,z,wd).call(this,t.key);if(i!==void 0)return i;let s=await h(this,z,qo).call(this,t.key),o=await h(this,z,Fd).call(this,t,s,e);return Sd(o)}};$e=new WeakMap,Ke=new WeakMap,ve=new WeakMap,di=new WeakMap,z=new WeakSet,wd=function(e){let t=n(this,Ke)[e];if(t){let i=n(this,ve).now().getTime(),s=t?.error&&t?.errorTime&&t.errorCount<Jo&&Math.random()<Cd&&t.errorTime+Pd<i;if(t?.expires&&t.expires<i&&t.checkedAt+Pd<i||s){delete n(this,Ke)[e];return}else return Sd(t)}},Fd=async function(e,t,i){let s=t?.expires,o=s?h(this,z,Id).call(this,s):1;return!t||t?.error&&t.errorCount<Jo&&Cd>Math.random()||o>Math.random()?h(this,z,xd).call(this,e,t,i):t},xd=async function(e,t,i){let s=kd(e.key),o=n(this,ve).now().getTime(),d=new Date(o+e.ttl/2);if(await n(this,$e).set(s,"1",{expiration:d,nx:!0}))return h(this,z,Ad).call(this,e.key,t,i,e.ttl);if(t)return t;{let m=n(this,ve).now();return h(this,z,zo).call(this,m,e.key,e.ttl)}},zo=async function(e,t,i){let s=Math.min(i,om),o=await h(this,z,qo).call(this,t);if(o)return o;if(n(this,ve).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,sm)),h(this,z,zo).call(this,e,t,i)},Ad=async function(e,t,i,s){let o=n(this,ve).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,ve).now().getTime(),t.errorCount++}return n(this,Ke)[e]=t,await n(this,$e).set(vd(e),JSON.stringify(t),{expiration:new Date(o+am)}),t.error&&t.errorCount<Jo&&await n(this,$e).del(kd(e)),t},Id=function(e){let t=n(this,ve).now().getTime(),i=e-t;return i<0?1:i<1e3?.1:i<2e3?.01:i<3e3?.001:0},qo=async function(e){let t=await n(this,$e).get(vd(e));if(t){let i=JSON.parse(t);return i.checkedAt=n(this,ve).now().getTime(),n(this,Ke)[e]=i,i}},Ed=function(e){e.ttl<js&&(console.warn(`Cache TTL cannot be less than ${js} milliseconds! Updating ttl value of ${e.ttl} to ${js}.`),e.ttl=js)};function Td(r,e,t=$o){let i=new Vs(r,e,t);return i.cache.bind(i)}function Rd(r){new URL(r.slice(0,r.indexOf(",")))}var li,ui,mi,Od,Md,ci=class{constructor(){l(this,mi);l(this,li,{});l(this,ui,{});a(this,li,u.assets),a(this,ui,u.webViewAssets)}getURL(e,t){return typeof e=="string"?h(this,mi,Od).call(this,e,t??{webView:!1}):h(this,mi,Md).call(this,e,t??{webView:!1})}};li=new WeakMap,ui=new WeakMap,mi=new WeakSet,Od=function(e,t){let i=t.webView?n(this,ui)[e]:n(this,li)[e];if(i)return i;try{return Rd(e),e}catch{return""}},Md=function(e,t){let i={},s=[],o=t.webView?n(this,ui):n(this,li);if(o)for(let d of e)if(o[d])i[d]=o[d];else try{Rd(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 Ze,pi=class{constructor(e){l(this,Ze);a(this,Ze,e)}async get(e){let{messages:t}=await u.kvStorePlugin.Get({keys:[e]},n(this,Ze));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,Ze))}async delete(e){await u.kvStorePlugin.Del({keys:[e]},n(this,Ze))}async list(){let{keys:e}=await u.kvStorePlugin.List({filter:"*"},n(this,Ze));return e}};Ze=new WeakMap;var Or,gi=class{constructor(e){l(this,Or);a(this,Or,e)}async upload(e){let t=await u.mediaPlugin.Upload(e,n(this,Or));if(!t.mediaId)throw new Error("unable to get mediaId via uploads");return Promise.resolve({mediaId:t.mediaId,mediaUrl:t.mediaUrl})}};Or=new WeakMap;var Mr,hi=class{constructor(e){l(this,Mr);a(this,Mr,e)}async add(e){await u.modLogPlugin.Add(e,n(this,Mr))}};Mr=new WeakMap;var Ur,fi=class{constructor(e){l(this,Ur);a(this,Ur,e)}async send(e,t){await u.realtimePlugin.Send({channel:e,data:{msg:t}},n(this,Ur))}};Ur=new WeakMap;import"@devvit/protos";var g,Br,Dr,Nr,yi=class{constructor(e){l(this,g);l(this,Br);l(this,Dr);l(this,Nr);a(this,g,e),a(this,Br,new Gs(e))}get modMail(){return n(this,Br)}getSubredditById(e){return le.getById(ye(e),n(this,g))}getSubredditInfoById(e){return Dd(e,n(this,g))}getSubredditByName(e){return le.getByName(e,n(this,g))}getSubredditInfoByName(e){return Nd(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)?.[S.SubredditName]?.values[0];if(e)return e;let t=n(this,g)?.[S.Subreddit]?.values[0],i=await Ko(K(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 G.getById(ye(e),n(this,g))}submitPost(e){return G.submit(e,n(this,g))}crosspost(e){return G.crosspost(e,n(this,g))}getUserById(e){return C.getById(ye(e),n(this,g))}getUserByUsername(e){return C.getByUsername(e,n(this,g))}async getCurrentUsername(){return n(this,Nr)??a(this,Nr,Ud(n(this,g))),n(this,Nr)}async getCurrentUser(){return n(this,Dr)??a(this,Dr,this.getCurrentUsername().then(e=>e?C.getByUsername(e,n(this,g)):void 0)),n(this,Dr)}getAppUser(){return C.getFromMetadata(S.AppUser,n(this,g))}async getSnoovatarUrl(e){let t=await this.getCurrentUsername();if(t&&e===t){let i=n(this,g)?.[S.UserSnoovatarUrl]?.values[0];if(i)return i}return C.getSnoovatarUrl(e,n(this,g))}getCommentById(e){return Q.getById(ye(e),n(this,g))}getComments(e){return Q.getComments(e,n(this,g))}getCommentsByUser(e){return Q.getCommentsByUser(e,n(this,g))}submitComment(e){return Q.submit({...e,id:ye(e.id)},n(this,g))}getControversialPosts(e){return G.getControversialPosts(e,n(this,g))}getTopPosts(e){return G.getTopPosts(e,n(this,g))}getHotPosts(e){return G.getHotPosts(e,n(this,g))}getNewPosts(e){return G.getNewPosts(e,n(this,g))}getRisingPosts(e){return G.getRisingPosts(e,n(this,g))}getPostsByUser(e){return G.getPostsByUser(e,n(this,g))}getCommentsAndPostsByUser(e){return C.getOverview(e,n(this,g))}getModerationLog(e){return Ws(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 ke.get(e,n(this,g))}deleteModNote(e){return ke.delete(e,n(this,g))}addModNote(e){let t={...e,redditId:e.redditId?ye(e.redditId):void 0};return ke.add(t,n(this,g))}addRemovalNote(e){return ke.addRemovalNote(e,n(this,g))}async sendPrivateMessage(e){return Rt.send(e,n(this,g))}async sendPrivateMessageAsSubreddit(e){return Rt.sendAsSubreddit(e,n(this,g))}async approve(e){if(Je(e))return Q.approve(e,n(this,g));if(Et(e))return G.approve(e,n(this,g));throw new Error("id must start with either t1_ or t3_")}async remove(e,t){if(Je(e))return Q.remove(e,t,n(this,g));if(Et(e))return G.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 Rt.getMessages(e,n(this,g))}markAllMessagesAsRead(){return Rt.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 Hd(e,n(this,g))}getVaultByUserId(e){return jd(ye(e),n(this,g))}getSubredditLeaderboard(e){return Ld(e,n(this,g))}getSubredditStyles(e){return _d(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,Br=new WeakMap,Dr=new WeakMap,Nr=new WeakMap;import{BitfieldOverflowBehavior as Zo,RedisKeyScope as Xo}from"@devvit/protos";function Lr(r){return r&&typeof r=="object"&&"message"in r&&r.message!==void 0&&typeof r.message=="string"?r.message.includes("redis: nil"):!1}var I,E,T,Qo=class{constructor(e,t,i){l(this,I);l(this,E);l(this,T);a(this,I,e),a(this,E,t),a(this,T,i)}async get(e){return await n(this,I).Get({key:e,transactionId:n(this,E)},n(this,T)),this}async multi(){await n(this,I).Multi(n(this,E),n(this,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 n(this,I).Set({key:e,value:t,nx:i?.nx===!0,xx:i?.xx===!0,expiration:s||0,transactionId:n(this,E)},n(this,T)),this}async del(...e){return await n(this,I).Del({keys:e,transactionId:n(this,E)},n(this,T)),this}async type(e){return await n(this,I).Type({key:e,transactionId:n(this,E)},n(this,T)),this}async exec(){let e=await n(this,I).Exec(n(this,E),n(this,T)),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,I).Discard(n(this,E),n(this,T))}async watch(...e){return await n(this,I).Watch({keys:e,transactionId:n(this,E)},n(this,T)),this}async unwatch(){return await n(this,I).Unwatch(n(this,E),n(this,T)),this}async getRange(e,t,i){return await n(this,I).GetRange({key:e,start:t,end:i,transactionId:n(this,E)},n(this,T)),this}async setRange(e,t,i){return await n(this,I).SetRange({key:e,offset:t,value:i,transactionId:n(this,E)},n(this,T)),this}async strlen(e){return this.strLen(e)}async strLen(e){return await n(this,I).Strlen({key:e,transactionId:n(this,E)},n(this,T)),this}async mget(e){return this.mGet(e)}async mGet(e){return await n(this,I).MGet({keys:e,transactionId:n(this,E)},n(this,T)),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,I).MSet({kv:t,transactionId:n(this,E)},n(this,T)),this}async incrBy(e,t){return await n(this,I).IncrBy({key:e,value:t,transactionId:n(this,E)},n(this,T)),this}async expire(e,t){return await n(this,I).Expire({key:e,seconds:t,transactionId:n(this,E)},n(this,T)),this}async expireTime(e){return await n(this,I).ExpireTime({key:e,transactionId:n(this,E)},n(this,T)),this}async zAdd(e,...t){return await n(this,I).ZAdd({key:e,members:t,transactionId:n(this,E)},n(this,T)),this}async zScore(e,t){return await n(this,I).ZScore({key:{key:e,transactionId:n(this,E)},member:t},n(this,T)),this}async zRank(e,t){return await n(this,I).ZRank({key:{key:e,transactionId:n(this,E)},member:t},n(this,T)),this}async zIncrBy(e,t,i){return await n(this,I).ZIncrBy({key:e,member:t,value:i,transactionId:n(this,E)},n(this,T)),this}async zScan(e,t,i,s){let o={key:e,cursor:t,pattern:i,count:s,transactionId:n(this,E)};return await n(this,I).ZScan(o,n(this,T)),this}async zCard(e){return await n(this,I).ZCard({key:e,transactionId:n(this,E)},n(this,T)),this}async zRange(e,t,i,s){let o={rev:!1,byLex:!1,byScore:!1,offset:0,count:1e3};if(s?.reverse&&(o.rev=s.reverse),s?.by==="lex"?o.byLex=!0:s?.by==="score"&&(o.byScore=!0),s?.limit)if(o.byLex||o.byScore)o.offset=s.limit.offset,o.count=s.limit.count;else throw new Error("zRange parsing error: 'limit' only allowed when 'options.by' is 'lex' or 'score'");return await n(this,I).ZRange({key:{key:e,transactionId:n(this,E)},start:t+"",stop:i+"",...o},n(this,T)),this}async zRem(e,t){return await n(this,I).ZRem({key:{key:e,transactionId:n(this,E)},members:t},n(this,T)),this}async zRemRangeByLex(e,t,i){return await n(this,I).ZRemRangeByLex({key:{key:e,transactionId:n(this,E)},min:t,max:i},n(this,T)),this}async zRemRangeByRank(e,t,i){return await n(this,I).ZRemRangeByRank({key:{key:e,transactionId:n(this,E)},start:t,stop:i},n(this,T)),this}async zRemRangeByScore(e,t,i){return await n(this,I).ZRemRangeByScore({key:{key:e,transactionId:n(this,E)},min:t,max:i},n(this,T)),this}async hgetall(e){return this.hGetAll(e)}async hGetAll(e){return await n(this,I).HGetAll({key:e,transactionId:n(this,E)},n(this,T)),this}async hget(e,t){return this.hGet(e,t)}async hGet(e,t){return await n(this,I).HGet({key:e,field:t,transactionId:n(this,E)},n(this,T)),this}async hMGet(e,t){return await n(this,I).HMGet({key:e,fields:t,transactionId:n(this,E)},n(this,T)),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,I).HSet({key:e,fv:i,transactionId:n(this,E)},n(this,T)),this}async hincrby(e,t,i){return this.hIncrBy(e,t,i)}async hIncrBy(e,t,i){return await n(this,I).HIncrBy({key:e,field:t,value:i,transactionId:n(this,E)},n(this,T)),this}async hdel(e,t){return this.hDel(e,t)}async hDel(e,t){return await n(this,I).HDel({key:e,fields:t,transactionId:n(this,E)},n(this,T)),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,E)};return await n(this,I).HScan(o,n(this,T)),this}async hkeys(e){return this.hKeys(e)}async hKeys(e){return await n(this,I).HKeys({key:e,transactionId:n(this,E)},n(this,T)),this}async hlen(e){return this.hLen(e)}async hLen(e){return await n(this,I).HLen({key:e,transactionId:n(this,E)},n(this,T)),this}};I=new WeakMap,E=new WeakMap,T=new WeakMap;var w,bi,Yo=class Yo{constructor(e,t=void 0,i=Xo.INSTALLATION){l(this,w);l(this,bi);a(this,w,e),a(this,bi,t),this.scope=i,this.global=i===Xo.INSTALLATION?new Yo(n(this,w),n(this,bi),Xo.GLOBAL):this}get storage(){return n(this,bi)||u.redisPlugin}async watch(...e){let t=await this.storage.Watch({keys:e},n(this,w));return new Qo(this.storage,t,n(this,w))}async get(e){try{let t=await this.storage.Get({key:e,scope:this.scope},{...n(this,w),"throw-redis-nil":{values:["true"]}});return t!==null?t.value??void 0:t}catch(t){if(Lr(t))return;throw t}}async getBuffer(e){try{let t=await this.storage.GetBytes({key:e,scope:this.scope},{...n(this,w),"throw-redis-nil":{values:["true"]}});return t!==null?Buffer.from(t.value):t}catch(t){if(Lr(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,w))).value}async exists(...e){return(await this.storage.Exists({keys:e,scope:this.scope},n(this,w))).existingKeys}async del(...e){await this.storage.Del({keys:e,scope:this.scope},n(this,w))}async incrBy(e,t){return(await this.storage.IncrBy({key:e,value:t,scope:this.scope},n(this,w))).value}async getRange(e,t,i){let s=await this.storage.GetRange({key:e,start:t,end:i,scope:this.scope},n(this,w));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,w))).value}async strlen(e){return this.strLen(e)}async strLen(e){return(await this.storage.Strlen({key:e,scope:this.scope},n(this,w))).value}async expire(e,t){await this.storage.Expire({key:e,seconds:t,scope:this.scope},n(this,w))}async expireTime(e){return(await this.storage.ExpireTime({key:e,scope:this.scope},n(this,w))).value}async zAdd(e,...t){return(await this.storage.ZAdd({key:e,members:t,scope:this.scope},n(this,w))).value}async zRange(e,t,i,s){let o={rev:!1,byLex:!1,byScore:!1,offset:0,count:1e3};if(s?.reverse&&(o.rev=s.reverse),s?.by==="lex"?o.byLex=!0:s?.by==="score"?o.byScore=!0:(o.offset=0,o.count=0),s?.limit)if(o.byLex||o.byScore)o.offset=s.limit.offset,o.count=s.limit.count;else throw new Error("zRange parsing error: 'limit' only allowed when 'options.by' is 'lex' or 'score'");return(await this.storage.ZRange({key:{key:e},start:t+"",stop:i+"",...o,scope:this.scope},n(this,w))).members}async zRem(e,t){return(await this.storage.ZRem({key:{key:e},members:t,scope:this.scope},n(this,w))).value}async zRemRangeByLex(e,t,i){return(await this.storage.ZRemRangeByLex({key:{key:e},min:t,max:i,scope:this.scope},n(this,w))).value}async zRemRangeByRank(e,t,i){return(await this.storage.ZRemRangeByRank({key:{key:e},start:t,stop:i,scope:this.scope},n(this,w))).value}async zRemRangeByScore(e,t,i){return(await this.storage.ZRemRangeByScore({key:{key:e},min:t,max:i,scope:this.scope},n(this,w))).value}async zScore(e,t){try{let i=await this.storage.ZScore({key:{key:e},member:t,scope:this.scope},{...n(this,w),"throw-redis-nil":{values:["true"]}});return i!==null?i.value:i}catch(i){if(Lr(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,w),"throw-redis-nil":{values:["true"]}});return i!==null?i.value:i}catch(i){if(Lr(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,w));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,w));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,w))}async zCard(e){let t=await this.storage.ZCard({key:e,scope:this.scope},n(this,w));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,w))}async type(e){let t=await this.storage.Type({key:e,scope:this.scope},n(this,w));return t!==null?t.value:t}async rename(e,t){return(await this.storage.Rename({key:e,newKey:t,scope:this.scope},n(this,w))).result}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,w),"throw-redis-nil":{values:["true"]}});return i!==null?i.value??void 0:i}catch(i){if(Lr(i))return;throw i}}async hMGet(e,t){let i=await this.storage.HMGet({key:e,fields:t,scope:this.scope},n(this,w));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,w))).value}async hSetNX(e,t,i){return(await this.storage.HSetNX({key:e,field:t,value:i,scope:this.scope},n(this,w))).success}async hgetall(e){return this.hGetAll(e)}async hGetAll(e){let t=await this.storage.HGetAll({key:e,scope:this.scope},n(this,w));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,w))).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,w))}async hkeys(e){return this.hKeys(e)}async hKeys(e){let t=await this.storage.HKeys({key:e,scope:this.scope},n(this,w));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,w))).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:dm(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}};w=new WeakMap,bi=new WeakMap;var vi=Yo;function dm(r){let e=r.toLowerCase();switch(e){case"wrap":return Zo.BITFIELD_OVERFLOW_BEHAVIOR_WRAP;case"sat":return Zo.BITFIELD_OVERFLOW_BEHAVIOR_SAT;case"fail":return Zo.BITFIELD_OVERFLOW_BEHAVIOR_FAIL;default:throw Error(`unknown bitfield overflow behavior: ${e}`)}}var Ot,ki=class{constructor(e){l(this,Ot);a(this,Ot,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,Ot))).id}async cancelJob(e){await u.schedulerPlugin.Cancel({id:e},n(this,Ot))}async listJobs(){return(await u.schedulerPlugin.List({after:new Date(0),before:new Date(Date.now()+31536e7)},n(this,Ot))).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}))}};Ot=new WeakMap;import{FormFieldType as Js}from"@devvit/protos";var _r,Ci=class{constructor(e){l(this,_r);a(this,_r,e)}async get(e){return(await this.getAll())[e]}async getAll(){let t=await u.settingsPlugin.GetSettings({},n(this,_r));if(!t.installationSettings)throw new Error("Could not get installation settings");if(!t.appSettings)throw new Error("Could not get app settings");return lm(t),{...Vd(t.installationSettings.settings,u.installationSettings),...Vd(t.appSettings.settings,u.appSettings)}}};_r=new WeakMap;function lm(r){if(!r.appSettings)throw new Error("Could not get app settings");for(let[e,t]of Object.entries(r.appSettings.settings)){let i=u.appSettings?.find(s=>s.type!=="group"&&s.name===e);i&&(i.type==="boolean"&&t.fieldType===Js.STRING&&t.boolValue==null&&t.stringValue!=null?(t.fieldType=Js.BOOLEAN,t.boolValue=!!t.stringValue,delete t.stringValue):i.type==="number"&&t.fieldType===Js.STRING&&t.numberValue==null&&t.stringValue!=null&&(t.fieldType=Js.NUMBER,t.numberValue=Number(t.stringValue),delete t.stringValue))}}function Vd(r,e){let t=Object.keys(r).reduce((i,s)=>(i[s]=Go(r[s]),i),{});return e&&Wd(t,e),t}function Wd(r,e){for(let t of e)t.type==="group"?Wd(r,t.fields):!(t.name in r)&&"defaultValue"in t&&(r[t.name]=t.defaultValue)}import{EffectType as zs,ToastAppearance as Gd}from"@devvit/protos";var Xe,Pi,Hr,$s,qs=class{constructor(e){l(this,Xe,[]);l(this,Pi);l(this,Hr);l(this,$s,(e,t)=>{let i=t!==void 0?e:"",s=t!==void 0?t:e;n(this,Xe).push({type:zs.EFFECT_WEB_VIEW,webView:{postMessage:{webViewId:i,app:{message:s}}}})});a(this,Pi,e),a(this,Hr,{postMessage:n(this,$s)})}get webView(){return n(this,Hr)}showForm(e,t){let i=u.formDefinitions.get(e);if(!i&&n(this,Pi)){let d=n(this,Pi).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};Tt(s.fields),o.fields=Le(s.fields),n(this,Xe).push({type:zs.EFFECT_SHOW_FORM,showForm:{form:o}})}showToast(e){let t;e instanceof Object?t={text:e.text,appearance:e.appearance==="success"?Gd.SUCCESS:Gd.NEUTRAL}:t={text:e},n(this,Xe).push({type:zs.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,Xe).push({type:zs.EFFECT_NAVIGATE_TO_URL,navigateToUrl:{url:t}})}get __effects(){return n(this,Xe)}};Xe=new WeakMap,Pi=new WeakMap,Hr=new WeakMap,$s=new WeakMap;function Ce({metadata:r,ui:e,hooks:t,reconciler:i}){let s=new hi(r),o=new pi(r),d=new vi(r),c=Td(d,i?i.state:{}),m=new yi(r),y=new ki(r),v=new Ci(r),f=e?new qs(i):void 0,P=new gi(r),b=new ci,L=new fi(r),A=t&&i?bd(i):void 0,V=t&&i?yd(i):void 0,B=t&&i?fd(i):void 0,ni=t&&i?hd(i):void 0;return{modLog:s,kvStore:o,redis:d,reddit:m,scheduler:y,settings:v,media:P,assets:b,realtime:L,get useForm(){return B??(()=>{throw new Error("useForm() is unavailable")})},get cache(){return c??(()=>{throw new Error("cache() is unavailable")})},get useState(){return A??(()=>{throw new Error("useState() is unavailable")})},get useInterval(){return V??(()=>{throw new Error("useInterval() is unavailable")})},get useChannel(){return ni??(()=>{throw new Error("useChannel() is unavailable")})},get ui(){if(!f)throw new Error("ui client is not available");return f}}}var Jd={name:"@devvit/public-api",version:"0.11.15-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/metrics":"0.11.15-dev","@devvit/protos":"0.11.15-dev","@devvit/shared-types":"0.11.15-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.15-dev","@devvit/tsconfig":"0.11.15-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.8.3",vitest:"1.6.1"},publishConfig:{directory:"dist"},filesize:{"dist/public-api.min.js":{gzip:"62 KB",none:"217 KB"}},source:"./src/index.ts"};function se(r,e,t){let i=r[S.Subreddit]?.values[0];p(i,"subreddit is missing from Context");let s=r[S.SubredditName]?.values[0],o=r[S.AppUser]?.values[0],d=r[S.App]?.values[0],c=r[S.Version]?.values[0],m=r[S.User]?.values[0],y=cm(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:y,toJSON(){return{appAccountId:o,appName:d,appVersion:c,subredditId:i,subredditName:s,userId:m,postId:e,commentId:t,debug:y}}}}function cm(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[S.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[S.Debug]&&console.info(`[api] @devvit/public-api v${Jd.version} ${Object.entries(i).map(([s,o])=>`${s}=${o}`).join(" ")}`),{...i,metadata:r}}function zd(r){return r.flatMap(e=>e.type==="group"?zd(e.fields):e)}async function Ks(r,e,t){if(!e)throw new Error("Settings were not defined.");let i={success:!0,errors:{}},s=qe(r.fieldValues),o=zd(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(Ce({metadata:t}),se(t)),f=await y({value:m,isEditing:r.editing},v);f&&(i.success=!1,i.errors[c]=f)}})),mm.fromJSON(i)}async function hm(){if(!u.appSettings)throw new Error("App settings were not defined.");return gm.fromJSON({fields:{fields:Le(u.appSettings)}})}async function fm(r,e){return Ks(r,u.appSettings,e)}function qd(r){r.provides(pm),O("GetAppSettingsFields",hm),O("ValidateAppForm",fm)}import{CustomPostDefinition as Sm,RenderPostResponse as wm}from"@devvit/protos";import{BlockRenderEventType as pa,EffectType as dl}from"@devvit/protos";function Si(r){return r.__effects}function $d(){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 ma,BlockAvatarBackground as nl,BlockAvatarFacing as sl,BlockAvatarSize as Qe,BlockBorderWidth as Ys,BlockButtonAppearance as Ye,BlockButtonSize as na,BlockGap as eo,BlockHorizontalAlignment as sa,BlockIconSize as to,BlockImageResizeMode as jr,BlockPadding as Vr,BlockRadius as Wr,BlockSpacerShape as oa,BlockSpacerSize as io,BlockStackDirection as aa,BlockTextOutline as da,BlockTextOverflow as la,BlockTextSize as Fi,BlockTextStyle as ua,BlockTextWeight as ol,BlockType as Re,BlockVerticalAlignment as ca}from"@devvit/protos";var ea={"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 Kd={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"},Zd=r=>!!r.match(/^(#[0-9a-fA-F]{3,8}).*/),Xd=r=>r in ea,ta=r=>r in Kd,Qd=r=>!!r.match(/^rgba?\(.*/),Yd=r=>!!r.match(/^hsla?\(.*/),el=(r,e="light")=>{if(ta(r))return Zs(r);let i=ea[r];return typeof i=="string"?i:i[e]},Zs=r=>Kd[r]??r,tl=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),y=Math.round(m*255);d.push(y)}return`#${d.map(m=>m.toString(16).padStart(2,"0")).join("")}`};import{BlockStackDirection as Xs}from"@devvit/protos";var ia={stackParentLayout:{hasHeight:!0,hasWidth:!0,direction:Xs.UNRECOGNIZED,alignment:void 0}};function rl(r,e,t){if(!e)return{hasHeight:!1,hasWidth:!1};let{growDirection:i,stretchDirection:s}=ym(r?.grow,e.direction,e.alignment),o=t?.height?.value?.value||t?.height?.min?.value||il(2,i,s,e.hasHeight),d=t?.width?.value?.value||t?.width?.min?.value||il(1,i,s,e.hasWidth);return{hasHeight:!!o,hasWidth:!!d}}function il(r,e,t,i){return e===r&&i||t===r&&i}function ym(r,e,t){let i=e===Xs.STACK_VERTICAL||e===Xs.UNRECOGNIZED,s=e===Xs.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,y=0;return s&&m?y=2:i&&m&&(y=1),{growDirection:o,stretchDirection:y}}import{BlockSizeUnit as Mt,BlockStackDirection as Qs}from"@devvit/protos";function wi(r){if(r==null)return;if(typeof r=="number")return{value:r,unit:Mt.SIZE_UNIT_PERCENT};let e=r.match(/^(\d+(?:\.\d+)?)(px|%)?$/);if(e==null)return;let t=Mt.SIZE_UNIT_PERCENT;return e.at(2)==="px"&&(t=Mt.SIZE_UNIT_PIXELS),{value:Number.parseFloat(e[1]),unit:t}}function bm(r,e){return(r.width?.value?.unit===Mt.SIZE_UNIT_PERCENT||r.width?.min?.unit===Mt.SIZE_UNIT_PERCENT)&&(e.direction===Qs.STACK_HORIZONTAL||e.direction===Qs.STACK_DEPTH)&&(e.hasWidth||(r.width=void 0)),(r.height?.value?.unit===Mt.SIZE_UNIT_PERCENT||r.height?.min?.unit===Mt.SIZE_UNIT_PERCENT)&&(e.direction===Qs.STACK_VERTICAL||e.direction===Qs.STACK_DEPTH)&&(e.hasHeight||(r.height=void 0)),r}function ra(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:wi(r.width),min:wi(r.minWidth),max:wi(r.maxWidth)}:void 0,height:i?{value:wi(r.height),min:wi(r.minHeight),max:wi(r.maxHeight)}:void 0,grow:r.grow};return e.stackParentLayout&&(s=bm(s,e.stackParentLayout)),s}}}var al="data-",vm=new Set(["onPress","onMessage"]),km=new Map([["onPress",ma.ACTION_CLICK],["onMessage",ma.ACTION_WEBVIEW]]),Gr,xi=class{constructor(e=()=>{}){l(this,Gr);a(this,Gr,e)}createBlocksElementOrThrow({type:e,props:t,children:i}){let s=this.createBlocksElement({type:e,props:t,children:i},ia);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 Vr.PADDING_NONE;case"xsmall":return Vr.PADDING_XSMALL;case"small":return Vr.PADDING_SMALL;case"medium":return Vr.PADDING_MEDIUM;case"large":return Vr.PADDING_LARGE}}makeBlockRadius(e){switch(e){case"none":return Wr.RADIUS_NONE;case"small":return Wr.RADIUS_SMALL;case"medium":return Wr.RADIUS_MEDIUM;case"large":return Wr.RADIUS_LARGE;case"full":return Wr.RADIUS_FULL}}makeBlockGap(e){switch(e){case"none":return eo.GAP_NONE;case"small":return eo.GAP_SMALL;case"medium":return eo.GAP_MEDIUM;case"large":return eo.GAP_LARGE}}makeBlockAlignment(e){if(e===void 0)return;let t,i;if(e.includes("top")?t=ca.ALIGN_TOP:e.includes("middle")?t=ca.ALIGN_MIDDLE:e.includes("bottom")&&(t=ca.ALIGN_BOTTOM),e.includes("start")?i=sa.ALIGN_START:e.includes("center")?i=sa.ALIGN_CENTER:e.includes("end")&&(i=sa.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=Ys.BORDER_WIDTH_NONE;break;case"thin":o=Ys.BORDER_WIDTH_THIN;break;case"thick":o=Ys.BORDER_WIDTH_THICK;break;default:o=Ys.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 Fi.TEXT_SIZE_XSMALL;case"small":return Fi.TEXT_SIZE_SMALL;case"medium":return Fi.TEXT_SIZE_MEDIUM;case"large":return Fi.TEXT_SIZE_LARGE;case"xlarge":return Fi.TEXT_SIZE_XLARGE;case"xxlarge":return Fi.TEXT_SIZE_XXLARGE}}makeBlockTextStyle(e){switch(e){case"body":return ua.TEXT_STYLE_BODY;case"metadata":return ua.TEXT_STYLE_METADATA;case"heading":return ua.TEXT_STYLE_HEADING}}makeBlockTextOutline(e){switch(e){case"none":return da.TEXT_OUTLINE_NONE;case"thin":return da.TEXT_OUTLINE_THIN;case"thick":return da.TEXT_OUTLINE_THICK}}makeBlockTextWeight(e){switch(e){case"regular":return ol.TEXT_WEIGHT_REGULAR;case"bold":return ol.TEXT_WEIGHT_BOLD}}makeBlockTextOverflow(e){switch(e){case"clip":return la.TEXT_OVERFLOW_CLIP;case"ellipsis":return la.TEXT_OVERFLOW_ELLIPSE}return la.TEXT_OVERFLOW_ELLIPSE}makeBlockButtonAppearance(e){switch(e){case"secondary":return Ye.BUTTON_APPEARANCE_SECONDARY;case"primary":return Ye.BUTTON_APPEARANCE_PRIMARY;case"plain":return Ye.BUTTON_APPEARANCE_PLAIN;case"bordered":return Ye.BUTTON_APPEARANCE_BORDERED;case"media":return Ye.BUTTON_APPEARANCE_MEDIA;case"destructive":return Ye.BUTTON_APPEARANCE_DESTRUCTIVE;case"caution":return Ye.BUTTON_APPEARANCE_CAUTION;case"success":return Ye.BUTTON_APPEARANCE_SUCCESS}}makeBlockButtonSize(e){switch(e){case"small":return na.BUTTON_SIZE_SMALL;case"medium":return na.BUTTON_SIZE_MEDIUM;case"large":return na.BUTTON_SIZE_LARGE}}makeBlockImageResizeMode(e){switch(e){case"none":return jr.IMAGE_RESIZE_NONE;case"fit":return jr.IMAGE_RESIZE_FIT;case"fill":return jr.IMAGE_RESIZE_FILL;case"cover":return jr.IMAGE_RESIZE_COVER;case"scale-down":return jr.IMAGE_RESIZE_SCALE_DOWN}}makeBlockSpacerSize(e){switch(e){case"xsmall":return io.SPACER_XSMALL;case"small":return io.SPACER_SMALL;case"medium":return io.SPACER_MEDIUM;case"large":return io.SPACER_LARGE}}makeBlockSpacerShape(e){switch(e){case"invisible":return oa.SPACER_INVISIBLE;case"thin":return oa.SPACER_THIN;case"square":return oa.SPACER_SQUARE}}makeBlockIconSize(e){switch(e){case"xsmall":return to.ICON_SIZE_XSMALL;case"small":return to.ICON_SIZE_SMALL;case"medium":return to.ICON_SIZE_MEDIUM;case"large":return to.ICON_SIZE_LARGE}}makeBlockAvatarSize(e){switch(e){case"xxsmall":return Qe.AVATAR_SIZE_XXSMALL;case"xsmall":return Qe.AVATAR_SIZE_XSMALL;case"small":return Qe.AVATAR_SIZE_SMALL;case"medium":return Qe.AVATAR_SIZE_MEDIUM;case"large":return Qe.AVATAR_SIZE_LARGE;case"xlarge":return Qe.AVATAR_SIZE_XXLARGE;case"xxlarge":return Qe.AVATAR_SIZE_XXLARGE;case"xxxlarge":return Qe.AVATAR_SIZE_XXXLARGE}}makeBlockAvatarFacing(e){switch(e){case"left":return sl.AVATAR_FACING_LEFT;case"right":return sl.AVATAR_FACING_RIGHT}}makeBlockAvatarBackground(e){switch(e){case"dark":return nl.AVATAR_BG_DARK;case"light":return nl.AVATAR_BG_LIGHT}}getDataSet(e){return Object.keys(e).filter(t=>t.startsWith(al)).reduce((t,i)=>(t[i.substring(al.length)]=e[i],t),{})}makeActions(e,t){let i=[],s=this.getDataSet(t);return vm.forEach(o=>{if(o in t){let d=t[o];i.push({type:km.get(o)??ma.UNRECOGNIZED,id:d.toString(),data:s})}}),i}blockColorToHex(e,t="light"){if(e)return e=e.toLowerCase(),Zd(e)?e:Xd(e)?el(e,t):ta(e)?Zs(e):Qd(e)?tl(e):Yd(e)?e:(console.warn(`Could not parse color: ${e}.`),Zs("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,Gr).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,ia))}wrapRoot(e,t){return this.makeBlock(Re.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=ra(t,i),m=rl(t,i.stackParentLayout,c);return this.makeBlock(Re.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(aa.STACK_HORIZONTAL,e,t,i)}makeVStack(e,t,...i){return this.makeStackBlock(aa.STACK_VERTICAL,e,t,i)}makeZStack(e,t,...i){return this.makeStackBlock(aa.STACK_DEPTH,e,t,i)}makeText(e,t,...i){let s=this.getThemedColors(e?.color,e?.lightColor,e?.darkColor);return this.makeBlock(Re.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(Re.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(Re.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(Re.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(Re.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(Re.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(Re.BLOCK_WEBVIEW,e,t,{webviewConfig:{url:this.resolveAssetUrl(e.url,{webView:!0})}})}makeBlock(e,t,i,s){return{type:e,sizes:ra(t,i),config:s,actions:(t&&this.makeActions(e,t))??[],id:t?.id,key:t?.key}}ensureRootBlock(e){let t;if(e.type===Re.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}};Gr=new WeakMap;function ll(r){if(typeof r=="string")throw new Error("Root element cannot be a string")}var ul=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+=ul(i);return e+=`</${r.type}>`,e};function Cm(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+=Cm(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 Pe,cl,Jr,ga,zr,_e=class{constructor(e,t,i,s,o){l(this,Pe);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 xi(()=>this.assets);this.effects=[];l(this,zr,!1);this.component=e,this.event=t,this.state={__renderState:{},...i},this.metadata=s,this.state.__realtimeChannels&&(this.realtimeChannels=this.state.__realtimeChannels);let d=Ce({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,Pe,Jr).call(this),t={type:this.component,props:e,children:[]},i=await this.processBlock(t);if(ll(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,Pe,cl).call(this)}async buildBlocksUI(){let e=h(this,Pe,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 ll(i),(u.debug.emitSnapshots||e.debug.emitSnapshots)&&console.debug(Pm(ul(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=$d(),i=[]){let s=e;if(typeof s.type=="string"){let c=[];for(let f=0;f<s.children.length;f++){let P=s.children[f];P!=null&&c.push(await this.processBlock(P,t,[...i,`${s.type}.${f}`]))}let m=c.flat(),y=h(this,Pe,ga).call(this,m);return await this.processProps(s),{type:s.type,props:s.props,children:y}}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),y={...h(this,Pe,Jr).call(this),...s.props,children:m},v;for(;v===void 0;)try{v=await s.type(y,h(this,Pe,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,[...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===pa.RENDER_INITIAL:!1}get isUserActionRender(){return this.event?this.event.type===pa.RENDER_USER_ACTION:!1}get isEffectRender(){return this.event?this.event.type===pa.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,zr)||(a(this,zr,!0),this.effects.push({type:dl.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:dl.EFFECT_REALTIME_SUB,realtimeSubscriptions:{subscriptionIds:this.realtimeChannels}}]:[]}getEffects(){return[...Si(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}:{}}}};Pe=new WeakSet,cl=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[S.Timezone]?.values[0],locale:this.metadata[S.Language]?.values[0],dimensions:this.dimensions},...this.hooks};return e.debug.effects=this,e},ga=function(e){let t=[];for(let i of e)typeof i=="string"?t.push(i):i.type==="__fragment"?t.push(...h(this,Pe,ga).call(this,i.children)):t.push(i);return t},zr=new WeakMap;async function Fm(r,e){let t=u.customPostType;if(!t)throw new Error("Custom post type not registered");let i=new _e((o,d)=>t.render(d),r.blocks,r.state,e,r.dimensions),s=await i.render();return wm.fromJSON({state:i.state,blocks:{ui:s},effects:i.getEffects()})}function ml(r){r.provides(Sm),O("RenderPost",Fm)}import{GetFieldsResponse as xm,InstallationSettingsDefinition as Am}from"@devvit/protos";async function Im(){if(!u.installationSettings)throw new Error("Installation settings were not defined.");return xm.fromJSON({fields:{fields:Le(u.installationSettings)}})}async function Em(r,e){return Ks(r,u.installationSettings,e)}function pl(r){r.provides(Am),O("GetSettingsFields",Im),O("ValidateForm",Em)}import{ContextActionDefinition as Tm,ContextActionList as Rm,ContextActionResponse as Om}from"@devvit/protos";function ha(r){let e=r.debug.metadata[S.User].values[0];if(!e)throw new Error("User missing from context");return e}function fa(r){let e=r.debug.metadata[S.Subreddit].values[0];if(!e)throw new Error("Subreddit missing from context");return e}async function gl(r,e){let t=ha(r),i=fa(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=qr(e.actionId);if(!m)throw new Error("Action not found");let y=!!m.forUserType?.includes("moderator");if(y&&!hl(r))throw new Error("User is not a moderator");let v={needsModCheck:y};await r.redis.set(`${t}${i}${c}${e.actionId}`,JSON.stringify(v)),await r.redis.expire(`${t}${i}${c}${e.actionId}`,600)}async function hl(r){let e=ha(r),t=fa(r),i=await r.reddit.getSubredditInfoById(t);return!!(await r.reddit.getModerators({subredditName:i.name}).all()).find(o=>o.id===e)}async function fl(r,e){let t=ha(r),i=fa(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 hl(r))throw new Error("User is not a moderator: "+t+"; "+i)}var yl=r=>`menuItem.${r}`;function qr(r){return u.menuItems.find((e,t)=>yl(t)===r)}async function Mm(r,e){let t=u.menuItems;if(!t.length)throw new Error("No menu items registered.");let i=t.map((s,o)=>({actionId:yl(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 Rm.fromJSON({actions:i})}async function Um(r,e){let t=qr(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(Ce({ui:!0,metadata:e}),se(e,s,i),{uiEnvironment:{timezone:e[S.Timezone]?.values[0],locale:e[S.Language]?.values[0]}});return await gl(m,r),await t.onPress(c,m),Om.fromJSON({effects:Si(m.ui)})}function bl(r){r.provides(Tm),O("GetActions",Mm),O("OnAction",Um)}function Se(r){return r?r===!0?!0:r.enabled:!1}import{SchedulerHandlerDefinition as Bm}from"@devvit/protos";async function Dm(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(Ce({metadata:e}),se(e));return await i(s,o),{}}function vl(r){r.provides(Bm),O("HandleScheduledAction",Dm)}import{OnAppInstallDefinition as Nm,OnAppUpgradeDefinition as Lm,OnAutomoderatorFilterCommentDefinition as _m,OnAutomoderatorFilterPostDefinition as Hm,OnCommentCreateDefinition as jm,OnCommentDeleteDefinition as Vm,OnCommentReportDefinition as Wm,OnCommentSubmitDefinition as Gm,OnCommentUpdateDefinition as Jm,OnModActionDefinition as zm,OnModMailDefinition as qm,OnPostCreateDefinition as $m,OnPostDeleteDefinition as Km,OnPostFlairUpdateDefinition as Zm,OnPostNsfwUpdateDefinition as Xm,OnPostReportDefinition as Qm,OnPostSpoilerUpdateDefinition as Ym,OnPostSubmitDefinition as ep,OnPostUpdateDefinition as tp}from"@devvit/protos";var et;(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})(et||(et={}));function $(r,e){return p(e),async(t,i)=>{let s={...t,type:r},o=Object.assign(Ce({metadata:i}),se(i)),d=await Promise.allSettled(e.map(m=>m(s,o))),c=ip(d);if(c)throw c.err;return{}}}function kl(r){for(let e of u.triggerOnEventHandlers.keys())switch(e){case"PostSubmit":r.provides(ep),O("OnPostSubmit",$("PostSubmit",u.triggerOnEventHandlers.get(e)));break;case"PostCreate":r.provides($m),O("OnPostCreate",$("PostCreate",u.triggerOnEventHandlers.get(e)));break;case"PostUpdate":r.provides(tp),O("OnPostUpdate",$("PostUpdate",u.triggerOnEventHandlers.get(e)));break;case"PostReport":r.provides(Qm),O("OnPostReport",$("PostReport",u.triggerOnEventHandlers.get(e)));break;case"PostDelete":r.provides(Km),O("OnPostDelete",$("PostDelete",u.triggerOnEventHandlers.get(e)));break;case"PostFlairUpdate":r.provides(Zm),O("OnPostFlairUpdate",$("PostFlairUpdate",u.triggerOnEventHandlers.get(e)));break;case"CommentSubmit":r.provides(Gm),O("OnCommentSubmit",$("CommentSubmit",u.triggerOnEventHandlers.get(e)));break;case"CommentCreate":r.provides(jm),O("OnCommentCreate",$("CommentCreate",u.triggerOnEventHandlers.get(e)));break;case"CommentUpdate":r.provides(Jm),O("OnCommentUpdate",$("CommentUpdate",u.triggerOnEventHandlers.get(e)));break;case"CommentReport":r.provides(Wm),O("OnCommentReport",$("CommentReport",u.triggerOnEventHandlers.get(e)));break;case"CommentDelete":r.provides(Vm),O("OnCommentDelete",$("CommentDelete",u.triggerOnEventHandlers.get(e)));break;case"AppInstall":r.provides(Nm),O("OnAppInstall",$("AppInstall",u.triggerOnEventHandlers.get(e)));break;case"AppUpgrade":r.provides(Lm),O("OnAppUpgrade",$("AppUpgrade",u.triggerOnEventHandlers.get(e)));break;case"ModAction":r.provides(zm),O("OnModAction",$("ModAction",u.triggerOnEventHandlers.get(e)));break;case"ModMail":r.provides(qm),O("OnModMail",$("ModMail",u.triggerOnEventHandlers.get(e)));break;case"PostNsfwUpdate":r.provides(Xm),O("OnPostNsfwUpdate",$("PostNsfwUpdate",u.triggerOnEventHandlers.get(e)));break;case"PostSpoilerUpdate":r.provides(Ym),O("OnPostSpoilerUpdate",$("PostSpoilerUpdate",u.triggerOnEventHandlers.get(e)));break;case"AutomoderatorFilterPost":r.provides(Hm),O("OnAutomoderatorFilterPost",$("AutomoderatorFilterPost",u.triggerOnEventHandlers.get(e)));break;case"AutomoderatorFilterComment":r.provides(_m),O("OnAutomoderatorFilterComment",$("AutomoderatorFilterComment",u.triggerOnEventHandlers.get(e)));break;default:throw new Error(`Unknown trigger event: ${e}`)}}function ip(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=>et.caughtToString(t)).join(`
|
|
3
|
+
`))}}import{EffectType as xp,HandleUIEventResponse as va,UIEventHandlerDefinition as Ap}from"@devvit/protos";var Nl=dd(Ol(),1);function Ml(r){return r?.constructor===Object}function Ut(r,e){return Object.is(r,e)?!0:typeof r!=typeof e?!1:Array.isArray(r)&&Array.isArray(e)?Ul(r,e):r instanceof Date&&e instanceof Date?r.getTime()===e.getTime():r instanceof RegExp&&e instanceof RegExp?r.toString()===e.toString():Ml(r)&&Ml(e)?Fp(r,e):r instanceof ArrayBuffer&&e instanceof ArrayBuffer?Bl(new DataView(r),new DataView(e)):r instanceof DataView&&e instanceof DataView?Bl(r,e):Dl(r)&&Dl(e)?r.byteLength!==e.byteLength?!1:Ul(r,e):!1}function Fp(r,e){let t=Object.keys(r),i=Object.keys(e);if(!Ut(t,i))return!1;for(let s of t)if(!Ut(r[s],e[s]))return!1;return!0}function Ul(r,e){return r.length!==e.length?!1:r.every((t,i)=>Ut(t,e[i]))}function Bl(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 Dl(r){return ArrayBuffer.isView(r)&&!(r instanceof DataView)}async function Ip(r,e){let t=r.state??{},i=(0,Nl.default)(t),s=Ce({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 b=new _e((L,A)=>u.customPostType?.render(A)??null,r.event,r.state,e,void 0);return await b.reconcile(),va.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(i.__contextAction){let{actionId:b,thingId:L}=i.__contextAction,A=qr(b);A?.location==="post"?v=L:A?.location==="comment"&&(f=L)}let P=Object.assign(s,se(e,v,f),{uiEnvironment:{timezone:e[S.Timezone]?.values[0],locale:e[S.Language]?.values[0]}});await fl(P,r),await y.onSubmit({values:qe(r.event.formSubmitted.results)},P)}else if(r.event?.realtimeEvent){if(u.customPostType){let m=new _e((y,v)=>u.customPostType?.render(v)??null,r.event,r.state,e,void 0);return await m.reconcile(),va.fromJSON({state:m.state,effects:m.getEffects()})}}else if(r.event?.toastAction)throw new Error("Toast actions not yet implemented");let o=!Ut(t,i),d=Si(s.ui),c=o?[...d,{type:xp.EFFECT_RERENDER_UI,rerenderUi:{delaySeconds:0}}]:d;return va.fromJSON({state:i,effects:c})}function Ll(r){r.provides(Ap),O("HandleUIEvent",Ip)}import{CustomPostDefinition as yo,UIResponse as cu}from"@devvit/protos";import{UIEventScope as Dp}from"@devvit/protos";var ka="ServerCallRequired";function ro(r){return r?.message===ka}var wa={now(){return new Date}};function _l(r){return`__autocache__${r}`}function Hl(r){return`__lock__${r}`}var Ep=300,Tp=1e3,no=5e3,Ca=3,jl=.1,Vl=1e3,Rp=3e4;function Wl(r){if(r.error)throw new Error(r.error);return r.value}var tt,it,we,Ai,q,Gl,Jl,zl,Pa,ql,$l,Sa,Kl,so=class{constructor(e,t,i=wa){l(this,q);l(this,tt);l(this,it,{});l(this,we);l(this,Ai);a(this,tt,e),a(this,Ai,t),a(this,we,i)}async cache(e,t){var d;(d=n(this,Ai)).__cache??(d.__cache={}),a(this,it,n(this,Ai).__cache),h(this,q,Kl).call(this,t);let i=h(this,q,Gl).call(this,t.key);if(i!==void 0)return i;let s=await h(this,q,Sa).call(this,t.key),o=await h(this,q,Jl).call(this,t,s,e);return Wl(o)}};tt=new WeakMap,it=new WeakMap,we=new WeakMap,Ai=new WeakMap,q=new WeakSet,Gl=function(e){let t=n(this,it)[e];if(t){let i=n(this,we).now().getTime(),s=t?.error&&t?.errorTime&&t.errorCount<Ca&&Math.random()<jl&&t.errorTime+Vl<i;if(t?.expires&&t.expires<i&&t.checkedAt+Vl<i||s){delete n(this,it)[e];return}else return Wl(t)}},Jl=async function(e,t,i){let s=t?.expires,o=s?h(this,q,$l).call(this,s):1;return!t||t?.error&&t.errorCount<Ca&&jl>Math.random()||o>Math.random()?h(this,q,zl).call(this,e,t,i):t},zl=async function(e,t,i){let s=Hl(e.key),o=n(this,we).now().getTime(),d=new Date(o+e.ttl/2);if(await n(this,tt).set(s,"1",{expiration:d,nx:!0}))return h(this,q,ql).call(this,e.key,t,i,e.ttl);if(t)return t;{let m=n(this,we).now();return h(this,q,Pa).call(this,m,e.key,e.ttl)}},Pa=async function(e,t,i){let s=Math.min(i,Tp),o=await h(this,q,Sa).call(this,t);if(o)return o;if(n(this,we).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,Ep)),h(this,q,Pa).call(this,e,t,i)},ql=async function(e,t,i,s){let o=n(this,we).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,we).now().getTime(),t.errorCount++}return n(this,it)[e]=t,await n(this,tt).set(_l(e),JSON.stringify(t),{expiration:new Date(o+Rp)}),t.error&&t.errorCount<Ca&&await n(this,tt).del(Hl(e)),t},$l=function(e){let t=n(this,we).now().getTime(),i=e-t;return i<0?1:i<1e3?.1:i<2e3?.01:i<3e3?.001:0},Sa=async function(e){let t=await n(this,tt).get(_l(e));if(t){let i=JSON.parse(t);return i.checkedAt=n(this,we).now().getTime(),n(this,it)[e]=i,i}},Kl=function(e){e.ttl<no&&(console.warn(`Cache TTL cannot be less than ${no} milliseconds! Updating ttl value of ${e.ttl} to ${no}.`),e.ttl=no)};function Zl(r,e,t=wa){let i=new so(r,e,t);return i.cache.bind(i)}import{EffectType as oo,ToastAppearance as Yl}from"@devvit/protos";function Xl(r){let e=r.match(/form\.hook\.(.+)\.0/);if(e?.[1])return e[1]}var Fa=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(qe(s.formSubmitted.results))}}};function xa(r,e){let t=me({namespace:"useForm",initializer:i=>new Fa(i,r,e)});return Op({id:t.hookId})}function Op(r){return`form.hook.${r.id}.0`}function Ql(r,e){let t=Xl(e);return r.getHook({id:t})}var He,lo,$r,uo,ao=class{constructor(e){l(this,He);l(this,lo,0);l(this,$r);l(this,uo,(e,t)=>{let i=t!==void 0?e:"",s=t!==void 0?t:e;n(this,He).emitEffect(`postMessage${ld(this,lo)._++}`,{type:oo.EFFECT_WEB_VIEW,webView:{postMessage:{webViewId:i,app:{message:s,jsonString:JSON.stringify(s)}}}})});a(this,He,e),a(this,$r,{postMessage:n(this,uo)})}get webView(){return n(this,$r)}showForm(e,t){let i=Ql(n(this,He),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};Tt(s.fields),o.fields=Le(s.fields),n(this,He).emitEffect(e,{type:oo.EFFECT_SHOW_FORM,showForm:{form:o}})}showToast(e){let t;e instanceof Object?t={text:e.text,appearance:e.appearance==="success"?Yl.SUCCESS:Yl.NEUTRAL}:t={text:e},n(this,He).emitEffect(e.toString(),{type:oo.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,He).emitEffect(t,{type:oo.EFFECT_NAVIGATE_TO_URL,navigateToUrl:{url:t}})}};He=new WeakMap,lo=new WeakMap,$r=new WeakMap,uo=new WeakMap;import{EffectType as Mp,RealtimeSubscriptionStatus as eu}from"@devvit/protos";var rt,Oe,nt,Bt,Kr,Ia,co=class co{constructor(e,t){l(this,Kr);l(this,rt);l(this,Oe);l(this,nt);l(this,Bt);a(this,rt,t.context),a(this,Oe,!!t.context._devvitContext?.debug.realtime),a(this,Bt,e),a(this,nt,t.invalidate);let i=t.context.meta[S.App]?.values[0];if(!i)throw Error("useChannel missing app ID metadata");let s=t.context.meta[S.Installation]?.values[0];if(!s)throw Error("useChannel missing install ID from metadata");let o=`${i}:${s}:${e.name}`;if(Object.values(n(this,rt)._hooks).filter(c=>c instanceof co).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 eu.REALTIME_SUBSCRIBED:n(this,Oe)&&console.debug(`[realtime] "${this.state.channel}" connected`),this.state.connected=!0,n(this,nt).call(this),await n(this,Bt).onSubscribed?.();break;case eu.REALTIME_UNSUBSCRIBED:n(this,Oe)&&console.debug(`[realtime] "${this.state.channel}" disconnected`),this.state.connected=!1,n(this,nt).call(this),await n(this,Bt).onUnsubscribed?.();break;default:n(this,Oe)&&console.debug(`[realtime] "${this.state.channel}" received message: ${JSON.stringify(e,void 0,2)}`),n(this,Bt).onMessage(t.event?.data?.msg);break}}async send(e){if(n(this,Oe)&&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,rt).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,Oe)&&console.debug(`[realtime] "${this.state.channel}" subscribed`),this.state.subscribed=!0,n(this,nt).call(this),h(this,Kr,Ia).call(this))}unsubscribe(){this.state.subscribed&&(n(this,Oe)&&console.debug(`[realtime] "${this.state.channel}" unsubscribed`),this.state.subscribed=!1,n(this,nt).call(this),h(this,Kr,Ia).call(this))}};rt=new WeakMap,Oe=new WeakMap,nt=new WeakMap,Bt=new WeakMap,Kr=new WeakSet,Ia=function(){let e=Object.values(n(this,rt)._hooks).filter(t=>t instanceof co&&t.state.subscribed).map(t=>t.state.channel);n(this,rt).emitEffect(this.state.channel,{type:Mp.EFFECT_REALTIME_SUB,realtimeSubscriptions:{subscriptionIds:e}})};var Aa=co;function Ea(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 Aa(r,t)})}import{EffectType as Ta}from"@devvit/protos";function tu(r){return typeof r=="object"&&r!==null&&"__deleted"in r}var Dt,st,Ii=class Ii{constructor(e,t){l(this,Dt);this._segments=[];l(this,st,{});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,Dt,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,Dt).__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,st)).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,st)}set _hooks(e){this._prevHooks=n(this,st),a(this,st,e)}get _state(){return n(this,Dt)}set _state(e){a(this,Dt,e)}push(e){this._segments.push({...e,next:0})}pop(){this._segments.pop()}addUndeliveredEventHandler(e,t){this._undeliveredHandlers[e]=t}addGlobalUndeliveredEventHandler(e,t){Ii.addGlobalUndeliveredEventHandler(e,t)}getHook(e){return n(this,st)[e.id]}static addGlobalUndeliveredEventHandler(e,t){Ii._staticUndeliveredHandlers[e]=t}async handleUndeliveredEvent(e){let t={...Ii._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()}}};Dt=new WeakMap,st=new WeakMap,Ii._staticUndeliveredHandlers={};var Ei=Ii;var ot={};Ei.addGlobalUndeliveredEventHandler("intervals",async(r,e)=>{r.timer&&r.hook&&(delete ot[r.hook],e.emitEffect("timers",{type:Ta.EFFECT_SET_INTERVALS,interval:{intervals:ot}}))});var at,Ti,Zr,Ri,Ra=class{constructor(e,t,i){l(this,at);l(this,Ti);l(this,Zr);l(this,Ri);this.state={duration:{seconds:0,nanos:0},running:!1};a(this,Ti,i.invalidate),a(this,at,i.hookId),a(this,Zr,e),a(this,Ri,i.context);let s=Math.floor(t/1e3),o=t%1e3*1e6;this.state.duration={seconds:s,nanos:o}}onStateLoaded(){this.state.running?ot[n(this,at)]={duration:this.state.duration}:delete ot[n(this,at)]}async onUIEvent(e){await n(this,Zr).call(this)}start(){ot[n(this,at)]={duration:this.state.duration},this.state.running=!0,n(this,Ti).call(this),n(this,Ri).emitEffect("timers",{type:Ta.EFFECT_SET_INTERVALS,interval:{intervals:ot}})}stop(){delete ot[n(this,at)],this.state.running=!1,n(this,Ti).call(this),n(this,Ri).emitEffect("timers",{type:Ta.EFFECT_SET_INTERVALS,interval:{intervals:ot}})}};at=new WeakMap,Ti=new WeakMap,Zr=new WeakMap,Ri=new WeakMap;function Oa(r,e){let t=me({namespace:"useInterval",initializer:i=>new Ra(r,e,i)});return{start:()=>t.start(),stop:()=>t.stop()}}import{UIEventScope as Bp}from"@devvit/protos";var Nt=class extends Error{};import{UIEventScope as iu}from"@devvit/protos";function Ua(r){if(r instanceof Error){if(r.message===ka)throw r;return console.error(r),{message:r.message,details:r.stack??""}}else return console.error(r),{message:"Unknown error",details:et.caughtToString(r)}}var Ae,Me,Oi,Xr,Mi,Ma=class{constructor(e,t,i){l(this,Ae);l(this,Me);l(this,Oi);l(this,Xr);l(this,Mi);a(this,Ae,!!i.context.devvitContext.debug.useAsync),n(this,Ae)&&console.debug("[useAsync] v1",t),this.state={data:null,load_state:"initial",error:null,depends:null},a(this,Me,i.hookId),this.initializer=e,a(this,Oi,i.invalidate),a(this,Xr,i.context),this.localDepends=t.depends??null,a(this,Mi,t)}onStateLoaded(){if(n(this,Ae)&&console.debug("[useAsync] async onLoad ",n(this,Me),this.state),n(this,Ae)&&console.debug("[useAsync] async onLoad have ",this.localDepends,"and",this.state.depends),!Ut(this.localDepends,this.state.depends)||this.state.load_state==="initial"){n(this,Ae)&&console.debug("[useAsync] attempting to resolve for hookId",n(this,Me)),this.state.load_state="loading",this.state.depends=this.localDepends,n(this,Oi).call(this);let e={scope:iu.ALL,hook:n(this,Me),async:!0,asyncRequest:{requestId:n(this,Me)+"-"+JSON.stringify(this.state.depends)}};n(this,Ae)&&console.debug("[useAsync] onLoad requeue"),n(this,Xr).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=Ua(o)}let s={scope:iu.ALL,asyncResponse:i,hook:n(this,Me)};n(this,Ae)&&console.debug("[useAsync] onReq requeue"),t.addToRequeueEvents(s)}else if(e.asyncResponse){let i=n(this,Me)+"-"+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,Mi).finally&&await n(this,Mi).finally(this.state.data,this.state.error?new Error(this.state.error?.message??"Unknown error"):null),n(this,Oi).call(this)):n(this,Ae)&&console.debug("[useAsync] onResp skip, stale event",e.asyncResponse.requestId," !== ",i)}else throw new Error("Unknown event type")}};Ae=new WeakMap,Me=new WeakMap,Oi=new WeakMap,Xr=new WeakMap,Mi=new WeakMap;function Up(r,e={}){let t=me({namespace:"useAsync",initializer:i=>new Ma(r,e,i)});return{data:t.state.data,error:t.state.error,loading:t.state.load_state==="loading"}}var je,Ui,Lt,dt,Ba=class{constructor(e,t){this.state={value:null,load_state:"initial",error:null};l(this,je);l(this,Ui);l(this,Lt);l(this,dt);a(this,Lt,e),a(this,dt,t.hookId),a(this,je,t.invalidate),a(this,Ui,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=Ua(e)}n(this,je).call(this)}else console.warn(`Invalid state for hook (${n(this,dt)}):`,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,je).call(this)}onStateLoaded(){if(this._promise=n(this,Ui)._prevHooks[n(this,dt)]?._promise,this.state.load_state==="loading")throw new Nt;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,Lt)instanceof Function?n(this,Lt).call(this):n(this,Lt)}catch(t){console.log("error in loading async",t),this.state.load_state="error",n(this,je).call(this);return}if(e instanceof Promise){this._promise=e,this.state.load_state="loading";let t={scope:Bp.ALL,asyncRequest:{requestId:n(this,dt)},hook:n(this,dt)};throw n(this,Ui).addToRequeueEvents(t),n(this,je).call(this),new Nt}else this.state.value=e,this.state.load_state="loaded";n(this,je).call(this)}}};je=new WeakMap,Ui=new WeakMap,Lt=new WeakMap,dt=new WeakMap;function Da(r){let e=me({namespace:"useState",initializer:t=>new Ba(r,t)});return[e.state.value,e.setter.bind(e)]}var mo=class{buildContext(e,t,i){let s=new hi(i),o=new pi(i),d=new vi(i),c=new yi(i),m=new ki(i),y=new Ci(i),v=new ao(e),f=new gi(i),P=new ci,b=new fi(i),L=Zl(d,e._state),A={modLog:s,kvStore:o,redis:d,reddit:c,scheduler:m,settings:y,media:f,assets:P,realtime:b,ui:v,useState:Da,useChannel:Ea,useInterval:Oa,useForm:xa,cache:L,dimensions:t.env?.dimensions,uiEnvironment:{timezone:i[S.Timezone]?.values[0],locale:i[S.Language]?.values[0],dimensions:t.env?.dimensions,colorScheme:t.env?.colorScheme}},V=se(i,t.props?.postId);return V.debug.effects=e,{...V,...A}}};var pe=null;function ru(r){return JSON.parse(JSON.stringify(r))}function Np(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.");Np(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||tu(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 Lp=null,po=128,Bi,fo,Qr,F,oe,go,nu,Na,su,La,_a,ho,Ha,ou,_t=class{constructor(e){l(this,F);l(this,Bi);l(this,fo,new mo);l(this,Qr,new xi(()=>this._latestRenderContext?.devvitContext?.assets));this._latestRenderContext=null;n(this,F,oe)&&console.debug("[blocks] BlocksHandler v1"),a(this,Bi,e),Lp=this}async handle(e,t){let i=new Ei(e,t),s=n(this,fo).buildContext(i,e,t);i.devvitContext=s;let o,d=e.events.length-po,c=e.events;if(d>0){c=[];{let A=0;for(let V of e.events)A<d&&V.realtimeEvent?A++:c.push(V)}for(;c.length>po;)c.shift();console.warn(`dropped ${d} events`)}let y=!c.length||c.some(A=>!A.async),v=c.some(A=>A.blocking),f,P,b=[...c];c.length===0&&c.push({scope:Dp.ALL}),n(this,F,oe)&&console.debug("[blocks] starting processing events");let L=0;for(;c.length>0;){if(L++>po)throw new Error(`Exceeded maximum iterations of ${po}`);n(this,F,oe)&&console.debug("[blocks] processing events loop iteration",c.length);let A=[];if(!c[0].async)A.push(c.shift());else for(;c[0]?.async;)A.push(c.shift());if(!A.length)throw Error("batch must have at least one event");try{if(A[0].async){let B=ru(i._state);await h(this,F,nu).call(this,i,...A),i._state=B}else await h(this,F,su).call(this,i,...A)}catch(B){if(!ro(B))throw B;if(n(this,F,oe)&&console.debug("[blocks] caught in handler",B),i._latestRenderContent=void 0,P){i._state=P._state,i._changed=f,i._effects=P._effects;let ni=b.map(nd=>{let sd={...nd};return sd.retry=!0,sd});i.addToRequeueEvents(...ni);break}else throw ro(B)||console.error("[blocks] unhandled error in handler",B),B}n(this,F,oe)&&console.debug("[blocks] remaining events",i._requeueEvents);let V=[];for(let B of i._requeueEvents){if(!y&&!B.async){n(this,F,oe)&&console.debug("[blocks] NOT reprocessing event in BlocksHandler, sync mismatch A",B),V.push(B);continue}if(y&&B.async&&!v){n(this,F,oe)&&console.debug("[blocks] NOT reprocessing event in BlocksHandler, sync mismatch B",B),V.push(B);continue}n(this,F,oe)&&console.debug("[blocks] reprocessing event in BlocksHandler",B),c.push(B)}i._requeueEvents=V,c.length>0&&(f={...i._changed},P={_state:ru(i._state),_effects:{...i._effects}},b=[...c])}if(y){i._latestRenderContent||(i._latestRenderContent=h(this,F,La).call(this,n(this,Bi),i.request.props??{},i));let A=i._latestRenderContent;A&&(o=n(this,Qr).createBlocksElementOrThrow(A),o=n(this,Qr).ensureRootBlock(o))}return{state:i._changedState,effects:i.effects,blocks:o,events:i._requeueEvents}}};Bi=new WeakMap,fo=new WeakMap,Qr=new WeakMap,F=new WeakSet,oe=function(){return!!this._latestRenderContext?.devvitContext.debug.blocks},go=function(e,...t){e._hooks={},h(this,F,La).call(this,n(this,Bi),e.request.props??{},e)},nu=async function(e,...t){h(this,F,go).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,F,Na).call(this,e,i)}))},Na=async function(e,t){let i=e._hooks[t.hook];if(i?.onUIEvent)try{await i.onUIEvent(t,e)}catch(s){throw ro(s)?n(this,F,oe)&&console.error("Server call required",s):console.error("Error in event handler",s),s}else await e.handleUndeliveredEvent(t)},su=async function(e,...t){for(let i of t)n(this,F,oe)&&console.log("[blocks] handling main queue event",i),n(this,F,oe)&&console.log("[blocks] before",e._state),h(this,F,go).call(this,e,i),await h(this,F,Na).call(this,e,i),n(this,F,oe)&&console.log("[blocks] after",e._state);h(this,F,go).call(this,e)},La=function(e,t,i){n(this,F,oe)&&console.debug("[blocks] renderRoot"),i._generated={},pe=i,this._latestRenderContext=i;try{let s=h(this,F,_a).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 Nt)return;throw s}finally{pe=null}},_a=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,F,Ha).call(this,s,i)}finally{i.pop()}},ho=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,F,Ha).call(this,i,t)))},Ha=function(e,t){if(Array.isArray(e))return h(this,F,ho).call(this,e,t);if(_p(e))if(e.type===void 0)try{return t.push({namespace:"fragment",...e.props}),h(this,F,ho).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,F,_a).call(this,e.type,i,t)}else try{t.push({namespace:e.type,...e.props});let i=h(this,F,ho).call(this,e.children,t),s=h(this,F,ou).call(this,e.props??{});return[{type:e.type,children:i,props:s}]}finally{t.pop()}else return[(e??"").toString()]},ou=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){let c=d.webView.postMessage.jsonString?JSON.parse(d.webView.postMessage.jsonString):d.webView.postMessage.message;return e[i](c)}}})});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 _p(r){return typeof r=="object"&&r!=null&&"type"in r}var au=r=>{let e=Number(r.trim().split(".").pop());return isNaN(e)?void 0:e},du=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=au(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=au(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)},lu=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),Hp=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}`)}},jp=({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=Hp(r);t?e.ui.navigateTo(t):console.warn("No upgrade link found for platform:",r)}},"Upgrade"))))),uu=r=>()=>u.createElement(jp,{platform:r});var Vp=()=>u.createElement("vstack",{alignment:"center middle",width:"100%",height:"100%"},u.createElement("text",null,"This feature is not available yet")),Wp=[[yo,yo.methods.renderPostContent,(r,e)=>u.customPostType?.render(e)??null],[yo,yo.methods.renderPostComposer,(r,e)=>u.createElement(Vp,null)]];function Gp(r){return async(e,t)=>{let i=du(t["devvit-user-agent"]?.values?.[0]??"");if(i&&lu(i)){let o=new _t(uu(i.platform));return cu.fromJSON(await o.handle(e,t))}let s=new _t(r);return cu.fromJSON(await s.handle(e,t))}}function mu(r){for(let[e,t,i]of Wp)r.provides(e),O(t.name,Gp(i))}var lt,Yr,ut,Ht,jt,ct,Di,Vt,mt,en,Wt,tn,Gt,H,U=class U extends Hs{static configure(e){a(this,ut,{...n(this,ut),...e});let t=e.http,i=typeof t=="object"&&"requestedFetchDomains"in t;Se(i?{enabled:!0}:t)&&(i&&a(this,Wt,t.requestedFetchDomains),this.use(k.HTTPDefinition)),(e.redis===void 0||Se(e.kvStore)||Se(e.redis))&&(this.use(k.KVStoreDefinition),this.use(k.RedisAPIDefinition)),Se(e.media)&&this.use(k.MediaServiceDefinition),Se(e.modLog)&&this.use(k.ModlogDefinition),Se(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)),Se(e.realtime)&&this.use(k.RealtimeDefinition),Se(e.userActions)&&this.use(k.UserActionsDefinition)}static addMenuItem(e){n(this,Di).push(e)}static addCustomPostType(e){a(this,Ht,e)}static createForm(e,t){let i=`form.${n(this,jt).size}`;return n(this,jt).set(i,{form:e,onSubmit:t}),i}static addSchedulerJob(e){if(n(this,H)[k.SchedulerDefinition.fullName]||this.use(k.SchedulerDefinition),n(this,Vt).has(e.name))throw new Error(`Job ${e.name} is already defined`);n(this,Vt).set(e.name,e.onRun)}static addSettings(e){let t=Array.isArray(e)?e:[e],i=t.filter(o=>o.type==="group"||!o.scope||o.scope==="installation"),s=t.filter(o=>o.type!=="group"&&o.scope==="app");i.length>0&&(n(this,ct)??a(this,ct,[]),n(this,ct).push(...i)),s.length>0&&(n(this,lt)??a(this,lt,[]),n(this,lt).push(...s)),Tt([...n(this,ct)??[],...n(this,lt)??[]]),n(this,H)[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,mt).has(e.event)?n(this,mt).get(e.event)?.push(e.onEvent):n(this,mt).set(e.event,[e.onEvent]),U}static provide(e){n(this,tn).push(e)}static use(e,t){n(this,Gt)[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,Gt)[e.fullName].handler?.[s.name]?.(s.requestType?.fromPartial(o??{}),d);return n(this,H)[e.fullName]=i,i}static get redditAPIPlugins(){if(!Se(n(this,ut).redditAPI))throw new Error("Reddit API is not enabled. You can enable it by passing `redditAPI: true` to `Devvit.configure`.");return{Flair:n(this,H)[k.FlairDefinition.fullName],GraphQL:n(this,H)[k.GraphQLDefinition.fullName],LinksAndComments:n(this,H)[k.LinksAndCommentsDefinition.fullName],Listings:n(this,H)[k.ListingsDefinition.fullName],Moderation:n(this,H)[k.ModerationDefinition.fullName],ModNote:n(this,H)[k.ModNoteDefinition.fullName],NewModmail:n(this,H)[k.NewModmailDefinition.fullName],PrivateMessages:n(this,H)[k.PrivateMessagesDefinition.fullName],Subreddits:n(this,H)[k.SubredditsDefinition.fullName],Users:n(this,H)[k.UsersDefinition.fullName],Widgets:n(this,H)[k.WidgetsDefinition.fullName],Wiki:n(this,H)[k.WikiDefinition.fullName]}}static get modLogPlugin(){let e=n(this,H)[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,H)[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,H)[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,H)[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,H)[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,H)[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,H)[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 userActionsPlugin(){if(!(Se(n(this,ut).userActions)&&Se(n(this,ut).redditAPI)))throw new Error("UserActions is not enabled. You can enable it by passing both `userActions: true` and `redditAPI: true` to `Devvit.configure`");return n(this,H)[k.UserActionsDefinition.fullName]}static get menuItems(){return n(this,Di)}static get customPostType(){return n(this,Ht)}static get formDefinitions(){return n(this,jt)}static get scheduledJobHandlers(){return n(this,Vt)}static get installationSettings(){return n(this,ct)}static get appSettings(){return n(this,lt)}static get triggerOnEventHandlers(){return n(this,mt)}static get assets(){return n(this,Yr)}static get webViewAssets(){return n(this,en)}static get requestedHosts(){return n(this,Wt)}constructor(e){super(e),a(U,Yr,e.assets??{}),a(U,en,e.webviewAssets??{});for(let t in n(U,Gt)){let i=n(U,Gt)[t];i.handler=e.use(i.def,i.options)}n(U,Di).length>0&&bl(e),n(U,Vt).size>0&&vl(e),n(U,Ht)&&(ml(e),mu(e)),(n(U,Ht)||n(U,jt).size>0)&&Ll(e),n(U,ct)&&pl(e),n(U,lt)&&qd(e),n(U,mt).size>0&&kl(e);for(let t of n(U,tn))e.provides(t);n(U,Wt).length>0&&e.addPermissions({requestedFetchDomains:n(U,Wt)})}};lt=new WeakMap,Yr=new WeakMap,ut=new WeakMap,Ht=new WeakMap,jt=new WeakMap,ct=new WeakMap,Di=new WeakMap,Vt=new WeakMap,mt=new WeakMap,en=new WeakMap,Wt=new WeakMap,tn=new WeakMap,Gt=new WeakMap,H=new WeakMap,U.debug={},l(U,lt),l(U,Yr,{}),l(U,ut,{}),l(U,Ht),l(U,jt,new Map),l(U,ct),l(U,Di,[]),l(U,Vt,new Map),l(U,mt,new Map),l(U,en,{}),l(U,Wt,[]),l(U,tn,[]),l(U,Gt,{}),l(U,H,{});var u=U;(e=>{function r(t,i,...s){return{type:t,props:i,children:s}}e.createElement=r})(u||(u={}));function Z(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 ja;(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"})(ja||(ja={}));var pu="text",gu="raw",hu="br",fu="link",yu="c/",bu="p/",vu="r/",ku="u/",Cu="@",Pu="spoilertext",Su="par",wu="h",Fu="hr",xu="blockquote",Au="code",Iu="li",Eu="list",Tu="L",Ru="R",Ou="C",Mu="table",Uu="embed",Bu="img",Du="gif",Nu="video";function Lu(r){return{e:Du,id:r.mediaId,...r.caption&&{c:r.caption},...r.blur&&{o:r.blur}}}function _u(r,e){let t={},i=[];return Object.assign(t,rn(t,i),nn(t,i),sn(t,i),dn(t,i),ln(t,i),un(t,i)),e(t),{e:xu,c:i,...r.author&&{a:r.author}}}function Hu(r,e){let t={},i=[];return Object.assign(t,Wa(t,i)),e(t),{e:Au,c:i,...r.language&&{l:r.language}}}function ju(r){return{e:yu,t:r.permalink}}function Vu(r,e){let t={},i=[];return Object.assign(t,Wa(t,i),an(t,i)),e(t),{e:wu,l:r.level,c:i}}function Wu(r){return{e:Uu,u:r.sourceUrl,c:r.contentUrl,x:r.width,y:r.height}}function Gu(){return{e:Fu}}function Ju(r){return{e:Bu,id:r.mediaId,...r.caption&&{c:r.caption},...r.blur&&{o:r.blur}}}function zu(){return{e:hu}}function qu(r){return{e:fu,t:r.text,u:r.url,...r.formatting&&{f:r.formatting},...r.tooltip&&{a:r.tooltip}}}function $u(r,e){let t={},i=[];return Object.assign(t,uc(t,i)),e(t),{e:Eu,o:r.ordered,c:i}}function Ku(r){let e={},t=[];return Object.assign(e,rn(e,t),nn(e,t),sn(e,t),bo(e,t),dn(e,t),ln(e,t),un(e,t)),r(e),{e:Iu,c:t}}function Zu(r){let e={},t=[];return Object.assign(e,vo(e,t),an(e,t),Va(e,t),Ga(e,t),on(e,t)),r(e),{e:Su,c:t}}function Xu(r){return{e:bu,t:r.permalink}}function Qu(r){return{e:gu,t:r}}function Yu(r){let e={},t=[];return Object.assign(e,vo(e,t),an(e,t),Va(e,t)),r(e),{e:Pu,c:t}}function ec(r){return{e:vu,t:r.subredditName,l:r.showPrefix}}function tc(r){let e={},t=[],i=[];return Object.assign(e,cc(e,t,i)),r(e),{e:Mu,h:t,c:i}}function ic(r){let[e,t]=lc();return r(e),{c:t}}function rc(r,e){let[t,i]=lc();e(t);let s;switch(r.columnAlignment){case"left":s=Tu;break;case"right":s=Ru;break;case"center":s=Ou;break}return{...s&&{a:s},...i&&{c:i}}}function nc(r){let e={},t=[];return Object.assign(e,mc(e,t)),r(e),t}function sc(r){return{e:pu,t:r.text,...r.formatting&&{f:r.formatting}}}function oc(r){return{e:ku,t:r.username,l:r.showPrefix}}function ac(r){return{e:Cu,t:r.username,l:r.showPrefix}}function dc(r){return{e:Nu,id:r.mediaId,...r.caption&&{c:r.caption},...r.blur&&{o:r.blur},...r.thumbnail&&{p:r.thumbnail},...r.convertToGif&&{gifify:r.convertToGif}}}function lc(){let r={},e=[];return Object.assign(r,vo(r,e),an(r,e),Ga(r,e),on(r,e)),[r,e]}function rn(r,e){return{blockQuote(t,i){return e.push(_u(t,i)),r}}}function nn(r,e){return{codeBlock(t,i){return e.push(Hu(t,i)),r}}}function pc(r,e){return{embed(t){return e.push(Wu(t)),r}}}function sn(r,e){return{heading(t,i){return e.push(Vu(t,i)),r}}}function bo(r,e){return{horizontalRule(){return e.push(Gu()),r}}}function on(r,e){return{image(t){return e.push(Ju(t)),r},animatedImage(t){return e.push(Lu(t)),r}}}function Va(r,e){return{linebreak(){return e.push(zu()),r}}}function an(r,e){return{link(t){return e.push(qu(t)),r},commentLink(t){return e.push(ju(t)),r},postLink(t){return e.push(Xu(t)),r},subredditLink(t){return e.push(ec(t)),r},userLink(t){return e.push(oc(t)),r},userMention(t){return e.push(ac(t)),r}}}function dn(r,e){return{list(t,i){return e.push($u(t,i)),r}}}function uc(r,e){return{item(t){return e.push(Ku(t)),r}}}function ln(r,e){return{paragraph(t){return e.push(Zu(t)),r}}}function Wa(r,e){return{rawText(t){return e.push(Qu(t)),r}}}function Ga(r,e){return{spoiler(t){return e.push(Yu(t)),r}}}function cc(r,e,t){return{headerCell(i,s){return e.push(rc(i,s)),r},row(i){return t.push(nc(i)),r}}}function un(r,e){return{table(t){return e.push(tc(t)),r}}}function mc(r,e){return{cell(t){return e.push(ic(t)),r}}}function vo(r,e){return{text(t){return e.push(sc(t)),r}}}function gc(r,e){return{video(t){return e.push(dc(t)),r}}}var Jp=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},zp=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)},ko,Jt=class{constructor(){ko.set(this,void 0);let e=[];Object.assign(this,ln(this,e),sn(this,e),bo(this,e),rn(this,e),nn(this,e),pc(this,e),dn(this,e),un(this,e),on(this,e),gc(this,e)),Jp(this,ko,{document:e},"f")}build(){return JSON.stringify(zp(this,ko,"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}};ko=new WeakMap;function Ni(r){let e;return r instanceof Jt?e=r.build():typeof r=="object"?e=JSON.stringify(r):e=r,e}var hc=100,fc=1/0,zt,qt,pt,Li,_i,Co,W=class{constructor(e){l(this,_i);l(this,zt);l(this,qt);l(this,pt);l(this,Li,!1);this.pageSize=hc;this.limit=fc;this.children=[];Z(this),this._fetch=e.fetch,this.pageSize=e.pageSize??hc,this.limit=e.limit??fc,a(this,qt,e.after),a(this,zt,e.before),a(this,pt,e.more),e.children&&(this.children=e.children)}get hasMore(){return!n(this,Li)||!!(n(this,qt)||n(this,zt)||n(this,pt))}async*[Symbol.asyncIterator](){let e=0;for(;;){if(e===this.children.length)if(this.hasMore){if((await h(this,_i,Co).call(this)).length===0)break}else break;if(yield this.children[e],e++,e===this.limit)break}}setMore(e){a(this,pt,e)}preventInitialFetch(){a(this,Li,!0)}async all(){for(;this.hasMore&&this.children.length<this.limit;)await h(this,_i,Co).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,_i,Co).call(this);return this.children.slice(0,t)}};zt=new WeakMap,qt=new WeakMap,pt=new WeakMap,Li=new WeakMap,_i=new WeakSet,Co=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,zt),after:n(this,qt),limit:this.pageSize,more:n(this,pt)});return this.children.push(...e),a(this,zt,t),a(this,qt,i),a(this,pt,s),a(this,Li,!0),e};var cn,Ja,ke=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,cn,Ja).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,cn,Ja).call(this,s.created)}static async addRemovalNote(e,t){await u.redditAPIPlugins.ModNote.PostRemovalNote(e,t)}};cn=new WeakSet,Ja=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:K(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?ye(e.userNoteData?.redditId):void 0,label:e.userNoteData?.label},type:e.type}},l(ke,cn);var Y=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 yc=["all","wiki","posts","access","mail","config","flair","channels","chat_config","chat_operator","community_chat"];function qp(r,e){return e.map(t=>(r.includes(t)?"+":"-")+t).join(",")}function za(r){return qp(r,yc)}function bc(r){return r.filter(e=>yc.includes(e))}import"@devvit/protos";var $p=(t=>(t.User="USER_FLAIR",t.Post="LINK_FLAIR",t))($p||{}),$t,Hi,ji,Vi,Wi,Gi,Ji,zi,qi,$i,Ki,Po,Ie=class Ie{constructor(e,t,i){l(this,$t);l(this,Hi);l(this,ji);l(this,Vi);l(this,Wi);l(this,Gi);l(this,Ji);l(this,zi);l(this,qi);l(this,$i);Z(this),p(e.id),p(e.text),a(this,$t,e.id),a(this,Hi,t),a(this,ji,e.text),a(this,Vi,Kp(e.textColor)),a(this,Wi,Zp(e.backgroundColor)),a(this,Gi,Xp(e.allowableContent)),a(this,Ji,e.modOnly),a(this,zi,e.maxEmojis),a(this,qi,e.textEditable),a(this,$i,i)}get id(){return n(this,$t)}get text(){return n(this,ji)}get textColor(){return n(this,Vi)}get backgroundColor(){return n(this,Wi)}get allowableContent(){return n(this,Gi)}get modOnly(){return n(this,Ji)}get maxEmojis(){return n(this,zi)}get allowUserEdits(){return n(this,qi)}async delete(){return Ie.deleteFlairTemplate(n(this,$t),n(this,Hi),n(this,$i))}async edit(e){return Ie.editFlairTemplate({id:n(this,$t),subredditName:n(this,Hi),text:e.text??n(this,ji),allowableContent:e.allowableContent??n(this,Gi),backgroundColor:e.backgroundColor??n(this,Wi),maxEmojis:e.maxEmojis??n(this,zi),modOnly:e.modOnly??n(this,Ji),textColor:e.textColor??n(this,Vi),allowUserEdits:e.allowUserEdits??n(this,qi)},n(this,$i))}static async createPostFlairTemplate(e,t){var i;return h(i=Ie,Ki,Po).call(i,{...e,flairType:"LINK_FLAIR"},t)}static async createUserFlairTemplate(e,t){var i;return h(i=Ie,Ki,Po).call(i,{...e,flairType:"USER_FLAIR"},t)}static async editFlairTemplate(e,t){var i;return h(i=Ie,Ki,Po).call(i,e,t)}static async getPostFlairTemplates(e,t){return(await u.redditAPIPlugins.Flair.LinkFlair({subreddit:e},t)).flair?.map(o=>new Ie(o,e,t))||[]}static async getUserFlairTemplates(e,t){return(await u.redditAPIPlugins.Flair.UserFlair({subreddit:e},t)).flair?.map(o=>new Ie(o,e,t))||[]}static async deleteFlairTemplate(e,t,i){await u.redditAPIPlugins.Flair.DeleteFlairTemplate({subreddit:e,flairTemplateId:t},i)}};$t=new WeakMap,Hi=new WeakMap,ji=new WeakMap,Vi=new WeakMap,Wi=new WeakMap,Gi=new WeakMap,Ji=new WeakMap,zi=new WeakMap,qi=new WeakMap,$i=new WeakMap,Ki=new WeakSet,Po=async function(e,t){let{subredditName:i,allowableContent:s="all",backgroundColor:o="transparent",flairType:d="",maxEmojis:c=10,modOnly:m=!1,text:y,textColor:v="dark",allowUserEdits:f=!1,id:P=""}=e;if(m&&f)throw new Error("Cannot have a mod only flair that is editable by users");let L=await u.redditAPIPlugins.Flair.FlairTemplate({subreddit:i,allowableContent:s,backgroundColor:o,flairType:d,maxEmojis:c,modOnly:m,text:y,textColor:v,textEditable:f,flairTemplateId:P,cssClass:"",overrideCss:!1},t);return new Ie(L,i,t)},l(Ie,Ki);var ne=Ie;function mn(r){return{flairCssClass:r.flairCssClass,user:r.user,flairText:r.flairText}}var Ue,qa,vc,$a,gt=class gt{static async getUserFlairBySubreddit(e,t){return u.redditAPIPlugins.Flair.FlairList(e,t)}static setUserFlair(e,t){var i;return h(i=gt,Ue,qa).call(i,e,t)}static setUserFlairBatch(e,t,i){var s;return h(s=gt,Ue,vc).call(s,e,t,i)}static setPostFlair(e,t){var i;return h(i=gt,Ue,qa).call(i,{...e,postId:de(e.postId)},t)}static async removePostFlair(e,t,i){var s;return h(s=gt,Ue,$a).call(s,e,t,void 0,i)}static async removeUserFlair(e,t,i){var s;return h(s=gt,Ue,$a).call(s,e,void 0,t,i)}};Ue=new WeakSet,qa=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)},vc=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(y=>{for(let v in y)if(y[v]?.includes(o))throw new Error(`Unexpected input: ${v} cannot contain the "," character`);return[y.username,y.text||"",y.cssClass||""].join(o)}).join(`
|
|
4
|
+
`);return(await u.redditAPIPlugins.Flair.FlairCsv({subreddit:e,flairCsv:d},i)).result},$a=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(gt,Ue);var ce=gt;function Kp(r){if(p(r,"Flair text color is required"),r==="light"||r==="dark")return r;throw new Error(`Invalid flair text color: ${r}`)}function Zp(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 Xp(r){if(r==="all"||r==="text"||r==="emoji")return r;throw new Error(`Invalid allowable content: ${r}`)}import{Block as Sc,UIResponse as og}from"@devvit/protos";var Xa=dd(Pc(),1);var Za=r=>"text"in r?r.text:sg(r.richtext),sg=r=>r instanceof Jt?r.build():typeof r=="object"?JSON.stringify(r):r;var ag={NONE:0,BLOCKS:1,UNRECOGNIZED:-1},yC={UNKNOWN:0,VALID:1,FAILED:2},Zi,gn,Zt,hn,Xi,fn,yn,bn,Xt,vn,kn,Cn,Pn,Sn,wn,ht,Fn,xn,Qt,Qi,ft,Yi,er,tr,yt,bt,vt,ir,kt,Ct,Pt,Ve,An,In,rr,nr,sr,M,D=class D{constructor(e,t){l(this,Zi);l(this,gn);l(this,Zt);l(this,hn);l(this,Xi);l(this,fn);l(this,yn);l(this,bn);l(this,Xt);l(this,vn);l(this,kn);l(this,Cn);l(this,Pn);l(this,Sn);l(this,wn);l(this,ht);l(this,Fn);l(this,xn);l(this,Qt);l(this,Qi);l(this,ft);l(this,Yi);l(this,er);l(this,tr);l(this,yt);l(this,bt);l(this,vt);l(this,ir);l(this,kt);l(this,Ct);l(this,Pt);l(this,Ve);l(this,An);l(this,In);l(this,rr);l(this,nr);l(this,sr);l(this,M);Z(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,Zi,de(`t3_${e.id}`)),a(this,Zt,e.author),a(this,gn,e.authorFullname?te(e.authorFullname):void 0),a(this,Xi,K(e.subredditId)),a(this,fn,e.subreddit),a(this,Cn,e.score??0),a(this,Pn,e.numComments??0),a(this,Sn,e.numReports??0);let i=new Date(0);i.setUTCSeconds(e.createdUtc),a(this,hn,i),a(this,bn,e.title),a(this,Xt,e.selftext),a(this,vn,e.selftextHtml),a(this,kn,e.url),a(this,yn,e.permalink),e.thumbnail&&e.thumbnail!=="self"&&e.thumbnail!=="nsfw"&&e.thumbnailHeight!=null&&e.thumbnailWidth!=null&&a(this,wn,{url:e.thumbnail,height:e.thumbnailHeight,width:e.thumbnailWidth}),a(this,ht,e.approved??!1),a(this,Fn,e.approvedAtUtc??0),a(this,xn,e.bannedAtUtc??0),a(this,ft,e.removed??!1),a(this,Yi,e.removedBy),a(this,er,e.removedByCategory),a(this,Qt,e.spam??!1),a(this,Qi,e.stickied??!1),a(this,tr,e.archived??!1),a(this,yt,e.edited??!1),a(this,bt,e.locked??!1),a(this,vt,e.over18??!1),a(this,ir,e.quarantine??!1),a(this,kt,e.spoiler),a(this,Ct,e.hidden??!1),a(this,Pt,e.ignoreReports??!1),a(this,Ve,e.distinguished),a(this,In,e.secureMedia),a(this,rr,(e.modReports??[]).map(([s])=>s)),a(this,nr,(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,An,{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}),e.gallery?a(this,sr,e.gallery.map(s=>({status:s.status,url:s.url,height:s.height,width:s.width}))):a(this,sr,[])}get id(){return n(this,Zi)}get authorId(){return n(this,gn)}get authorName(){return n(this,Zt)}get subredditId(){return n(this,Xi)}get subredditName(){return n(this,fn)}get permalink(){return n(this,yn)}get title(){return n(this,bn)}get body(){return n(this,Xt)}get bodyHtml(){return n(this,vn)}get url(){return n(this,kn)}get thumbnail(){return n(this,wn)}get createdAt(){return n(this,hn)}get score(){return n(this,Cn)}get numberOfComments(){return n(this,Pn)}get numberOfReports(){return n(this,Sn)}get approved(){return n(this,ht)}get approvedAtUtc(){return n(this,Fn)}get bannedAtUtc(){return n(this,xn)}get spam(){return n(this,Qt)}get stickied(){return n(this,Qi)}get removed(){return n(this,ft)}get removedBy(){return n(this,Yi)}get removedByCategory(){return n(this,er)}get archived(){return n(this,tr)}get edited(){return n(this,yt)}get locked(){return n(this,bt)}get nsfw(){return n(this,vt)}get quarantined(){return n(this,ir)}get spoiler(){return n(this,kt)}get hidden(){return n(this,Ct)}get ignoringReports(){return n(this,Pt)}get distinguishedBy(){return n(this,Ve)}get comments(){return Q.getComments({postId:this.id},n(this,M))}get flair(){return n(this,An)}get secureMedia(){return n(this,In)}get userReportReasons(){return n(this,nr)}get modReportReasons(){return n(this,rr)}get gallery(){return n(this,sr)}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,Yi),removedByCategory:n(this,er),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,rr),userReportReasons:n(this,nr)}}isApproved(){return n(this,ht)}isSpam(){return n(this,Qt)}isStickied(){return n(this,Qi)}isRemoved(){return n(this,ft)}isArchived(){return n(this,tr)}isEdited(){return n(this,yt)}isLocked(){return n(this,bt)}isNsfw(){return n(this,vt)}isQuarantined(){return n(this,ir)}isSpoiler(){return n(this,kt)}isHidden(){return n(this,Ct)}isIgnoringReports(){return n(this,Pt)}isDistinguishedBy(){return n(this,Ve)}async edit(e){let t=await D.edit({id:this.id,...e},n(this,M));a(this,Xt,t.body),a(this,yt,t.edited)}async setSuggestedCommentSort(e){await D.setSuggestedCommentSort({id:this.id,subredditId:n(this,Xi),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,Xt,t.body),a(this,yt,t.edited)}async addComment(e){return Q.submit({id:this.id,...e},n(this,M))}async delete(){p(n(this,M));let e=n(this,M)?.[S.App]?.values[0];if(e!==n(this,Zt))throw new Error(`App '${e}' is not the author of Post ${this.id}, delete not allowed.`);return D.delete(this.id,n(this,M))}async approve(){await D.approve(this.id,n(this,M)),a(this,ht,!0),a(this,ft,!1)}async remove(e=!1){await D.remove(this.id,e,n(this,M)),a(this,ft,!0),a(this,Qt,e),a(this,ht,!1)}async lock(){await D.lock(this.id,n(this,M)),a(this,bt,!0)}async unlock(){await D.unlock(this.id,n(this,M)),a(this,bt,!1)}async hide(){await D.hide(this.id,n(this,M)),a(this,Ct,!0)}async unhide(){await D.unhide(this.id,n(this,M)),a(this,Ct,!1)}async markAsNsfw(){await D.markAsNsfw(this.id,n(this,M)),a(this,vt,!0)}async unmarkAsNsfw(){await D.unmarkAsNsfw(this.id,n(this,M)),a(this,vt,!1)}async markAsSpoiler(){await D.markAsSpoiler(this.id,n(this,M)),a(this,kt,!0)}async unmarkAsSpoiler(){await D.unmarkAsSpoiler(this.id,n(this,M)),a(this,kt,!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,Ve,e)}async distinguishAsAdmin(){let{distinguishedBy:e}=await D.distinguish(this.id,!0,n(this,M));a(this,Ve,e)}async undistinguish(){let{distinguishedBy:e}=await D.undistinguish(this.id,n(this,M));a(this,Ve,e)}async ignoreReports(){await D.ignoreReports(this.id,n(this,M)),a(this,Pt,!0)}async unignoreReports(){await D.unignoreReports(this.id,n(this,M)),a(this,Pt,!1)}async getAuthor(){return C.getByUsername(n(this,Zt),n(this,M))}async crosspost(e){return D.crosspost({...e,postId:this.id},n(this,M))}addRemovalNote(e){return ke.addRemovalNote({itemIds:[n(this,Zi)],...e},n(this,M))}async getEnrichedThumbnail(){return dg({id:this.id},n(this,M))}static async getById(e,t){let i=u.redditAPIPlugins.LinksAndComments,s=Et(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{runAs:i="APP"}=e,s=fe[i],o=s===fe.USER?u.userActionsPlugin:u.redditAPIPlugins.LinksAndComments,d;if("preview"in e){p(t,"Missing metadata in `SubmitPostOptions`"),s===fe.USER&&p(e.userGeneratedContent,"userGeneratedContent must be set in `SubmitPostOptions` when RunAs=USER for experience posts");let y=await new _e(()=>e.preview,void 0,{},t,void 0).buildBlocksUI(),v=Sc.encode(y).finish(),{textFallback:f,...P}=e,b=f?Za(f):"",L=e.userGeneratedContent?{text:e.userGeneratedContent.text??"",imageUrls:e.userGeneratedContent.imageUrls??[]}:void 0,A={kind:"custom",sr:e.subredditName,richtextJson:(0,Xa.fromByteArray)(v),richtextFallback:b,...P,userGeneratedContent:L,runAs:s};d=await o.SubmitCustomPost(A,t)}else d=await o.Submit({kind:"kind"in e?e.kind:"url"in e?"link":"self",sr:e.subredditName,richtextJson:"richtext"in e?Ni(e.richtext):void 0,...e,runAs:s},t);if("kind"in e&&["image","video","videogif"].includes(e.kind)&&!d.json?.data?.id){if(e.kind==="image"&&"imageUrls"in e)throw new Error(`Image post type with ${e.imageUrls} is being created asynchronously and should be updated in the subreddit soon.`);if("videoPosterUrl"in e)throw new Error(`Post of ${e.kind} type with ${e.videoPosterUrl} is being created asynchronously and should be updated in the subreddit soon.`)}if(!d.json?.data?.id||d.json?.errors?.length)throw new Error(`failed to submit post - either post ID is empty or request failed with errors: ${d.json?.errors}`);return D.getById(`t3_${d.json.data.id}`,t)}static async crosspost(e,t){let{runAs:i="APP"}=e,s=fe[i],o=s===fe.USER?u.userActionsPlugin:u.redditAPIPlugins.LinksAndComments,{postId:d,subredditName:c,...m}=e,y=await o.Submit({kind:"crosspost",sr:c,crosspostFullname:de(d),...m,runAs:s},t);if(!y.json?.data?.id||y.json?.errors?.length)throw new Error("failed to crosspost post");return D.getById(`t3_${y.json.data.id}`,t)}static async edit(e,t){let i=u.redditAPIPlugins.LinksAndComments,{id:s}=e,o;if("richtext"in e&&(o=Ni(e.richtext)),(await i.EditUserText({thingId:s,text:"text"in e?e.text:"",richtextJson:o,runAs:fe.APP},t)).json?.errors?.length)throw new Error("Failed to edit post");return D.getById(s,t)}static async setSuggestedCommentSort(e,t){if(!(await Y.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 _t(e.ui),d=og.fromJSON(await s.handle({events:[]},t)).blocks,c=(0,Xa.fromByteArray)(Sc.encode(d).finish());await i.SetCustomPostPreview({thingId:e.id,bodyType:ag.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=Za(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 pn(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 pn(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 pn(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 pn(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 pn(o,t)}})}};Zi=new WeakMap,gn=new WeakMap,Zt=new WeakMap,hn=new WeakMap,Xi=new WeakMap,fn=new WeakMap,yn=new WeakMap,bn=new WeakMap,Xt=new WeakMap,vn=new WeakMap,kn=new WeakMap,Cn=new WeakMap,Pn=new WeakMap,Sn=new WeakMap,wn=new WeakMap,ht=new WeakMap,Fn=new WeakMap,xn=new WeakMap,Qt=new WeakMap,Qi=new WeakMap,ft=new WeakMap,Yi=new WeakMap,er=new WeakMap,tr=new WeakMap,yt=new WeakMap,bt=new WeakMap,vt=new WeakMap,ir=new WeakMap,kt=new WeakMap,Ct=new WeakMap,Pt=new WeakMap,Ve=new WeakMap,An=new WeakMap,In=new WeakMap,rr=new WeakMap,nr=new WeakMap,sr=new WeakMap,M=new WeakMap;var G=D;function pn(r,e){if(!r.data?.children)throw new Error("Listing response is missing children");return{children:r.data.children.map(i=>new G(i.data,e)),before:r.data.before,after:r.data.after}}async function dg(r,e){let o=(await Y.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 lg=(_=>(_.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",_))(lg||{}),En,or,Tn,Rn,On,Mn,Un,St,Bn,Dn,Nn,De,Yt=class Yt{constructor(e,t){l(this,En);l(this,or);l(this,Tn);l(this,Rn);l(this,On);l(this,Mn);l(this,Un);l(this,St,new Map);l(this,Bn);l(this,Dn);l(this,Nn);l(this,De);Z(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,En,te(_s(e.id)?e.id:`t2_${e.id}`)),a(this,or,e.name),a(this,Mn,e.over18??!1),a(this,Un,e.isEmployee??!1);let i=new Date(0);if(i.setUTCSeconds(e.createdUtc),a(this,Tn,i),a(this,Rn,e.linkKarma??0),a(this,On,e.commentKarma??0),e.modPermissions)for(let[s,o]of Object.entries(e.modPermissions))n(this,St).set(s,bc(o));a(this,Bn,new URL(e.subreddit?.url??"","https://www.reddit.com").toString()),a(this,Dn,e.subreddit?.url??""),a(this,Nn,e.hasVerifiedEmail??!1),a(this,De,t)}get id(){return n(this,En)}get username(){return n(this,or)}get createdAt(){return n(this,Tn)}get linkKarma(){return n(this,Rn)}get commentKarma(){return n(this,On)}get nsfw(){return n(this,Mn)}get isAdmin(){return n(this,Un)}get modPermissions(){return n(this,St)}get url(){return n(this,Bn)}get permalink(){return n(this,Dn)}get hasVerifiedEmail(){return n(this,Nn)}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,St).has(e))return n(this,St).get(e);let t=await Yt.getSubredditUsersByType({subredditName:e,type:"moderators",username:this.username},n(this,De)).all();if(t.length===0)return[];let i=t[0].modPermissions.get(e)??[];return i.length>0&&n(this,St).set(e,i),i}getComments(e){return Q.getCommentsByUser({username:this.username,...e},n(this,De))}getPosts(e){return G.getPostsByUser({username:this.username,...e},n(this,De))}async getUserFlairBySubreddit(e){let t=await ce.getUserFlairBySubreddit({subreddit:e,name:n(this,or)},n(this,De));return t.users[0]?mn(t.users[0]):void 0}getSnoovatarUrl(){return Yt.getSnoovatarUrl(this.username,n(this,De))}async getSocialLinks(){let i=await Y.query("GetUserSocialLinks","2aca18ef5f4fc75fb91cdaace3e9aeeae2cb3843b5c26ad511e6f01b8521593a",{name:this.username},n(this,De));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 wc(e,t);return i==null?void 0:Yt.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 Yt(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?Yt.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 cg(o,e.subredditName,t)}})}static async createRelationship(e,t){let i=u.redditAPIPlugins.Users,{type:s,subredditName:o,username:d,permissions:c,...m}=e,y=await i.Friend({type:s,subreddit:o,name:d,permissions:c?za(c):void 0,...m},t);if(y.json?.errors?.length)throw new Error(y.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:za(i)},s);if(d.json?.errors?.length)throw new Error(d.json.errors.join(`
|
|
6
|
+
`))}static async getSnoovatarUrl(e,t){return(await Y.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 ug(o,t)}})}};En=new WeakMap,or=new WeakMap,Tn=new WeakMap,Rn=new WeakMap,On=new WeakMap,Mn=new WeakMap,Un=new WeakMap,St=new WeakMap,Bn=new WeakMap,Dn=new WeakMap,Nn=new WeakMap,De=new WeakMap;var C=Yt;function ug(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 G(i.data,e);if(i.kind==="t1")return new Q(i.data,e);throw new Error(`Type ${i.kind} is not supported`)}),before:r.data.before,after:r.data.after}}async function cg(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(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=>i.UserDataByAccountIds({ids:v.join(",")},t)))).reduce((v,f)=>({...v,...f.users}),{});return{children:r.data.children.map(v=>{let f=v.data?.id;p(f,"User id is missing from listing");let P=m[f];return p(P,"User data is missing from response"),new C({id:f,name:P.name,linkKarma:P.linkKarma,commentKarma:P.commentKarma,createdUtc:P.createdUtc,over18:P.profileOver18,snoovatarSize:[],modPermissions:{[e]:v.data?.modPermissions??[]}},t)}),before:r.data.before,after:r.data.after}}async function wc(r,e){return(await u.redditAPIPlugins.Users.UserDataByAccountIds({ids:r},e))?.users?.[r]?.name}async function Ud(r){p(r);let e=r?.[S.Username]?.values[0];if(e)return e;let t=r?.[S.User]?.values[0];if(t)return wc(t,r)}var ei,Ln,ar,dr,_n,Hn,lr,jn,Vn,ur,wt,Wn,Gn,ti,Ft,xt,We,ii,Ge,Jn,zn,qn,$n,Kn,Zn,Xn,At,X,Ne,wo,Fo,j=class j{constructor(e,t){l(this,ei);l(this,Ln);l(this,ar);l(this,dr);l(this,_n);l(this,Hn);l(this,lr);l(this,jn);l(this,Vn);l(this,ur);l(this,wt);l(this,Wn);l(this,Gn);l(this,ti);l(this,Ft);l(this,xt);l(this,We);l(this,ii);l(this,Ge);l(this,Jn);l(this,zn);l(this,qn);l(this,$n);l(this,Kn);l(this,Zn);l(this,Xn);l(this,At);l(this,X);var s;Z(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,ei,oi(`t1_${e.id}`)),a(this,Ln,e.authorFullname?te(e.authorFullname):void 0),a(this,ar,e.author),a(this,dr,e.body),a(this,jn,K(e.subredditId)),a(this,Vn,e.subreddit),a(this,Hn,Vo(e.parentId)?oi(e.parentId):de(e.parentId)),a(this,lr,de(e.linkId)),a(this,ti,e.edited??!1),a(this,Ft,e.locked??!1),a(this,xt,e.removed??!1),a(this,We,e.stickied??!1),a(this,wt,e.approved??!1),a(this,Wn,e.approvedAtUtc??0),a(this,Gn,e.bannedAtUtc??0),a(this,ii,e.spam??!1),a(this,Ge,e.distinguished),a(this,Jn,e.numReports??0),a(this,zn,e.collapsedBecauseCrowdControl??!1),a(this,qn,e.score??0),a(this,$n,e.permalink),a(this,Xn,new URL(e.permalink??"","https://www.reddit.com/").toString()),a(this,At,e.ignoreReports??!1),a(this,Kn,(e.modReports??[]).map(([o])=>o)),a(this,Zn,(e.userReports??[]).map(([o])=>o));let i=new Date(0);i.setUTCSeconds(e.createdUtc),a(this,_n,i),a(this,ur,h(s=j,Ne,wo).call(s,{postId:n(this,lr),commentId:n(this,ei)},t)),a(this,X,t)}get id(){return n(this,ei)}get authorId(){return n(this,Ln)}get authorName(){return n(this,ar)}get subredditId(){return n(this,jn)}get subredditName(){return n(this,Vn)}get body(){return n(this,dr)}get createdAt(){return n(this,_n)}get parentId(){return n(this,Hn)}get postId(){return n(this,lr)}get replies(){return n(this,ur)}get distinguishedBy(){return n(this,Ge)}get locked(){return n(this,Ft)}get stickied(){return n(this,We)}get removed(){return n(this,xt)}get approved(){return n(this,wt)}get approvedAtUtc(){return n(this,Wn)}get bannedAtUtc(){return n(this,Gn)}get spam(){return n(this,ii)}get edited(){return n(this,ti)}get numReports(){return n(this,Jn)}get collapsedBecauseCrowdControl(){return n(this,zn)}get score(){return n(this,qn)}get permalink(){return n(this,$n)}get userReportReasons(){return n(this,Zn)}get modReportReasons(){return n(this,Kn)}get url(){return n(this,Xn)}get ignoringReports(){return n(this,At)}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,Ft)}isApproved(){return n(this,wt)}isRemoved(){return n(this,xt)}isSpam(){return n(this,ii)}isStickied(){return n(this,We)}isDistinguished(){return!!n(this,Ge)}isEdited(){return n(this,ti)}isIgnoringReports(){return n(this,At)}async delete(){return j.delete(this.id,n(this,X))}async edit(e){let t=await j.edit({id:this.id,...e},n(this,X));return a(this,dr,t.body),a(this,ti,t.edited),this}async approve(){await j.approve(this.id,n(this,X)),a(this,wt,!0),a(this,xt,!1)}async remove(e=!1){await j.remove(this.id,e,n(this,X)),a(this,xt,!0),a(this,ii,e),a(this,wt,!1)}async lock(){await j.lock(this.id,n(this,X)),a(this,Ft,!0)}async unlock(){await j.unlock(this.id,n(this,X)),a(this,Ft,!1)}async reply(e){return j.submit({id:this.id,...e},n(this,X))}async getAuthor(){return C.getByUsername(n(this,ar),n(this,X))}async distinguish(e=!1){let{distinguishedBy:t,stickied:i}=await j.distinguish(this.id,e,!1,n(this,X));a(this,Ge,t),a(this,We,i)}async distinguishAsAdmin(e=!1){let{distinguishedBy:t,stickied:i}=await j.distinguish(this.id,e,!0,n(this,X));a(this,Ge,t),a(this,We,i)}async undistinguish(){let{distinguishedBy:e,stickied:t}=await j.undistinguish(this.id,n(this,X));a(this,Ge,e),a(this,We,t)}async ignoreReports(){await j.ignoreReports(this.id,n(this,X)),a(this,At,!0)}async unignoreReports(){await j.unignoreReports(this.id,n(this,X)),a(this,At,!1)}addRemovalNote(e){return ke.addRemovalNote({itemIds:[n(this,ei)],...e},n(this,X))}static async getById(e,t){let i=u.redditAPIPlugins.LinksAndComments,s=Je(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 j(o.data.children[0].data,t)}static getComments(e,t){var d;let{postId:i,commentId:s,...o}=e;return h(d=j,Ne,wo).call(d,{postId:de(i),commentId:s?oi(s):void 0,...o},t)}static async edit(e,t){let i=u.redditAPIPlugins.LinksAndComments,{id:s}=e,o;"richtext"in e&&(o=Ni(e.richtext));let d=await i.EditUserText({thingId:s,text:"text"in e?e.text:"",richtextJson:o,runAs:fe.APP},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 j(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{runAs:i="APP"}=e,s=fe[i],o=s===fe.USER?u.userActionsPlugin:u.redditAPIPlugins.LinksAndComments,{id:d}=e,c;"richtext"in e&&(c=Ni(e.richtext));let m=await o.Comment({thingId:d,text:"text"in e?e.text:"",richtextJson:c,runAs:s},t);if(m.json?.errors?.length)throw new Error("failed to reply to comment");let y=m.json?.data?.things?.[0]?.data;return p(y),new j(y,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 j(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)}};ei=new WeakMap,Ln=new WeakMap,ar=new WeakMap,dr=new WeakMap,_n=new WeakMap,Hn=new WeakMap,lr=new WeakMap,jn=new WeakMap,Vn=new WeakMap,ur=new WeakMap,wt=new WeakMap,Wn=new WeakMap,Gn=new WeakMap,ti=new WeakMap,Ft=new WeakMap,xt=new WeakMap,We=new WeakMap,ii=new WeakMap,Ge=new WeakMap,Jn=new WeakMap,zn=new WeakMap,qn=new WeakMap,$n=new WeakMap,Kn=new WeakMap,Zn=new WeakMap,Xn=new WeakMap,At=new WeakMap,X=new WeakMap,Ne=new WeakSet,wo=function(e,t,i=0){return new W({limit:e.limit,pageSize:e.pageSize,fetch:async s=>{var P,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 L=s.more;(!o||o>100)&&(o=100);let A=L.children.splice(0,o),V=await c.MoreChildren({linkId:e.postId,children:A,sort:e.sort},t);if(!V.json?.data?.things?.length)return{children:[]};let{children:B}=h(P=j,Ne,Fo).call(P,V.json.data.things,e.postId,e,t);return{children:B,more:L.children.length?L:void 0}}else m=s.more.parentId,i=i+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=j,Ne,Fo).call(b,v,m??e.postId,e,t,i)}})},Fo=function(e,t,i,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&&i.depth!=null&&f.data.depth>=i.depth))continue;let P=f.data.parentId?m[f.data.parentId]:void 0;if(f.kind==="t1"){if(f.data.name===t)continue;let b=new j(f.data,s);if(m[b.id]=b,a(b,ur,h(y=j,Ne,wo).call(y,{...i,postId:b.postId,commentId:b.id},s,o)),"replyList"in f.data&&f.data.replyList?.data){let{children:L,more:A}=h(v=j,Ne,Fo).call(v,f.data.replyList.data.children,b.id,i,s,o);L.length&&b.replies.children.push(...L),A&&b.replies.setMore(A)}b.replies.preventInitialFetch(),P?P.replies.children.push(b):d.push(b)}else if(f.kind==="more"&&f.data.parentId&&f.data.depth!=null){let b={parentId:Vo(f.data.parentId)?oi(f.data.parentId):de(f.data.parentId),children:f.data.children??[],depth:f.data.depth};P?P.replies.setMore(b):b.parentId===t&&(c=b)}}return{children:d,more:c}},l(j,Ne);var Q=j;function Ws(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 mg(s)}})}function mg(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:y,srId36:v,description:f,details:P,targetAuthor:b,targetBody:L,targetFullname:A,targetPermalink:V,targetTitle:B}=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(y,"ModAction from AboutLogResponse is missing action"),p(v,"ModAction from AboutLogResponse is missing srId36");let ni=new Date(0);return ni.setUTCSeconds(d),{id:i,type:y,moderatorName:s,moderatorId:`t2_${o}`,createdAt:ni,subredditName:c,subredditId:`t5_${v}`,description:f,details:P,target:A?{id:A,author:b,body:L,permalink:V,title:B}:void 0}}),after:r.data.after,before:r.data.before}}import"@devvit/protos";var pg=(d=>(d.New="New",d.InProgress="InProgress",d.Archived="Archived",d.Appeals="Appeals",d.JoinRequests="JoinRequests",d.Filtered="Filtered",d))(pg||{}),gg={0:"New",1:"InProgress",2:"Archived",3:"Appeals",4:"JoinRequests",5:"Filtered"},hg=(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))(hg||{}),fg={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,J,re,Fc,xc,Gs=class{constructor(e){l(this,J);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,J,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,J,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,J,re).call(this,{protoConversation:i.conversation,protoMessages:i.messages,protoModActions:i.modActions}),user:i.user}}async createModDiscussionConversation(e){return Qa({subject:e.subject,bodyMarkdown:e.bodyMarkdown,subredditId:K(e.subredditId),isInternal:!0,participantType:"MODERATOR",conversationType:"INTERNAL"},n(this,N))}async createModInboxConversation(e){return Qa({subject:e.subject,bodyMarkdown:e.bodyMarkdown,subredditId:K(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}`),Qa({subject:t,bodyMarkdown:e.bodyMarkdown,subredditId:K(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,J,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,J,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,J,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,J,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,J,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,J,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,J,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,J,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,J,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,J,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,J,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,J=new WeakSet,re=function({protoConversation:e,protoMessages:t,protoModActions:i}){return{...e,state:gg[e.state],messages:h(this,J,Fc).call(this,e,t),modActions:h(this,J,xc).call(this,e,i)}},Fc=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},xc=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:fg[d.actionTypeId]})}return i};async function Qa(r,e){let t=e[S.AppUser]?.values[0],o=await Y.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 cr,mr,Qn,Yn,es,ts,Ya=class Ya{constructor(e,t){l(this,cr);l(this,mr);l(this,Qn);l(this,Yn);l(this,es);l(this,ts);if(Z(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,cr,ye(e.name)),e.author!=null)a(this,mr,{type:"user",username:e.author,id:e.authorFullname?te(e.authorFullname):void 0});else if(e.subreddit!=null)a(this,mr,{type:"subreddit",name:e.subreddit,id:e.subredditId?K(e.subredditId):void 0});else throw new Error("PrivateMessage: Invalid data, no author or subreddit");a(this,Qn,e.body??""),a(this,Yn,e.bodyHtml??"");let i=new Date(0);i.setUTCSeconds(e.createdUtc),a(this,es,i),a(this,ts,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 Ya(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,cr)}get from(){return n(this,mr)}get body(){return n(this,Qn)}get bodyHtml(){return n(this,Yn)}get created(){return n(this,es)}async markAsRead(){await u.redditAPIPlugins.PrivateMessages.ReadMessage({id:n(this,cr)},n(this,ts))}};cr=new WeakMap,mr=new WeakMap,Qn=new WeakMap,Yn=new WeakMap,es=new WeakMap,ts=new WeakMap;var Rt=Ya;var Bd=(o=>(o.Reports="reports",o.Spam="spam",o.Modqueue="modqueue",o.Unmoderated="unmoderated",o.Edited="edited",o))(Bd||{}),Ac=class{},Ic=class{},Ec=class{},Tc=class{},pr,x,is,rs,ns,ss,os,as,ds,ls,us,gr,R,Ee=class Ee{constructor(e,t){l(this,pr);l(this,x);l(this,is);l(this,rs);l(this,ns);l(this,ss);l(this,os);l(this,as);l(this,ds);l(this,ls);l(this,us);l(this,gr);l(this,R);Z(this),p(e.id,"Subreddit id is missing or undefined"),p(e.displayName,"Subreddit name is missing or undefined"),a(this,pr,K(`t5_${e.id}`)),a(this,x,e.displayName),p(e.createdUtc,"Subreddit is missing created date");let i=new Date(0);i.setUTCSeconds(e.createdUtc),a(this,is,i),a(this,rs,yg(e.subredditType)),a(this,ns,e.title),a(this,ss,e.description),p(e.lang,"Subreddit is missing language"),a(this,os,e.lang),a(this,as,e.subscribers??0),a(this,ds,e.activeUserCount??0),a(this,ls,e.over18??!1),a(this,gr,e.url??""),a(this,us,{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:bg(e.submissionType),allowedMediaInComments:(e.allowedMediaInComments??[]).map(vg),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,gr),"https://www.reddit.com").toString()}),a(this,R,t)}get id(){return n(this,pr)}get name(){return n(this,x)}get createdAt(){return n(this,is)}get type(){return n(this,rs)}get title(){return n(this,ns)}get description(){return n(this,ss)}get language(){return n(this,os)}get numberOfSubscribers(){return n(this,as)}get numberOfActiveUsers(){return n(this,ds)}get nsfw(){return n(this,ls)}get settings(){return n(this,us)}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,gr)}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,x)};return G.submit(t,n(this,R))}getControversialPosts(e={}){if(!n(this,x))throw new Error("subreddit missing displayName - it might not have been fetched");return G.getControversialPosts({...e,subredditName:n(this,x)},n(this,R))}getTopPosts(e={}){if(!n(this,x))throw new Error("subreddit missing displayName - it might not have been fetched");return G.getTopPosts({...e,subredditName:n(this,x)},n(this,R))}getApprovedUsers(e={}){return C.getSubredditUsersByType({type:"contributors",subredditName:n(this,x),...e},n(this,R))}approveUser(e){return C.createRelationship({username:e,subredditName:n(this,x),type:"contributor"},n(this,R))}removeUser(e){return C.removeRelationship({username:e,subredditName:n(this,x),type:"contributor"},n(this,R))}getWikiContributors(e={}){return C.getSubredditUsersByType({type:"wikicontributors",subredditName:n(this,x),...e},n(this,R))}addWikiContributor(e){return C.createRelationship({username:e,subredditName:n(this,x),type:"wikicontributor"},n(this,R))}removeWikiContributor(e){return C.removeRelationship({username:e,subredditName:n(this,x),type:"wikicontributor"},n(this,R))}getBannedUsers(e={}){return C.getSubredditUsersByType({type:"banned",subredditName:n(this,x),...e},n(this,R))}banUser(e){return C.createRelationship({username:e.username,subredditName:n(this,x),type:"banned",banReason:e.reason,banMessage:e.message,note:e.note,duration:e.duration,banContext:e.context},n(this,R))}unbanUser(e){return C.removeRelationship({username:e,subredditName:n(this,x),type:"banned"},n(this,R))}getBannedWikiContributors(e={}){return C.getSubredditUsersByType({type:"wikibanned",subredditName:n(this,x),...e},n(this,R))}banWikiContributor(e){return C.createRelationship({username:e.username,subredditName:n(this,x),type:"wikibanned",banReason:e.reason,note:e.note,duration:e.duration},n(this,R))}unbanWikiContributor(e){return C.removeRelationship({username:e,subredditName:n(this,x),type:"wikibanned"},n(this,R))}getModerators(e={}){return C.getSubredditUsersByType({type:"moderators",subredditName:n(this,x),...e},n(this,R))}inviteModerator(e,t){return C.createRelationship({type:"moderator_invite",subredditName:n(this,x),username:e,permissions:t??[]},n(this,R))}revokeModeratorInvite(e){return C.removeRelationship({username:e,subredditName:n(this,x),type:"moderator_invite"},n(this,R))}removeModerator(e){return C.removeRelationship({type:"moderator",subredditName:n(this,x),username:e},n(this,R))}setModeratorPermissions(e,t){return C.setModeratorPermissions(e,n(this,x),t,n(this,R))}getMutedUsers(e={}){return C.getSubredditUsersByType({type:"muted",subredditName:n(this,x),...e},n(this,R))}muteUser(e,t){return C.createRelationship({username:e,subredditName:n(this,x),type:"muted",note:t},n(this,R))}unmuteUser(e){return C.removeRelationship({username:e,subredditName:n(this,x),type:"muted"},n(this,R))}getModerationLog(e){return Ws({subredditName:n(this,x),...e},n(this,R))}getUserFlairTemplates(){return ne.getUserFlairTemplates(n(this,x),n(this,R))}getPostFlairTemplates(){return ne.getPostFlairTemplates(n(this,x),n(this,R))}createPostFlairTemplate(e){return ne.createPostFlairTemplate({subredditName:n(this,x),...e},n(this,R))}createUserFlairTemplate(e){return ne.createUserFlairTemplate({subredditName:n(this,x),...e},n(this,R))}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,x),name:i},n(this,R));return mn(s.users[0])}))};{let t=await ce.getUserFlairBySubreddit({...e,subreddit:n(this,x)},n(this,R));return{next:t.next,prev:t.prev,users:t.users.map(i=>mn(i))}}}getModQueue(e={type:"all"}){return Ee.aboutLocation({...e,location:"modqueue",subreddit:n(this,x)},n(this,R))}getReports(e={type:"all"}){return Ee.aboutLocation({...e,location:"reports",subreddit:n(this,x)},n(this,R))}getSpam(e={type:"all"}){return Ee.aboutLocation({...e,location:"spam",subreddit:n(this,x)},n(this,R))}getUnmoderated(e={type:"all"}){return Ee.aboutLocation({...e,location:"unmoderated",subreddit:n(this,x)},n(this,R))}getEdited(e={type:"all"}){return Ee.aboutLocation({...e,location:"edited",subreddit:n(this,x)},n(this,R))}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 Rc(d,t)}})}getCommentsAndPostsByIds(e){let t=u.redditAPIPlugins.LinksAndComments;return new W({fetch:async()=>{let i=await t.Info({thingIds:e,subreddits:[n(this,pr)]},n(this,R));return Rc(i,n(this,R))}})}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?.[S.SubredditName]?.values[0];if(t)return Ee.getByName(t,e);let i=e?.[S.Subreddit]?.values[0];return p(i),Ee.getById(K(i),e)}static async getById(e,t){let i=await Ko(e,t);if(i)return Ee.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 Ee(s.data,t)}};pr=new WeakMap,x=new WeakMap,is=new WeakMap,rs=new WeakMap,ns=new WeakMap,ss=new WeakMap,os=new WeakMap,as=new WeakMap,ds=new WeakMap,ls=new WeakMap,us=new WeakMap,gr=new WeakMap,R=new WeakMap;var le=Ee;async function Dd(r,e){let o=(await Y.query("GetSubredditInfoById","315a9b75c22a017d526afdf2d274616946156451aacfd56dfb91e7ad3f7a2fde",{id:r},e)).data?.subredditInfoById;if(!o)throw new Error("subreddit info not found");return o}async function Nd(r,e){let o=(await Y.query("GetSubredditInfoByName","4aa69726c7e3f5d33ab2bee22b3d74fce645824fddd5ea3ec6dfe30bdb4295cb",{name:r},e)).data?.subredditInfoByName;if(!o)throw new Error("subreddit info not found");return o}async function Ld(r,e){let o=(await Y.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 _d(r,e){let o=(await Y.query("GetSubredditStyles","d491d17ea8858f563ea578b26b9595d64adecf4bf34557d567c7e53c470f5f22",{id:r},e)).data?.subredditInfoById?.styles;if(!o)throw new Error("subreddit styles not found");return o}function yg(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 bg(r){if(r==="any"||r==="link"||r==="self")return r;throw new Error(`invalid allowed post type: ${r}`)}function vg(r){if(r==="animated"||r==="giphy"||r==="static"||r==="expression")return r;throw new Error(`invalid comment media type: ${r}`)}function Rc(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 G(d.data,e)}catch{return null}}function o(d){try{return new Q(d.data,e)}catch{return null}}}async function Ko(r,e){return(await u.redditAPIPlugins.LinksAndComments.Info({thingIds:[r],subreddits:[]},e)).data?.children[0]?.data?.displayName}async function Hd(r,e){return Oc("GetVaultContactByAddress","3e2f7966a5c120e64fd2795d06a46595c52d988185be98d3ed71c3f81ae80d2e",{provider:"ethereum",address:r},e)}async function jd(r,e){return Oc("GetVaultContactByUserId","a854ddc19d0e22c4f36ed917fdbd568f299f3571427e393aee5e2972080fffe9",{provider:"ethereum",userId:r},e)}async function Oc(r,e,t,i){let o=(await Y.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 kg,GetWidgetsResponse_WidgetItem as ae}from"@devvit/protos";var cs,ms,ps,gs,td=class td{constructor(e,t,i){l(this,cs);l(this,ms);l(this,ps);l(this,gs);Z(this),a(this,cs,e.id),a(this,ms,e.shortName),a(this,ps,t),a(this,gs,i)}get id(){return n(this,cs)}get name(){return n(this,ms)}get subredditName(){return n(this,ps)}toJSON(){return{id:this.id,name:this.name,subredditName:this.subredditName}}delete(){return td.delete(this.subredditName,this.id,n(this,gs))}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 xo(m,e,t));break;case"calendar":d.push(new Ao(m,e,t));break;case"textarea":d.push(new Io(m,e,t));break;case"button":d.push(new Eo(m,e,t));break;case"community-list":d.push(new To(m,e,t));break;case"post-flair":d.push(new Ro(m,e,t));break;case"custom":d.push(new Oo(m,e,t));break;case"subreddit-rules":{let y=await u.redditAPIPlugins.Subreddits.SubredditAboutRules({subreddit:e},t);d.push(new ed(y,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 xo.create(e,t);case"calendar":return Ao.create(e,t);case"textarea":return Io.create(e,t);case"button":return Eo.create(e,t);case"community-list":return To.create(e,t);case"post-flair":return Ro.create(e,t);case"custom":return Oo.create(e,t);default:throw new Error("Unknown widget type")}}};cs=new WeakMap,ms=new WeakMap,ps=new WeakMap,gs=new WeakMap;var ie=td,hs,Mo=class Mo extends ie{constructor(t,i,s){super(t,i,s);l(this,hs);a(this,hs,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,hs)}toJSON(){return{...super.toJSON(),images:this.images}}static async create(t,i){let o=await u.redditAPIPlugins.Widgets.AddImageWidget(t,i);return new Mo(ae.fromJSON(o),t.subreddit,i)}static async update(t,i){let o=await u.redditAPIPlugins.Widgets.UpdateImageWidget(t,i);return new Mo(ae.fromJSON(o),t.subreddit,i)}};hs=new WeakMap;var xo=Mo,fs,ys,bs,Uo=class Uo extends ie{constructor(t,i,s){super(t,i,s);l(this,fs);l(this,ys);l(this,bs);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,fs,t.googleCalendarId),a(this,ys,t.configuration),a(this,bs,t.styles)}get googleCalendarId(){return n(this,fs)}get configuration(){return n(this,ys)}get styles(){return n(this,bs)}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 Uo(ae.fromJSON(o),t.subreddit,i)}static async update(t,i){let o=await u.redditAPIPlugins.Widgets.UpdateCalendarWidget(t,i);return new Uo(ae.fromJSON(o),t.subreddit,i)}};fs=new WeakMap,ys=new WeakMap,bs=new WeakMap;var Ao=Uo,vs,ks,Bo=class Bo extends ie{constructor(t,i,s){super(t,i,s);l(this,vs);l(this,ks);p(t.text,"Textarea widget data is missing text"),p(t.styles,"Textarea widget data is missing styles"),a(this,vs,t.text),a(this,ks,t.styles)}get text(){return n(this,vs)}get styles(){return n(this,ks)}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 Bo(ae.fromJSON(o),t.subreddit,i)}static async update(t,i){let o=await u.redditAPIPlugins.Widgets.UpdateTextAreaWidget(t,i);return new Bo(ae.fromJSON(o),t.subreddit,i)}};vs=new WeakMap,ks=new WeakMap;var Io=Bo,Cs,Ps,Ss,Do=class Do extends ie{constructor(t,i,s){super(t,i,s);l(this,Cs);l(this,Ps);l(this,Ss);p(t.styles,"Button widget data is missing styles"),a(this,Cs,t.buttons),a(this,Ps,t.description??""),a(this,Ss,t.styles)}get buttons(){return n(this,Cs)}get description(){return n(this,Ps)}get styles(){return n(this,Ss)}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 Do(ae.fromJSON(o),t.subreddit,i)}static async update(t,i){let o=await u.redditAPIPlugins.Widgets.UpdateButtonWidget(t,i);return new Do(ae.fromJSON(o),t.subreddit,i)}};Cs=new WeakMap,Ps=new WeakMap,Ss=new WeakMap;var Eo=Do,ws,Fs,No=class No extends ie{constructor(t,i,s){super(t,i,s);l(this,ws);l(this,Fs);a(this,ws,t.data.map(o=>kg.fromJSON(o))),p(t.styles,"Community list widget data is missing styles"),a(this,Fs,t.styles)}get communities(){return n(this,ws)}get styles(){return n(this,Fs)}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 No(ae.fromJSON(o),t.subreddit,i)}static async update(t,i){let o=await u.redditAPIPlugins.Widgets.UpdateCommunityListWidget(t,i);return new No(ae.fromJSON(o),t.subreddit,i)}};ws=new WeakMap,Fs=new WeakMap;var To=No,xs,As,Is,Lo=class Lo extends ie{constructor(t,i,s){super(t,i,s);l(this,xs);l(this,As);l(this,Is);if(p(t.styles,"Post flair widget data is missing styles"),a(this,xs,t.styles),a(this,As,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,Is,t.display)}get styles(){return n(this,xs)}get templates(){return n(this,As)}get display(){return n(this,Is)}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 Lo(ae.fromJSON(o),t.subreddit,i)}static async update(t,i){let o=await u.redditAPIPlugins.Widgets.UpdatePostFlairWidget(t,i);return new Lo(ae.fromJSON(o),t.subreddit,i)}};xs=new WeakMap,As=new WeakMap,Is=new WeakMap;var Ro=Lo,Es,Ts,Rs,Os,Ms,_o=class _o extends ie{constructor(t,i,s){super(t,i,s);l(this,Es);l(this,Ts);l(this,Rs);l(this,Os);l(this,Ms);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,Es,t.imageData??[]),a(this,Ts,t.text??""),a(this,Rs,t.stylesheetUrl),a(this,Os,t.height),a(this,Ms,t.css)}get images(){return n(this,Es)}get text(){return n(this,Ts)}get stylesheetUrl(){return n(this,Rs)}get height(){return n(this,Os)}get css(){return n(this,Ms)}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 _o(ae.fromJSON(o),t.subreddit,i)}static async update(t,i){let o=await u.redditAPIPlugins.Widgets.UpdateCustomWidget(t,i);return new _o(ae.fromJSON(o),t.subreddit,i)}};Es=new WeakMap,Ts=new WeakMap,Rs=new WeakMap,Os=new WeakMap,Ms=new WeakMap;var Oo=_o,Us,ed=class extends ie{constructor(t,i,s,o){super(i,s,o);l(this,Us);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,Us,d)}get rules(){return n(this,Us)}toJSON(){return{...super.toJSON(),rules:this.rules}}};Us=new WeakMap;var Cg=(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))(Cg||{}),ge,he,hr,fr,yr,br,vr,kr,Te,xe=class xe{constructor(e,t,i,s){l(this,ge);l(this,he);l(this,hr);l(this,fr);l(this,yr);l(this,br);l(this,vr);l(this,kr);l(this,Te);Z(this),a(this,ge,e),a(this,he,t),a(this,hr,i.contentMd),a(this,fr,i.contentHtml),a(this,yr,i.revisionId),a(this,br,new Date(i.revisionDate*1e3)),a(this,vr,i.reason??""),a(this,kr,i.revisionBy?.data?new C(i.revisionBy.data,s):void 0),a(this,Te,s)}get name(){return n(this,ge)}get subredditName(){return n(this,he)}get content(){return n(this,hr)}get contentHtml(){return n(this,fr)}get revisionId(){return n(this,yr)}get revisionDate(){return n(this,br)}get revisionReason(){return n(this,vr)}get revisionAuthor(){return n(this,kr)}toJSON(){return{name:n(this,ge),subredditName:n(this,he),content:n(this,hr),contentHtml:n(this,fr),revisionId:n(this,yr),revisionDate:n(this,br),revisionReason:n(this,vr),revisionAuthor:n(this,kr)?.toJSON()}}async update(e,t){return xe.updatePage({subredditName:n(this,he),page:n(this,ge),content:e,reason:t},n(this,Te))}async getRevisions(e){return xe.getPageRevisions({subredditName:n(this,he),page:n(this,ge),...e},n(this,Te))}async revertTo(e){return xe.revertPage(n(this,he),n(this,ge),e,n(this,Te))}async getSettings(){return xe.getPageSettings(n(this,he),n(this,ge),n(this,Te))}async updateSettings(e){return xe.updatePageSettings({subredditName:n(this,he),page:n(this,ge),listed:e.listed,permLevel:e.permLevel},n(this,Te))}async addEditor(e){return xe.addEditor(n(this,he),n(this,ge),e,n(this,Te))}async removeEditor(e){return xe.removeEditor(n(this,he),n(this,ge),e,n(this,Te))}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 xe(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 xe.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),xe.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 Ho(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 Ho(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,hr=new WeakMap,fr=new WeakMap,yr=new WeakMap,br=new WeakMap,vr=new WeakMap,kr=new WeakMap,Te=new WeakMap;var ue=xe,Cr,Pr,Sr,wr,Fr,xr,id=class{constructor(e,t){l(this,Cr);l(this,Pr);l(this,Sr);l(this,wr);l(this,Fr);l(this,xr);a(this,Cr,e.id),a(this,Pr,e.page),a(this,Sr,new Date(e.timestamp)),p(e.author?.data,"Wiki page revision author details are missing"),a(this,wr,new C(e.author.data,t)),a(this,Fr,e.reason??""),a(this,xr,e.revisionHidden??!1)}get id(){return n(this,Cr)}get page(){return n(this,Pr)}get date(){return n(this,Sr)}get author(){return n(this,wr)}get reason(){return n(this,Fr)}get hidden(){return n(this,xr)}toJSON(){return{id:n(this,Cr),page:n(this,Pr),date:n(this,Sr),author:n(this,wr).toJSON(),reason:n(this,Fr),hidden:n(this,xr)}}};Cr=new WeakMap,Pr=new WeakMap,Sr=new WeakMap,wr=new WeakMap,Fr=new WeakMap,xr=new WeakMap;var Ar,Ir,Er,Ho=class{constructor(e,t){l(this,Ar);l(this,Ir);l(this,Er);a(this,Ar,e.listed),a(this,Ir,e.permLevel),a(this,Er,e.editors.map(i=>(p(i.data,"Wiki page editor details are missing"),new C(i.data,t))))}get listed(){return n(this,Ar)}get permLevel(){return n(this,Ir)}get editors(){return n(this,Er)}toJSON(){return{listed:n(this,Ar),permLevel:n(this,Ir),editors:n(this,Er).map(e=>e.toJSON())}}};Ar=new WeakMap,Ir=new WeakMap,Er=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 id(i,e)),before:r.data.before,after:r.data.after}}var Sg=["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"],wg=["border-image","border-image-source","behavior","expression","list-style-image","cursor","content"],Fg=["onload","onerror","onclick","onmouseover"];function xg(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 Mc(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*(${Sg.join("|")})\\b`,"gi"),t=new RegExp(`(${wg.join("|")})\\s*:\\s*url\\s*\\((['"]?)(.*?)\\2\\)`,"gi"),i=new RegExp(`(${Fg.join("|")})\\s*(=\\s*(['"]?)(.*?)\\3)?`,"gi");r=r.trim().replace(/\s+/g," "),r=xg(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 eS(r,...e){let t="";return r.forEach((i,s)=>{t+=i;let o=e[s];o!==void 0&&(t+=`${o}`)}),t=Mc(t),t===void 0?"":`data:image/svg+xml;charset=UTF-8,${encodeURIComponent(t)}`}import{EffectType as Bc}from"@devvit/protos";import{WebViewVisibility as Ag}from"@devvit/protos";var Uc=r=>r===null||typeof r!="object"?!1:"scope"in r&&r.scope===0&&"type"in r&&r.type==="devvit-internal";var Tr,Bs,Ds,Rr,ri,Ns,Ls,rd=class{constructor(e,t){this.state={messageCount:0,isMounted:!1};l(this,Tr);l(this,Bs);l(this,Ds);l(this,Rr);l(this,ri);l(this,Ns);this.postMessage=e=>{try{let t=JSON.stringify(e);n(this,ri).emitEffect(`postMessage${this.state.messageCount++}`,{type:Bc.EFFECT_WEB_VIEW,webView:{postMessage:{webViewId:n(this,Tr),app:{message:e,jsonString:t}}}})}catch(t){throw console.error(et.caughtToString(t)),Error("Something went wrong. Please check the contents of your postMessage.")}};this.mount=()=>{if(this.state.isMounted){console.warn("Webview is already mounted!");return}let t=(n(this,ri)?.devvitContext?.assets).getURL(n(this,Bs),{webView:!0});if(!t)throw Error("useWebView fullscreen request failed; web view asset could not be found");n(this,Ls).call(this,!0,t)};this.unmount=()=>{n(this,Ls).call(this,!1,"")};l(this,Ls,(e,t)=>{n(this,ri).emitEffect("fullscreen",{type:Bc.EFFECT_WEB_VIEW,webView:{fullscreen:{id:n(this,Tr),show:e,url:t}}})});a(this,Bs,t.url??"index.html"),a(this,Tr,e.hookId),a(this,Ds,t.onMessage),a(this,Rr,t.onUnmount),a(this,ri,e.context),a(this,Ns,e.invalidate)}onStateLoaded(){}async onUIEvent(e){if(e.webView?.fullScreen){let t=e.webView.fullScreen.visibility===Ag.WEBVIEW_VISIBLE;this.state.isMounted=t,n(this,Ns).call(this),!t&&n(this,Rr)&&await n(this,Rr).call(this,this)}else if(e.webView?.postMessage){let t=e.webView.postMessage.jsonString?JSON.parse(e.webView.postMessage.jsonString):e.webView.postMessage.message;if(Uc(t))return;await n(this,Ds).call(this,t,this)}}};Tr=new WeakMap,Bs=new WeakMap,Ds=new WeakMap,Rr=new WeakMap,ri=new WeakMap,Ns=new WeakMap,Ls=new WeakMap;function Ig(r){let e=me({namespace:"useWebView",initializer:t=>new rd(t,r)});return{postMessage:e.postMessage,mount:e.mount,unmount:e.unmount}}export{Hg as ALL_ICON_NAMES,Bd as AboutLocations,Ec as AuthorFlairSettings,Eo as ButtonWidget,Ao as CalendarWidget,Q as Comment,To as CommunityListWidget,Oo as CustomWidget,Gg as DeletionReason,u as Devvit,Jg as EventSource,ce as Flair,ne as FlairTemplate,$p as FlairType,yC as GalleryMediaStatus,ze as Hook,xo as ImageWidget,W as Listing,hg as ModMailActionType,pg as ModMailConversationState,Gs as ModMailService,ke as ModNote,G as Post,Tc as PostFlairSettings,Ro as PostFlairWidget,Rt as PrivateMessage,Jt as RichTextBuilder,fe as RunAs,Wo as SettingScope,lg as SocialLinkType,le as Subreddit,Ac as SubredditDescription,ed as SubredditRulesWidget,Ic as SubredditWikiSettings,Io as TextAreaWidget,C as User,ie as Widget,ue as WikiPage,Cg as WikiPagePermissionLevel,id as WikiPageRevision,Ho as WikiPageSettings,mn as convertUserFlairProtoToAPI,Ud as getCurrentUsernameFromMetadata,Ws as getModerationLog,Dd as getSubredditInfoById,Nd as getSubredditInfoByName,Ld as getSubredditLeaderboard,Ko as getSubredditNameById,_d as getSubredditStyles,Hd as getVaultByAddress,jd as getVaultByUserId,eS as svg,Up as useAsync,Ea as useChannel,xa as useForm,Oa as useInterval,Da as useState,Ig as useWebView};
|
|
7
7
|
/*! Bundled license information:
|
|
8
8
|
|
|
9
9
|
shallow-clone/index.js:
|