You've already forked AstralRinth
forked from didirus/AstralRinth
refactor: migrate to common eslint+prettier configs (#4168)
* refactor: migrate to common eslint+prettier configs * fix: prettier frontend * feat: config changes * fix: lint issues * fix: lint * fix: type imports * fix: cyclical import issue * fix: lockfile * fix: missing dep * fix: switch to tabs * fix: continue switch to tabs * fix: rustfmt parity * fix: moderation lint issue * fix: lint issues * fix: ui intl * fix: lint issues * Revert "fix: rustfmt parity" This reverts commit cb99d2376c321d813d4b7fc7e2a213bb30a54711. * feat: revert last rs
This commit is contained in:
@@ -1,7 +0,0 @@
|
||||
module.exports = {
|
||||
root: true,
|
||||
extends: ['custom/library'],
|
||||
env: {
|
||||
node: true,
|
||||
},
|
||||
}
|
||||
@@ -1,139 +1,138 @@
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-nocheck
|
||||
|
||||
export const getCurrency = (userCountry) => {
|
||||
const countryCurrency = {
|
||||
US: 'USD',
|
||||
GB: 'GBP',
|
||||
EU: 'EUR',
|
||||
AT: 'EUR',
|
||||
BE: 'EUR',
|
||||
CY: 'EUR',
|
||||
EE: 'EUR',
|
||||
FI: 'EUR',
|
||||
FR: 'EUR',
|
||||
DE: 'EUR',
|
||||
GR: 'EUR',
|
||||
IE: 'EUR',
|
||||
IT: 'EUR',
|
||||
LV: 'EUR',
|
||||
LT: 'EUR',
|
||||
LU: 'EUR',
|
||||
MT: 'EUR',
|
||||
NL: 'EUR',
|
||||
PT: 'EUR',
|
||||
SK: 'EUR',
|
||||
SI: 'EUR',
|
||||
RU: 'RUB',
|
||||
BR: 'BRL',
|
||||
JP: 'JPY',
|
||||
ID: 'IDR',
|
||||
MY: 'MYR',
|
||||
PH: 'PHP',
|
||||
TH: 'THB',
|
||||
VN: 'VND',
|
||||
KR: 'KRW',
|
||||
TR: 'TRY',
|
||||
UA: 'UAH',
|
||||
MX: 'MXN',
|
||||
CA: 'CAD',
|
||||
NZ: 'NZD',
|
||||
NO: 'NOK',
|
||||
PL: 'PLN',
|
||||
CH: 'CHF',
|
||||
LI: 'CHF',
|
||||
IN: 'INR',
|
||||
CL: 'CLP',
|
||||
PE: 'PEN',
|
||||
CO: 'COP',
|
||||
ZA: 'ZAR',
|
||||
HK: 'HKD',
|
||||
AR: 'ARS',
|
||||
KZ: 'KZT',
|
||||
UY: 'UYU',
|
||||
CN: 'CNY',
|
||||
AU: 'AUD',
|
||||
TW: 'TWD',
|
||||
SA: 'SAR',
|
||||
QA: 'QAR',
|
||||
}
|
||||
const countryCurrency = {
|
||||
US: 'USD',
|
||||
GB: 'GBP',
|
||||
EU: 'EUR',
|
||||
AT: 'EUR',
|
||||
BE: 'EUR',
|
||||
CY: 'EUR',
|
||||
EE: 'EUR',
|
||||
FI: 'EUR',
|
||||
FR: 'EUR',
|
||||
DE: 'EUR',
|
||||
GR: 'EUR',
|
||||
IE: 'EUR',
|
||||
IT: 'EUR',
|
||||
LV: 'EUR',
|
||||
LT: 'EUR',
|
||||
LU: 'EUR',
|
||||
MT: 'EUR',
|
||||
NL: 'EUR',
|
||||
PT: 'EUR',
|
||||
SK: 'EUR',
|
||||
SI: 'EUR',
|
||||
RU: 'RUB',
|
||||
BR: 'BRL',
|
||||
JP: 'JPY',
|
||||
ID: 'IDR',
|
||||
MY: 'MYR',
|
||||
PH: 'PHP',
|
||||
TH: 'THB',
|
||||
VN: 'VND',
|
||||
KR: 'KRW',
|
||||
TR: 'TRY',
|
||||
UA: 'UAH',
|
||||
MX: 'MXN',
|
||||
CA: 'CAD',
|
||||
NZ: 'NZD',
|
||||
NO: 'NOK',
|
||||
PL: 'PLN',
|
||||
CH: 'CHF',
|
||||
LI: 'CHF',
|
||||
IN: 'INR',
|
||||
CL: 'CLP',
|
||||
PE: 'PEN',
|
||||
CO: 'COP',
|
||||
ZA: 'ZAR',
|
||||
HK: 'HKD',
|
||||
AR: 'ARS',
|
||||
KZ: 'KZT',
|
||||
UY: 'UYU',
|
||||
CN: 'CNY',
|
||||
AU: 'AUD',
|
||||
TW: 'TWD',
|
||||
SA: 'SAR',
|
||||
QA: 'QAR',
|
||||
}
|
||||
|
||||
return countryCurrency[userCountry] ?? 'USD'
|
||||
return countryCurrency[userCountry] ?? 'USD'
|
||||
}
|
||||
|
||||
export const formatPrice = (locale, price, currency, trimZeros = false) => {
|
||||
let formatter = new Intl.NumberFormat(locale, {
|
||||
style: 'currency',
|
||||
currency,
|
||||
})
|
||||
let formatter = new Intl.NumberFormat(locale, {
|
||||
style: 'currency',
|
||||
currency,
|
||||
})
|
||||
|
||||
const maxDigits = formatter.resolvedOptions().maximumFractionDigits
|
||||
const convertedPrice = price / Math.pow(10, maxDigits)
|
||||
const maxDigits = formatter.resolvedOptions().maximumFractionDigits
|
||||
const convertedPrice = price / Math.pow(10, maxDigits)
|
||||
|
||||
let minimumFractionDigits = maxDigits
|
||||
let minimumFractionDigits = maxDigits
|
||||
|
||||
if (trimZeros && Number.isInteger(convertedPrice)) {
|
||||
minimumFractionDigits = 0
|
||||
}
|
||||
if (trimZeros && Number.isInteger(convertedPrice)) {
|
||||
minimumFractionDigits = 0
|
||||
}
|
||||
|
||||
formatter = new Intl.NumberFormat(locale, {
|
||||
style: 'currency',
|
||||
currency,
|
||||
minimumFractionDigits,
|
||||
})
|
||||
return formatter.format(convertedPrice)
|
||||
formatter = new Intl.NumberFormat(locale, {
|
||||
style: 'currency',
|
||||
currency,
|
||||
minimumFractionDigits,
|
||||
})
|
||||
return formatter.format(convertedPrice)
|
||||
}
|
||||
|
||||
export const calculateSavings = (monthlyPlan, plan, months = 12) => {
|
||||
const monthlyAnnualized = monthlyPlan * months
|
||||
const monthlyAnnualized = monthlyPlan * months
|
||||
|
||||
return Math.floor(((monthlyAnnualized - plan) / monthlyAnnualized) * 100)
|
||||
return Math.floor(((monthlyAnnualized - plan) / monthlyAnnualized) * 100)
|
||||
}
|
||||
|
||||
export const createStripeElements = (stripe, paymentMethods, options) => {
|
||||
const styles = getComputedStyle(document.body)
|
||||
const styles = getComputedStyle(document.body)
|
||||
|
||||
const elements = stripe.elements({
|
||||
appearance: {
|
||||
variables: {
|
||||
colorPrimary: styles.getPropertyValue('--color-brand'),
|
||||
colorBackground: styles.getPropertyValue('--experimental-color-button-bg'),
|
||||
colorText: styles.getPropertyValue('--color-base'),
|
||||
colorTextPlaceholder: styles.getPropertyValue('--color-secondary'),
|
||||
colorDanger: styles.getPropertyValue('--color-red'),
|
||||
fontFamily: styles.getPropertyValue('--font-standard'),
|
||||
spacingUnit: '0.25rem',
|
||||
borderRadius: '0.75rem',
|
||||
},
|
||||
},
|
||||
loader: 'never',
|
||||
...options,
|
||||
})
|
||||
const elements = stripe.elements({
|
||||
appearance: {
|
||||
variables: {
|
||||
colorPrimary: styles.getPropertyValue('--color-brand'),
|
||||
colorBackground: styles.getPropertyValue('--experimental-color-button-bg'),
|
||||
colorText: styles.getPropertyValue('--color-base'),
|
||||
colorTextPlaceholder: styles.getPropertyValue('--color-secondary'),
|
||||
colorDanger: styles.getPropertyValue('--color-red'),
|
||||
fontFamily: styles.getPropertyValue('--font-standard'),
|
||||
spacingUnit: '0.25rem',
|
||||
borderRadius: '0.75rem',
|
||||
},
|
||||
},
|
||||
loader: 'never',
|
||||
...options,
|
||||
})
|
||||
|
||||
const paymentElement = elements.create('payment')
|
||||
paymentElement.mount('#payment-element')
|
||||
const paymentElement = elements.create('payment')
|
||||
paymentElement.mount('#payment-element')
|
||||
|
||||
const addressElement = elements.create('address', {
|
||||
mode: 'billing',
|
||||
contacts: paymentMethods
|
||||
? [
|
||||
...new Set(
|
||||
paymentMethods.map((x) => ({
|
||||
address: x.billing_details.address,
|
||||
email: x.billing_details.email,
|
||||
name: x.billing_details.name,
|
||||
})),
|
||||
),
|
||||
]
|
||||
: undefined,
|
||||
})
|
||||
addressElement.mount('#address-element')
|
||||
const addressElement = elements.create('address', {
|
||||
mode: 'billing',
|
||||
contacts: paymentMethods
|
||||
? [
|
||||
...new Set(
|
||||
paymentMethods.map((x) => ({
|
||||
address: x.billing_details.address,
|
||||
email: x.billing_details.email,
|
||||
name: x.billing_details.name,
|
||||
})),
|
||||
),
|
||||
]
|
||||
: undefined,
|
||||
})
|
||||
addressElement.mount('#address-element')
|
||||
|
||||
addressElement.on('change', (e) => {
|
||||
if (e.value && e.value.address && e.value.address.country) {
|
||||
elements.update({ currency: getCurrency(e.value.address.country).toLowerCase() })
|
||||
}
|
||||
})
|
||||
addressElement.on('change', (e) => {
|
||||
if (e.value && e.value.address && e.value.address.country) {
|
||||
elements.update({ currency: getCurrency(e.value.address.country).toLowerCase() })
|
||||
}
|
||||
})
|
||||
|
||||
return { elements, paymentElement, addressElement }
|
||||
return { elements, paymentElement, addressElement }
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,380 +1,379 @@
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-nocheck
|
||||
|
||||
import { insertNewlineAndIndent } from '@codemirror/commands'
|
||||
import { deleteMarkupBackward } from '@codemirror/lang-markdown'
|
||||
import { getIndentation, indentString, syntaxTree } from '@codemirror/language'
|
||||
import { type EditorState, type Transaction } from '@codemirror/state'
|
||||
import { type EditorView, type Command, type KeyBinding } from '@codemirror/view'
|
||||
import type { EditorState, Transaction } from '@codemirror/state'
|
||||
import type { Command, EditorView, KeyBinding } from '@codemirror/view'
|
||||
|
||||
const toggleBold: Command = ({ state, dispatch }) => {
|
||||
return toggleAround(state, dispatch, '**', '**')
|
||||
return toggleAround(state, dispatch, '**', '**')
|
||||
}
|
||||
|
||||
const toggleItalic: Command = ({ state, dispatch }) => {
|
||||
return toggleAround(state, dispatch, '_', '_')
|
||||
return toggleAround(state, dispatch, '_', '_')
|
||||
}
|
||||
|
||||
const toggleStrikethrough: Command = ({ state, dispatch }) => {
|
||||
return toggleAround(state, dispatch, '~~', '~~')
|
||||
return toggleAround(state, dispatch, '~~', '~~')
|
||||
}
|
||||
|
||||
const toggleCodeBlock: Command = ({ state, dispatch }) => {
|
||||
const lineBreak = state.lineBreak
|
||||
const codeBlockMark = `${lineBreak}\`\`\`${lineBreak}`
|
||||
return toggleAround(state, dispatch, codeBlockMark, codeBlockMark)
|
||||
const lineBreak = state.lineBreak
|
||||
const codeBlockMark = `${lineBreak}\`\`\`${lineBreak}`
|
||||
return toggleAround(state, dispatch, codeBlockMark, codeBlockMark)
|
||||
}
|
||||
|
||||
const toggleSpoiler: Command = ({ state, dispatch }) => {
|
||||
// Insert details tag with a summary tag at the start
|
||||
const detailsTags = ['\n<details>\n<summary>Spoiler</summary>\n\n', '\n\n</details>\n\n']
|
||||
return toggleAround(state, dispatch, detailsTags[0], detailsTags[1])
|
||||
// Insert details tag with a summary tag at the start
|
||||
const detailsTags = ['\n<details>\n<summary>Spoiler</summary>\n\n', '\n\n</details>\n\n']
|
||||
return toggleAround(state, dispatch, detailsTags[0], detailsTags[1])
|
||||
}
|
||||
|
||||
const toggleHeader: Command = ({ state, dispatch }) => {
|
||||
return toggleLineStart(state, dispatch, '# ')
|
||||
return toggleLineStart(state, dispatch, '# ')
|
||||
}
|
||||
|
||||
const toggleHeader2: Command = ({ state, dispatch }) => {
|
||||
return toggleLineStart(state, dispatch, '## ')
|
||||
return toggleLineStart(state, dispatch, '## ')
|
||||
}
|
||||
|
||||
const toggleHeader3: Command = ({ state, dispatch }) => {
|
||||
return toggleLineStart(state, dispatch, '### ')
|
||||
return toggleLineStart(state, dispatch, '### ')
|
||||
}
|
||||
|
||||
const toggleHeader4: Command = ({ state, dispatch }) => {
|
||||
return toggleLineStart(state, dispatch, '#### ')
|
||||
return toggleLineStart(state, dispatch, '#### ')
|
||||
}
|
||||
|
||||
const toggleHeader5: Command = ({ state, dispatch }) => {
|
||||
return toggleLineStart(state, dispatch, '##### ')
|
||||
return toggleLineStart(state, dispatch, '##### ')
|
||||
}
|
||||
|
||||
const toggleHeader6: Command = ({ state, dispatch }) => {
|
||||
return toggleLineStart(state, dispatch, '###### ')
|
||||
return toggleLineStart(state, dispatch, '###### ')
|
||||
}
|
||||
|
||||
const toggleQuote: Command = ({ state, dispatch }) => {
|
||||
return toggleLineStart(state, dispatch, '> ')
|
||||
return toggleLineStart(state, dispatch, '> ')
|
||||
}
|
||||
|
||||
const toggleBulletList: Command = ({ state, dispatch }) => {
|
||||
return toggleLineStart(state, dispatch, '- ')
|
||||
return toggleLineStart(state, dispatch, '- ')
|
||||
}
|
||||
|
||||
const toggleOrderedList: Command = ({ state, dispatch }) => {
|
||||
return toggleLineStart(state, dispatch, '1. ')
|
||||
return toggleLineStart(state, dispatch, '1. ')
|
||||
}
|
||||
|
||||
const yankSelection = ({ state }: EditorView): string => {
|
||||
const { from, to } = state.selection.main
|
||||
const selectedText = state.doc.sliceString(from, to)
|
||||
return selectedText
|
||||
const { from, to } = state.selection.main
|
||||
const selectedText = state.doc.sliceString(from, to)
|
||||
return selectedText
|
||||
}
|
||||
|
||||
const replaceSelection = ({ state, dispatch }: EditorView, text: string) => {
|
||||
const { from, to } = state.selection.main
|
||||
const transaction = state.update({
|
||||
changes: { from, to, insert: text },
|
||||
selection: { anchor: from + text.length, head: from + text.length },
|
||||
})
|
||||
dispatch(transaction)
|
||||
return true
|
||||
const { from, to } = state.selection.main
|
||||
const transaction = state.update({
|
||||
changes: { from, to, insert: text },
|
||||
selection: { anchor: from + text.length, head: from + text.length },
|
||||
})
|
||||
dispatch(transaction)
|
||||
return true
|
||||
}
|
||||
|
||||
type Dispatch = (tr: Transaction) => void
|
||||
|
||||
const surroundedByText = (
|
||||
state: EditorState,
|
||||
open: string,
|
||||
close: string,
|
||||
state: EditorState,
|
||||
open: string,
|
||||
close: string,
|
||||
): 'inclusive' | 'exclusive' | 'none' => {
|
||||
const { from, to } = state.selection.main
|
||||
const { from, to } = state.selection.main
|
||||
|
||||
// Check for inclusive surrounding first
|
||||
const selectedText = state.doc.sliceString(from, to)
|
||||
if (selectedText.startsWith(open) && selectedText.endsWith(close)) {
|
||||
return 'inclusive'
|
||||
}
|
||||
// Check for inclusive surrounding first
|
||||
const selectedText = state.doc.sliceString(from, to)
|
||||
if (selectedText.startsWith(open) && selectedText.endsWith(close)) {
|
||||
return 'inclusive'
|
||||
}
|
||||
|
||||
// Then check for exclusive surrounding
|
||||
const beforeText = state.doc.sliceString(Math.max(0, from - open.length), from)
|
||||
const afterText = state.doc.sliceString(to, to + close.length)
|
||||
if (beforeText === open && afterText === close) {
|
||||
return 'exclusive'
|
||||
}
|
||||
// Then check for exclusive surrounding
|
||||
const beforeText = state.doc.sliceString(Math.max(0, from - open.length), from)
|
||||
const afterText = state.doc.sliceString(to, to + close.length)
|
||||
if (beforeText === open && afterText === close) {
|
||||
return 'exclusive'
|
||||
}
|
||||
|
||||
// Return 'none' if no surrounding detected
|
||||
return 'none'
|
||||
// Return 'none' if no surrounding detected
|
||||
return 'none'
|
||||
}
|
||||
|
||||
// TODO: Node based toggleAround so that we can support nested delimiters
|
||||
const toggleAround = (
|
||||
state: EditorState,
|
||||
dispatch: Dispatch,
|
||||
open: string,
|
||||
close: string,
|
||||
state: EditorState,
|
||||
dispatch: Dispatch,
|
||||
open: string,
|
||||
close: string,
|
||||
): boolean => {
|
||||
const { from, to } = state.selection.main
|
||||
const { from, to } = state.selection.main
|
||||
|
||||
const isSurrounded = surroundedByText(state, open, close)
|
||||
const isSurrounded = surroundedByText(state, open, close)
|
||||
|
||||
if (isSurrounded !== 'none') {
|
||||
const isInclusive = isSurrounded === 'inclusive'
|
||||
let transaction: Transaction
|
||||
if (isSurrounded !== 'none') {
|
||||
const isInclusive = isSurrounded === 'inclusive'
|
||||
let transaction: Transaction
|
||||
|
||||
if (isInclusive) {
|
||||
// Remove delimiters on the inside edges of the selected text
|
||||
transaction = state.update({
|
||||
changes: [
|
||||
{ from, to: from + open.length, insert: '' },
|
||||
{ from: to - close.length, to, insert: '' },
|
||||
],
|
||||
})
|
||||
} else {
|
||||
// Remove delimiters on the outside edges of the selected text
|
||||
transaction = state.update({
|
||||
changes: [
|
||||
{ from: from - open.length, to: from, insert: '' },
|
||||
{ from: to, to: to + close.length, insert: '' },
|
||||
],
|
||||
})
|
||||
}
|
||||
if (isInclusive) {
|
||||
// Remove delimiters on the inside edges of the selected text
|
||||
transaction = state.update({
|
||||
changes: [
|
||||
{ from, to: from + open.length, insert: '' },
|
||||
{ from: to - close.length, to, insert: '' },
|
||||
],
|
||||
})
|
||||
} else {
|
||||
// Remove delimiters on the outside edges of the selected text
|
||||
transaction = state.update({
|
||||
changes: [
|
||||
{ from: from - open.length, to: from, insert: '' },
|
||||
{ from: to, to: to + close.length, insert: '' },
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
dispatch(transaction)
|
||||
return true
|
||||
}
|
||||
dispatch(transaction)
|
||||
return true
|
||||
}
|
||||
|
||||
// Add delimiters around the selected text
|
||||
const transaction = state.update({
|
||||
changes: [
|
||||
{ from, insert: open },
|
||||
{ from: to, insert: close },
|
||||
],
|
||||
selection: { anchor: from + open.length, head: to + open.length },
|
||||
})
|
||||
// Add delimiters around the selected text
|
||||
const transaction = state.update({
|
||||
changes: [
|
||||
{ from, insert: open },
|
||||
{ from: to, insert: close },
|
||||
],
|
||||
selection: { anchor: from + open.length, head: to + open.length },
|
||||
})
|
||||
|
||||
dispatch(transaction)
|
||||
return true
|
||||
dispatch(transaction)
|
||||
return true
|
||||
}
|
||||
|
||||
const toggleLineStart = (state: EditorState, dispatch: Dispatch, text: string): boolean => {
|
||||
const lines = state.doc.lineAt(state.selection.main.from)
|
||||
const lineBreak = state.lineBreak
|
||||
const lines = state.doc.lineAt(state.selection.main.from)
|
||||
const lineBreak = state.lineBreak
|
||||
|
||||
const range = {
|
||||
from: lines.from,
|
||||
to: state.selection.main.to,
|
||||
}
|
||||
const range = {
|
||||
from: lines.from,
|
||||
to: state.selection.main.to,
|
||||
}
|
||||
|
||||
const selectedText = state.doc.sliceString(range.from, range.to)
|
||||
const shouldRemove = selectedText.startsWith(text)
|
||||
const selectedText = state.doc.sliceString(range.from, range.to)
|
||||
const shouldRemove = selectedText.startsWith(text)
|
||||
|
||||
let transaction: Transaction | undefined
|
||||
let transaction: Transaction | undefined
|
||||
|
||||
if (shouldRemove) {
|
||||
const numOfSelectedLinesThatNeedToBeRemoved = selectedText.split(lineBreak + text).length
|
||||
const modifiedText = selectedText.substring(text.length).replaceAll(lineBreak + text, lineBreak)
|
||||
transaction = state.update({
|
||||
changes: { from: range.from, to: range.to, insert: modifiedText },
|
||||
selection: {
|
||||
anchor: state.selection.main.from - text.length,
|
||||
head: state.selection.main.to - text.length * numOfSelectedLinesThatNeedToBeRemoved,
|
||||
},
|
||||
})
|
||||
} else {
|
||||
const modifiedText = text + selectedText.replaceAll(lineBreak, lineBreak + text)
|
||||
const lengthDiff = modifiedText.length - selectedText.length
|
||||
transaction = state.update({
|
||||
changes: { from: range.from, to: range.to, insert: modifiedText },
|
||||
selection: {
|
||||
anchor: state.selection.main.from + text.length,
|
||||
head: state.selection.main.to + lengthDiff,
|
||||
},
|
||||
})
|
||||
}
|
||||
if (shouldRemove) {
|
||||
const numOfSelectedLinesThatNeedToBeRemoved = selectedText.split(lineBreak + text).length
|
||||
const modifiedText = selectedText.substring(text.length).replaceAll(lineBreak + text, lineBreak)
|
||||
transaction = state.update({
|
||||
changes: { from: range.from, to: range.to, insert: modifiedText },
|
||||
selection: {
|
||||
anchor: state.selection.main.from - text.length,
|
||||
head: state.selection.main.to - text.length * numOfSelectedLinesThatNeedToBeRemoved,
|
||||
},
|
||||
})
|
||||
} else {
|
||||
const modifiedText = text + selectedText.replaceAll(lineBreak, lineBreak + text)
|
||||
const lengthDiff = modifiedText.length - selectedText.length
|
||||
transaction = state.update({
|
||||
changes: { from: range.from, to: range.to, insert: modifiedText },
|
||||
selection: {
|
||||
anchor: state.selection.main.from + text.length,
|
||||
head: state.selection.main.to + lengthDiff,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
if (!transaction) return false
|
||||
if (!transaction) return false
|
||||
|
||||
dispatch(transaction)
|
||||
return true
|
||||
dispatch(transaction)
|
||||
return true
|
||||
}
|
||||
|
||||
const continueNodeTypes = ['ListItem', 'Blockquote']
|
||||
const blackListedNodeTypes = ['CodeBlock']
|
||||
|
||||
const getListStructure = (state: EditorState, head: number) => {
|
||||
const tree = syntaxTree(state)
|
||||
const headNode = tree.resolve(head, -1)
|
||||
const stack = []
|
||||
const tree = syntaxTree(state)
|
||||
const headNode = tree.resolve(head, -1)
|
||||
const stack = []
|
||||
|
||||
let node: typeof headNode.parent = headNode
|
||||
while (node) {
|
||||
if (continueNodeTypes.includes(node.name)) {
|
||||
stack.push(node)
|
||||
}
|
||||
if (blackListedNodeTypes.includes(node.name)) {
|
||||
return null
|
||||
}
|
||||
if (node.name === 'Document') {
|
||||
break
|
||||
}
|
||||
let node: typeof headNode.parent = headNode
|
||||
while (node) {
|
||||
if (continueNodeTypes.includes(node.name)) {
|
||||
stack.push(node)
|
||||
}
|
||||
if (blackListedNodeTypes.includes(node.name)) {
|
||||
return null
|
||||
}
|
||||
if (node.name === 'Document') {
|
||||
break
|
||||
}
|
||||
|
||||
node = node.parent
|
||||
}
|
||||
node = node.parent
|
||||
}
|
||||
|
||||
return stack
|
||||
return stack
|
||||
}
|
||||
|
||||
const insertNewlineContinueMark: Command = (view): boolean => {
|
||||
const { state, dispatch } = view
|
||||
const {
|
||||
selection: {
|
||||
main: { head },
|
||||
},
|
||||
} = state
|
||||
const { state, dispatch } = view
|
||||
const {
|
||||
selection: {
|
||||
main: { head },
|
||||
},
|
||||
} = state
|
||||
|
||||
// Get the current list structure to examine
|
||||
const stack = getListStructure(state, head)
|
||||
if (!stack || stack.length === 0) {
|
||||
// insert a newline as normal so that mobile works
|
||||
return insertNewlineAndIndent(view)
|
||||
}
|
||||
// Get the current list structure to examine
|
||||
const stack = getListStructure(state, head)
|
||||
if (!stack || stack.length === 0) {
|
||||
// insert a newline as normal so that mobile works
|
||||
return insertNewlineAndIndent(view)
|
||||
}
|
||||
|
||||
const lastNode = stack[stack.length - 1]
|
||||
const lastNode = stack[stack.length - 1]
|
||||
|
||||
// Get the necessary indentation
|
||||
const indentation = getIndentation(state, head)
|
||||
const indentStr = indentation ? indentString(state, indentation) : ''
|
||||
// Get the necessary indentation
|
||||
const indentation = getIndentation(state, head)
|
||||
const indentStr = indentation ? indentString(state, indentation) : ''
|
||||
|
||||
// Initialize a transaction variable
|
||||
let transaction: Transaction | undefined
|
||||
// Initialize a transaction variable
|
||||
let transaction: Transaction | undefined
|
||||
|
||||
const lineContent = state.doc.lineAt(head).text
|
||||
const lineContent = state.doc.lineAt(head).text
|
||||
|
||||
// Identify the patterns that should cancel the list continuation
|
||||
// TODO: Implement Node based cancellation
|
||||
const cancelPatterns = ['```', '# ', '> ']
|
||||
// Identify the patterns that should cancel the list continuation
|
||||
// TODO: Implement Node based cancellation
|
||||
const cancelPatterns = ['```', '# ', '> ']
|
||||
|
||||
const listMark = lastNode.getChild('ListMark')
|
||||
if (listMark) {
|
||||
cancelPatterns.push(`${state.doc.sliceString(listMark.from, listMark.to)} `)
|
||||
}
|
||||
const listMark = lastNode.getChild('ListMark')
|
||||
if (listMark) {
|
||||
cancelPatterns.push(`${state.doc.sliceString(listMark.from, listMark.to)} `)
|
||||
}
|
||||
|
||||
// Skip if current line matches any of the cancel patterns
|
||||
if (cancelPatterns.includes(lineContent)) {
|
||||
transaction = createSimpleTransaction(state)
|
||||
dispatch(transaction)
|
||||
return true
|
||||
}
|
||||
// Skip if current line matches any of the cancel patterns
|
||||
if (cancelPatterns.includes(lineContent)) {
|
||||
transaction = createSimpleTransaction(state)
|
||||
dispatch(transaction)
|
||||
return true
|
||||
}
|
||||
|
||||
switch (lastNode.name) {
|
||||
case 'ListItem':
|
||||
if (!listMark) return false
|
||||
transaction = createListTransaction(state, indentStr, listMark.from, listMark.to)
|
||||
break
|
||||
case 'Blockquote':
|
||||
transaction = createBlockquoteTransaction(state, indentStr)
|
||||
break
|
||||
}
|
||||
switch (lastNode.name) {
|
||||
case 'ListItem':
|
||||
if (!listMark) return false
|
||||
transaction = createListTransaction(state, indentStr, listMark.from, listMark.to)
|
||||
break
|
||||
case 'Blockquote':
|
||||
transaction = createBlockquoteTransaction(state, indentStr)
|
||||
break
|
||||
}
|
||||
|
||||
if (transaction) {
|
||||
dispatch(transaction)
|
||||
return true
|
||||
}
|
||||
if (transaction) {
|
||||
dispatch(transaction)
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
return false
|
||||
}
|
||||
|
||||
// Creates a transaction for a simple line break
|
||||
const createSimpleTransaction = (state: EditorState) => {
|
||||
const {
|
||||
lineBreak,
|
||||
selection: {
|
||||
main: { head },
|
||||
},
|
||||
} = state
|
||||
const line = state.doc.lineAt(head)
|
||||
return state.update({
|
||||
changes: {
|
||||
from: line.from,
|
||||
to: line.to,
|
||||
insert: lineBreak,
|
||||
},
|
||||
})
|
||||
const {
|
||||
lineBreak,
|
||||
selection: {
|
||||
main: { head },
|
||||
},
|
||||
} = state
|
||||
const line = state.doc.lineAt(head)
|
||||
return state.update({
|
||||
changes: {
|
||||
from: line.from,
|
||||
to: line.to,
|
||||
insert: lineBreak,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Creates a transaction for continuing a list item
|
||||
const createListTransaction = (state: EditorState, indentStr: string, from: number, to: number) => {
|
||||
const {
|
||||
lineBreak,
|
||||
selection: {
|
||||
main: { head },
|
||||
},
|
||||
} = state
|
||||
const listMarkContent = state.doc.sliceString(from, to)
|
||||
const insert = `${lineBreak}${indentStr}${incrementMark(listMarkContent)} `
|
||||
return state.update({
|
||||
changes: { from: head, insert },
|
||||
selection: { anchor: head + insert.length, head: head + insert.length },
|
||||
})
|
||||
const {
|
||||
lineBreak,
|
||||
selection: {
|
||||
main: { head },
|
||||
},
|
||||
} = state
|
||||
const listMarkContent = state.doc.sliceString(from, to)
|
||||
const insert = `${lineBreak}${indentStr}${incrementMark(listMarkContent)} `
|
||||
return state.update({
|
||||
changes: { from: head, insert },
|
||||
selection: { anchor: head + insert.length, head: head + insert.length },
|
||||
})
|
||||
}
|
||||
|
||||
// Creates a transaction for continuing a blockquote
|
||||
const createBlockquoteTransaction = (state: EditorState, indentStr: string) => {
|
||||
const {
|
||||
lineBreak,
|
||||
selection: {
|
||||
main: { head },
|
||||
},
|
||||
} = state
|
||||
const insert = `${lineBreak}${indentStr}> `
|
||||
return state.update({
|
||||
changes: { from: head, insert },
|
||||
selection: { anchor: head + insert.length, head: head + insert.length },
|
||||
})
|
||||
const {
|
||||
lineBreak,
|
||||
selection: {
|
||||
main: { head },
|
||||
},
|
||||
} = state
|
||||
const insert = `${lineBreak}${indentStr}> `
|
||||
return state.update({
|
||||
changes: { from: head, insert },
|
||||
selection: { anchor: head + insert.length, head: head + insert.length },
|
||||
})
|
||||
}
|
||||
|
||||
const incrementMark = (mark: string): string => {
|
||||
const numberedListRegex = /^(\d+)\.$/
|
||||
const match = numberedListRegex.exec(mark)
|
||||
if (match) {
|
||||
const number = parseInt(match[1])
|
||||
return `${(number + 1).toString()}.`
|
||||
}
|
||||
return mark
|
||||
const numberedListRegex = /^(\d+)\.$/
|
||||
const match = numberedListRegex.exec(mark)
|
||||
if (match) {
|
||||
const number = parseInt(match[1])
|
||||
return `${(number + 1).toString()}.`
|
||||
}
|
||||
return mark
|
||||
}
|
||||
|
||||
const commands = {
|
||||
toggleBold,
|
||||
toggleItalic,
|
||||
toggleStrikethrough,
|
||||
toggleCodeBlock,
|
||||
toggleSpoiler,
|
||||
toggleHeader,
|
||||
toggleHeader2,
|
||||
toggleHeader3,
|
||||
toggleHeader4,
|
||||
toggleHeader5,
|
||||
toggleHeader6,
|
||||
toggleQuote,
|
||||
toggleBulletList,
|
||||
toggleOrderedList,
|
||||
insertNewlineContinueMark,
|
||||
toggleBold,
|
||||
toggleItalic,
|
||||
toggleStrikethrough,
|
||||
toggleCodeBlock,
|
||||
toggleSpoiler,
|
||||
toggleHeader,
|
||||
toggleHeader2,
|
||||
toggleHeader3,
|
||||
toggleHeader4,
|
||||
toggleHeader5,
|
||||
toggleHeader6,
|
||||
toggleQuote,
|
||||
toggleBulletList,
|
||||
toggleOrderedList,
|
||||
insertNewlineContinueMark,
|
||||
|
||||
// Utility
|
||||
yankSelection,
|
||||
replaceSelection,
|
||||
// Utility
|
||||
yankSelection,
|
||||
replaceSelection,
|
||||
}
|
||||
|
||||
export const markdownCommands = commands
|
||||
export const modrinthMarkdownEditorKeymap: KeyBinding[] = [
|
||||
{ key: 'Enter', run: insertNewlineContinueMark },
|
||||
{ key: 'Backspace', run: deleteMarkupBackward },
|
||||
{ key: 'Mod-b', run: toggleBold },
|
||||
{ key: 'Mod-i', run: toggleItalic },
|
||||
{ key: 'Mod-e', run: toggleCodeBlock },
|
||||
{ key: 'Mod-s', run: toggleStrikethrough },
|
||||
{ key: 'Mod-Shift-.', run: toggleQuote },
|
||||
{ key: 'Enter', run: insertNewlineContinueMark },
|
||||
{ key: 'Backspace', run: deleteMarkupBackward },
|
||||
{ key: 'Mod-b', run: toggleBold },
|
||||
{ key: 'Mod-i', run: toggleItalic },
|
||||
{ key: 'Mod-e', run: toggleCodeBlock },
|
||||
{ key: 'Mod-s', run: toggleStrikethrough },
|
||||
{ key: 'Mod-Shift-.', run: toggleQuote },
|
||||
]
|
||||
|
||||
2
packages/utils/eslint.config.mjs
Normal file
2
packages/utils/eslint.config.mjs
Normal file
@@ -0,0 +1,2 @@
|
||||
import config from '@modrinth/tooling-config/eslint/nuxt.mjs'
|
||||
export default config
|
||||
@@ -1,20 +1,21 @@
|
||||
import hljs from 'highlight.js/lib/core'
|
||||
// Scripting
|
||||
import javascript from 'highlight.js/lib/languages/javascript'
|
||||
import lua from 'highlight.js/lib/languages/lua'
|
||||
import python from 'highlight.js/lib/languages/python'
|
||||
// Coding
|
||||
import groovy from 'highlight.js/lib/languages/groovy'
|
||||
import java from 'highlight.js/lib/languages/java'
|
||||
import kotlin from 'highlight.js/lib/languages/kotlin'
|
||||
import scala from 'highlight.js/lib/languages/scala'
|
||||
// Configs
|
||||
import gradle from 'highlight.js/lib/languages/gradle'
|
||||
// Coding
|
||||
import groovy from 'highlight.js/lib/languages/groovy'
|
||||
import ini from 'highlight.js/lib/languages/ini'
|
||||
import java from 'highlight.js/lib/languages/java'
|
||||
// Scripting
|
||||
import javascript from 'highlight.js/lib/languages/javascript'
|
||||
import json from 'highlight.js/lib/languages/json'
|
||||
import kotlin from 'highlight.js/lib/languages/kotlin'
|
||||
import lua from 'highlight.js/lib/languages/lua'
|
||||
import properties from 'highlight.js/lib/languages/properties'
|
||||
import python from 'highlight.js/lib/languages/python'
|
||||
import scala from 'highlight.js/lib/languages/scala'
|
||||
import xml from 'highlight.js/lib/languages/xml'
|
||||
import yaml from 'highlight.js/lib/languages/yaml'
|
||||
|
||||
import { configuredXss, md } from './parse'
|
||||
|
||||
/* REGISTRATION */
|
||||
@@ -48,18 +49,18 @@ hljs.registerAliases(['yml'], { languageName: 'yaml' })
|
||||
hljs.registerAliases(['html', 'htm', 'xhtml', 'mcui', 'fxml'], { languageName: 'xml' })
|
||||
|
||||
export const renderHighlightedString = (string) =>
|
||||
configuredXss.process(
|
||||
md({
|
||||
highlight(str, lang) {
|
||||
if (lang && hljs.getLanguage(lang)) {
|
||||
try {
|
||||
return hljs.highlight(str, { language: lang }).value
|
||||
} catch {
|
||||
/* empty */
|
||||
}
|
||||
}
|
||||
configuredXss.process(
|
||||
md({
|
||||
highlight(str, lang) {
|
||||
if (lang && hljs.getLanguage(lang)) {
|
||||
try {
|
||||
return hljs.highlight(str, { language: lang }).value
|
||||
} catch {
|
||||
/* empty */
|
||||
}
|
||||
}
|
||||
|
||||
return ''
|
||||
},
|
||||
}).render(string),
|
||||
)
|
||||
return ''
|
||||
},
|
||||
}).render(string),
|
||||
)
|
||||
|
||||
@@ -4,8 +4,8 @@ export * from './highlight'
|
||||
export * from './licenses'
|
||||
export * from './parse'
|
||||
export * from './projects'
|
||||
export * from './servers'
|
||||
export * from './three/skin-rendering'
|
||||
export * from './types'
|
||||
export * from './users'
|
||||
export * from './utils'
|
||||
export * from './servers'
|
||||
export * from './three/skin-rendering'
|
||||
|
||||
@@ -1,76 +1,76 @@
|
||||
export interface BuiltinLicense {
|
||||
friendly: string
|
||||
short: string
|
||||
requiresOnlyOrLater?: boolean
|
||||
friendly: string
|
||||
short: string
|
||||
requiresOnlyOrLater?: boolean
|
||||
}
|
||||
|
||||
export const builtinLicenses: BuiltinLicense[] = [
|
||||
{ friendly: 'Custom', short: '' },
|
||||
{
|
||||
friendly: 'All Rights Reserved/No License',
|
||||
short: 'All-Rights-Reserved',
|
||||
},
|
||||
{ friendly: 'Apache License 2.0', short: 'Apache-2.0' },
|
||||
{
|
||||
friendly: 'BSD 2-Clause "Simplified" License',
|
||||
short: 'BSD-2-Clause',
|
||||
},
|
||||
{
|
||||
friendly: 'BSD 3-Clause "New" or "Revised" License',
|
||||
short: 'BSD-3-Clause',
|
||||
},
|
||||
{
|
||||
friendly: 'CC Zero (Public Domain equivalent)',
|
||||
short: 'CC0-1.0',
|
||||
},
|
||||
{ friendly: 'CC-BY 4.0', short: 'CC-BY-4.0' },
|
||||
{
|
||||
friendly: 'CC-BY-SA 4.0',
|
||||
short: 'CC-BY-SA-4.0',
|
||||
},
|
||||
{
|
||||
friendly: 'CC-BY-NC 4.0',
|
||||
short: 'CC-BY-NC-4.0',
|
||||
},
|
||||
{
|
||||
friendly: 'CC-BY-NC-SA 4.0',
|
||||
short: 'CC-BY-NC-SA-4.0',
|
||||
},
|
||||
{
|
||||
friendly: 'CC-BY-ND 4.0',
|
||||
short: 'CC-BY-ND-4.0',
|
||||
},
|
||||
{
|
||||
friendly: 'CC-BY-NC-ND 4.0',
|
||||
short: 'CC-BY-NC-ND-4.0',
|
||||
},
|
||||
{
|
||||
friendly: 'GNU Affero General Public License v3',
|
||||
short: 'AGPL-3.0',
|
||||
requiresOnlyOrLater: true,
|
||||
},
|
||||
{
|
||||
friendly: 'GNU Lesser General Public License v2.1',
|
||||
short: 'LGPL-2.1',
|
||||
requiresOnlyOrLater: true,
|
||||
},
|
||||
{
|
||||
friendly: 'GNU Lesser General Public License v3',
|
||||
short: 'LGPL-3.0',
|
||||
requiresOnlyOrLater: true,
|
||||
},
|
||||
{
|
||||
friendly: 'GNU General Public License v2',
|
||||
short: 'GPL-2.0',
|
||||
requiresOnlyOrLater: true,
|
||||
},
|
||||
{
|
||||
friendly: 'GNU General Public License v3',
|
||||
short: 'GPL-3.0',
|
||||
requiresOnlyOrLater: true,
|
||||
},
|
||||
{ friendly: 'ISC License', short: 'ISC' },
|
||||
{ friendly: 'MIT License', short: 'MIT' },
|
||||
{ friendly: 'Mozilla Public License 2.0', short: 'MPL-2.0' },
|
||||
{ friendly: 'zlib License', short: 'Zlib' },
|
||||
{ friendly: 'Custom', short: '' },
|
||||
{
|
||||
friendly: 'All Rights Reserved/No License',
|
||||
short: 'All-Rights-Reserved',
|
||||
},
|
||||
{ friendly: 'Apache License 2.0', short: 'Apache-2.0' },
|
||||
{
|
||||
friendly: 'BSD 2-Clause "Simplified" License',
|
||||
short: 'BSD-2-Clause',
|
||||
},
|
||||
{
|
||||
friendly: 'BSD 3-Clause "New" or "Revised" License',
|
||||
short: 'BSD-3-Clause',
|
||||
},
|
||||
{
|
||||
friendly: 'CC Zero (Public Domain equivalent)',
|
||||
short: 'CC0-1.0',
|
||||
},
|
||||
{ friendly: 'CC-BY 4.0', short: 'CC-BY-4.0' },
|
||||
{
|
||||
friendly: 'CC-BY-SA 4.0',
|
||||
short: 'CC-BY-SA-4.0',
|
||||
},
|
||||
{
|
||||
friendly: 'CC-BY-NC 4.0',
|
||||
short: 'CC-BY-NC-4.0',
|
||||
},
|
||||
{
|
||||
friendly: 'CC-BY-NC-SA 4.0',
|
||||
short: 'CC-BY-NC-SA-4.0',
|
||||
},
|
||||
{
|
||||
friendly: 'CC-BY-ND 4.0',
|
||||
short: 'CC-BY-ND-4.0',
|
||||
},
|
||||
{
|
||||
friendly: 'CC-BY-NC-ND 4.0',
|
||||
short: 'CC-BY-NC-ND-4.0',
|
||||
},
|
||||
{
|
||||
friendly: 'GNU Affero General Public License v3',
|
||||
short: 'AGPL-3.0',
|
||||
requiresOnlyOrLater: true,
|
||||
},
|
||||
{
|
||||
friendly: 'GNU Lesser General Public License v2.1',
|
||||
short: 'LGPL-2.1',
|
||||
requiresOnlyOrLater: true,
|
||||
},
|
||||
{
|
||||
friendly: 'GNU Lesser General Public License v3',
|
||||
short: 'LGPL-3.0',
|
||||
requiresOnlyOrLater: true,
|
||||
},
|
||||
{
|
||||
friendly: 'GNU General Public License v2',
|
||||
short: 'GPL-2.0',
|
||||
requiresOnlyOrLater: true,
|
||||
},
|
||||
{
|
||||
friendly: 'GNU General Public License v3',
|
||||
short: 'GPL-3.0',
|
||||
requiresOnlyOrLater: true,
|
||||
},
|
||||
{ friendly: 'ISC License', short: 'ISC' },
|
||||
{ friendly: 'MIT License', short: 'MIT' },
|
||||
{ friendly: 'Mozilla Public License 2.0', short: 'MPL-2.0' },
|
||||
{ friendly: 'zlib License', short: 'Zlib' },
|
||||
] as const
|
||||
|
||||
@@ -1,31 +1,29 @@
|
||||
{
|
||||
"name": "@modrinth/utils",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"main": "./index.ts",
|
||||
"types": "./index.d.ts",
|
||||
"scripts": {
|
||||
"lint": "eslint . && prettier --check .",
|
||||
"fix": "eslint . --fix && prettier --write ."
|
||||
},
|
||||
"devDependencies": {
|
||||
"eslint": "^8.57.0",
|
||||
"eslint-config-custom": "workspace:*",
|
||||
"tsconfig": "workspace:*"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "^6.3.2",
|
||||
"@codemirror/lang-markdown": "^6.2.3",
|
||||
"@codemirror/language": "^6.9.3",
|
||||
"@codemirror/state": "^6.3.2",
|
||||
"@codemirror/view": "^6.22.1",
|
||||
"@types/markdown-it": "^14.1.1",
|
||||
"@types/three": "^0.172.0",
|
||||
"dayjs": "^1.11.10",
|
||||
"highlight.js": "^11.9.0",
|
||||
"markdown-it": "^14.1.0",
|
||||
"ofetch": "^1.3.4",
|
||||
"three": "^0.172.0",
|
||||
"xss": "^1.0.14"
|
||||
}
|
||||
"name": "@modrinth/utils",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"main": "./index.ts",
|
||||
"types": "./index.d.ts",
|
||||
"scripts": {
|
||||
"lint": "eslint . && prettier --check .",
|
||||
"fix": "eslint . --fix && prettier --write ."
|
||||
},
|
||||
"devDependencies": {
|
||||
"@modrinth/tooling-config": "workspace:*"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "^6.3.2",
|
||||
"@codemirror/lang-markdown": "^6.2.3",
|
||||
"@codemirror/language": "^6.9.3",
|
||||
"@codemirror/state": "^6.3.2",
|
||||
"@codemirror/view": "^6.22.1",
|
||||
"@types/markdown-it": "^14.1.1",
|
||||
"@types/three": "^0.172.0",
|
||||
"dayjs": "^1.11.10",
|
||||
"highlight.js": "^11.9.0",
|
||||
"markdown-it": "^14.1.0",
|
||||
"ofetch": "^1.3.4",
|
||||
"three": "^0.172.0",
|
||||
"xss": "^1.0.14"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,168 +2,168 @@ import MarkdownIt from 'markdown-it'
|
||||
import { escapeAttrValue, FilterXSS, safeAttrValue, whiteList } from 'xss'
|
||||
|
||||
export const configuredXss = new FilterXSS({
|
||||
whiteList: {
|
||||
...whiteList,
|
||||
summary: [],
|
||||
h1: ['id'],
|
||||
h2: ['id'],
|
||||
h3: ['id'],
|
||||
h4: ['id'],
|
||||
h5: ['id'],
|
||||
h6: ['id'],
|
||||
kbd: ['id'],
|
||||
input: ['checked', 'disabled', 'type'],
|
||||
iframe: ['width', 'height', 'allowfullscreen', 'frameborder', 'start', 'end'],
|
||||
img: [...(whiteList.img || []), 'usemap', 'style', 'align'],
|
||||
map: ['name'],
|
||||
area: [...(whiteList.a || []), 'coords'],
|
||||
a: [...(whiteList.a || []), 'rel'],
|
||||
td: [...(whiteList.td || []), 'style'],
|
||||
th: [...(whiteList.th || []), 'style'],
|
||||
picture: [],
|
||||
source: ['media', 'sizes', 'src', 'srcset', 'type'],
|
||||
p: [...(whiteList.p || []), 'align'],
|
||||
div: [...(whiteList.p || []), 'align'],
|
||||
},
|
||||
css: {
|
||||
whiteList: {
|
||||
'image-rendering': /^pixelated$/,
|
||||
'text-align': /^center|left|right$/,
|
||||
float: /^left|right$/,
|
||||
},
|
||||
},
|
||||
onIgnoreTagAttr: (tag, name, value) => {
|
||||
// Allow iframes from acceptable sources
|
||||
if (tag === 'iframe' && name === 'src') {
|
||||
const allowedSources = [
|
||||
{
|
||||
url: /^https?:\/\/(www\.)?youtube(-nocookie)?\.com\/embed\/[a-zA-Z0-9_-]{11}/,
|
||||
allowedParameters: [/start=\d+/, /end=\d+/],
|
||||
},
|
||||
{
|
||||
url: /^https?:\/\/(www\.)?discord\.com\/widget/,
|
||||
allowedParameters: [/id=\d{18,19}/],
|
||||
},
|
||||
]
|
||||
whiteList: {
|
||||
...whiteList,
|
||||
summary: [],
|
||||
h1: ['id'],
|
||||
h2: ['id'],
|
||||
h3: ['id'],
|
||||
h4: ['id'],
|
||||
h5: ['id'],
|
||||
h6: ['id'],
|
||||
kbd: ['id'],
|
||||
input: ['checked', 'disabled', 'type'],
|
||||
iframe: ['width', 'height', 'allowfullscreen', 'frameborder', 'start', 'end'],
|
||||
img: [...(whiteList.img || []), 'usemap', 'style', 'align'],
|
||||
map: ['name'],
|
||||
area: [...(whiteList.a || []), 'coords'],
|
||||
a: [...(whiteList.a || []), 'rel'],
|
||||
td: [...(whiteList.td || []), 'style'],
|
||||
th: [...(whiteList.th || []), 'style'],
|
||||
picture: [],
|
||||
source: ['media', 'sizes', 'src', 'srcset', 'type'],
|
||||
p: [...(whiteList.p || []), 'align'],
|
||||
div: [...(whiteList.p || []), 'align'],
|
||||
},
|
||||
css: {
|
||||
whiteList: {
|
||||
'image-rendering': /^pixelated$/,
|
||||
'text-align': /^center|left|right$/,
|
||||
float: /^left|right$/,
|
||||
},
|
||||
},
|
||||
onIgnoreTagAttr: (tag, name, value) => {
|
||||
// Allow iframes from acceptable sources
|
||||
if (tag === 'iframe' && name === 'src') {
|
||||
const allowedSources = [
|
||||
{
|
||||
url: /^https?:\/\/(www\.)?youtube(-nocookie)?\.com\/embed\/[a-zA-Z0-9_-]{11}/,
|
||||
allowedParameters: [/start=\d+/, /end=\d+/],
|
||||
},
|
||||
{
|
||||
url: /^https?:\/\/(www\.)?discord\.com\/widget/,
|
||||
allowedParameters: [/id=\d{18,19}/],
|
||||
},
|
||||
]
|
||||
|
||||
const url = new URL(value)
|
||||
const url = new URL(value)
|
||||
|
||||
for (const source of allowedSources) {
|
||||
if (!source.url.test(url.href)) {
|
||||
continue
|
||||
}
|
||||
for (const source of allowedSources) {
|
||||
if (!source.url.test(url.href)) {
|
||||
continue
|
||||
}
|
||||
|
||||
const newSearchParams = new URLSearchParams()
|
||||
url.searchParams.forEach((value, key) => {
|
||||
if (!source.allowedParameters.some((param) => param.test(`${key}=${value}`))) {
|
||||
newSearchParams.delete(key)
|
||||
}
|
||||
})
|
||||
const newSearchParams = new URLSearchParams()
|
||||
url.searchParams.forEach((value, key) => {
|
||||
if (!source.allowedParameters.some((param) => param.test(`${key}=${value}`))) {
|
||||
newSearchParams.delete(key)
|
||||
}
|
||||
})
|
||||
|
||||
url.search = newSearchParams.toString()
|
||||
return `${name}="${escapeAttrValue(url.toString())}"`
|
||||
}
|
||||
}
|
||||
url.search = newSearchParams.toString()
|
||||
return `${name}="${escapeAttrValue(url.toString())}"`
|
||||
}
|
||||
}
|
||||
|
||||
// For Highlight.JS
|
||||
if (name === 'class' && ['pre', 'code', 'span'].includes(tag)) {
|
||||
const allowedClasses: string[] = []
|
||||
for (const className of value.split(/\s/g)) {
|
||||
if (className.startsWith('hljs-') || className.startsWith('language-')) {
|
||||
allowedClasses.push(className)
|
||||
}
|
||||
}
|
||||
return `${name}="${escapeAttrValue(allowedClasses.join(' '))}"`
|
||||
}
|
||||
},
|
||||
safeAttrValue(tag, name, value, cssFilter) {
|
||||
if (
|
||||
(tag === 'img' || tag === 'video' || tag === 'audio' || tag === 'source') &&
|
||||
(name === 'src' || name === 'srcset') &&
|
||||
!value.startsWith('data:')
|
||||
) {
|
||||
try {
|
||||
const url = new URL(value)
|
||||
// For Highlight.JS
|
||||
if (name === 'class' && ['pre', 'code', 'span'].includes(tag)) {
|
||||
const allowedClasses: string[] = []
|
||||
for (const className of value.split(/\s/g)) {
|
||||
if (className.startsWith('hljs-') || className.startsWith('language-')) {
|
||||
allowedClasses.push(className)
|
||||
}
|
||||
}
|
||||
return `${name}="${escapeAttrValue(allowedClasses.join(' '))}"`
|
||||
}
|
||||
},
|
||||
safeAttrValue(tag, name, value, cssFilter) {
|
||||
if (
|
||||
(tag === 'img' || tag === 'video' || tag === 'audio' || tag === 'source') &&
|
||||
(name === 'src' || name === 'srcset') &&
|
||||
!value.startsWith('data:')
|
||||
) {
|
||||
try {
|
||||
const url = new URL(value)
|
||||
|
||||
if (url.hostname.includes('wsrv.nl')) {
|
||||
url.searchParams.delete('errorredirect')
|
||||
}
|
||||
if (url.hostname.includes('wsrv.nl')) {
|
||||
url.searchParams.delete('errorredirect')
|
||||
}
|
||||
|
||||
const allowedHostnames = [
|
||||
'imgur.com',
|
||||
'i.imgur.com',
|
||||
'cdn-raw.modrinth.com',
|
||||
'cdn.modrinth.com',
|
||||
'staging-cdn-raw.modrinth.com',
|
||||
'staging-cdn.modrinth.com',
|
||||
'github.com',
|
||||
'raw.githubusercontent.com',
|
||||
'img.shields.io',
|
||||
'i.postimg.cc',
|
||||
'wsrv.nl',
|
||||
'cf.way2muchnoise.eu',
|
||||
'bstats.org',
|
||||
]
|
||||
const allowedHostnames = [
|
||||
'imgur.com',
|
||||
'i.imgur.com',
|
||||
'cdn-raw.modrinth.com',
|
||||
'cdn.modrinth.com',
|
||||
'staging-cdn-raw.modrinth.com',
|
||||
'staging-cdn.modrinth.com',
|
||||
'github.com',
|
||||
'raw.githubusercontent.com',
|
||||
'img.shields.io',
|
||||
'i.postimg.cc',
|
||||
'wsrv.nl',
|
||||
'cf.way2muchnoise.eu',
|
||||
'bstats.org',
|
||||
]
|
||||
|
||||
if (!allowedHostnames.includes(url.hostname)) {
|
||||
return safeAttrValue(
|
||||
tag,
|
||||
name,
|
||||
`https://wsrv.nl/?url=${encodeURIComponent(
|
||||
url.toString().replaceAll('&', '&'),
|
||||
)}&n=-1`,
|
||||
cssFilter,
|
||||
)
|
||||
}
|
||||
return safeAttrValue(tag, name, url.toString(), cssFilter)
|
||||
} catch {
|
||||
/* empty */
|
||||
}
|
||||
}
|
||||
if (!allowedHostnames.includes(url.hostname)) {
|
||||
return safeAttrValue(
|
||||
tag,
|
||||
name,
|
||||
`https://wsrv.nl/?url=${encodeURIComponent(
|
||||
url.toString().replaceAll('&', '&'),
|
||||
)}&n=-1`,
|
||||
cssFilter,
|
||||
)
|
||||
}
|
||||
return safeAttrValue(tag, name, url.toString(), cssFilter)
|
||||
} catch {
|
||||
/* empty */
|
||||
}
|
||||
}
|
||||
|
||||
return safeAttrValue(tag, name, value, cssFilter)
|
||||
},
|
||||
return safeAttrValue(tag, name, value, cssFilter)
|
||||
},
|
||||
})
|
||||
|
||||
export const md = (options = {}) => {
|
||||
const md = new MarkdownIt('default', {
|
||||
html: true,
|
||||
linkify: true,
|
||||
breaks: false,
|
||||
...options,
|
||||
})
|
||||
const md = new MarkdownIt('default', {
|
||||
html: true,
|
||||
linkify: true,
|
||||
breaks: false,
|
||||
...options,
|
||||
})
|
||||
|
||||
const defaultLinkOpenRenderer =
|
||||
md.renderer.rules.link_open ||
|
||||
function (tokens, idx, options, _env, self) {
|
||||
return self.renderToken(tokens, idx, options)
|
||||
}
|
||||
const defaultLinkOpenRenderer =
|
||||
md.renderer.rules.link_open ||
|
||||
function (tokens, idx, options, _env, self) {
|
||||
return self.renderToken(tokens, idx, options)
|
||||
}
|
||||
|
||||
md.renderer.rules.link_open = function (tokens, idx, options, env, self) {
|
||||
const token = tokens[idx]
|
||||
const index = token.attrIndex('href')
|
||||
md.renderer.rules.link_open = function (tokens, idx, options, env, self) {
|
||||
const token = tokens[idx]
|
||||
const index = token.attrIndex('href')
|
||||
|
||||
if (token.attrs && index !== -1) {
|
||||
const href = token.attrs[index][1]
|
||||
if (token.attrs && index !== -1) {
|
||||
const href = token.attrs[index][1]
|
||||
|
||||
try {
|
||||
const url = new URL(href)
|
||||
const allowedHostnames = ['modrinth.com']
|
||||
try {
|
||||
const url = new URL(href)
|
||||
const allowedHostnames = ['modrinth.com']
|
||||
|
||||
if (allowedHostnames.includes(url.hostname)) {
|
||||
return defaultLinkOpenRenderer(tokens, idx, options, env, self)
|
||||
}
|
||||
} catch {
|
||||
/* empty */
|
||||
}
|
||||
}
|
||||
if (allowedHostnames.includes(url.hostname)) {
|
||||
return defaultLinkOpenRenderer(tokens, idx, options, env, self)
|
||||
}
|
||||
} catch {
|
||||
/* empty */
|
||||
}
|
||||
}
|
||||
|
||||
tokens[idx].attrSet('rel', 'noopener nofollow ugc')
|
||||
tokens[idx].attrSet('rel', 'noopener nofollow ugc')
|
||||
|
||||
return defaultLinkOpenRenderer(tokens, idx, options, env, self)
|
||||
}
|
||||
return defaultLinkOpenRenderer(tokens, idx, options, env, self)
|
||||
}
|
||||
|
||||
return md
|
||||
return md
|
||||
}
|
||||
|
||||
export const renderString = (string: string) => configuredXss.process(md().render(string))
|
||||
|
||||
@@ -1,31 +1,31 @@
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
|
||||
export const isApproved = (project) => {
|
||||
return project && APPROVED_PROJECT_STATUSES.includes(project.status)
|
||||
return project && APPROVED_PROJECT_STATUSES.includes(project.status)
|
||||
}
|
||||
|
||||
export const isListed = (project) => {
|
||||
return project && LISTED_PROJECT_STATUSES.includes(project.status)
|
||||
return project && LISTED_PROJECT_STATUSES.includes(project.status)
|
||||
}
|
||||
|
||||
export const isUnlisted = (project) => {
|
||||
return project && UNLISTED_PROJECT_STATUSES.includes(project.status)
|
||||
return project && UNLISTED_PROJECT_STATUSES.includes(project.status)
|
||||
}
|
||||
|
||||
export const isPrivate = (project) => {
|
||||
return project && PRIVATE_PROJECT_STATUSES.includes(project.status)
|
||||
return project && PRIVATE_PROJECT_STATUSES.includes(project.status)
|
||||
}
|
||||
|
||||
export const isRejected = (project) => {
|
||||
return project && REJECTED_PROJECT_STATUSES.includes(project.status)
|
||||
return project && REJECTED_PROJECT_STATUSES.includes(project.status)
|
||||
}
|
||||
|
||||
export const isUnderReview = (project) => {
|
||||
return project && UNDER_REVIEW_PROJECT_STATUSES.includes(project.status)
|
||||
return project && UNDER_REVIEW_PROJECT_STATUSES.includes(project.status)
|
||||
}
|
||||
|
||||
export const isDraft = (project) => {
|
||||
return project && DRAFT_PROJECT_STATUSES.includes(project.status)
|
||||
return project && DRAFT_PROJECT_STATUSES.includes(project.status)
|
||||
}
|
||||
|
||||
export const APPROVED_PROJECT_STATUSES = ['approved', 'archived', 'unlisted', 'private']
|
||||
@@ -37,199 +37,199 @@ export const UNDER_REVIEW_PROJECT_STATUSES = ['processing']
|
||||
export const DRAFT_PROJECT_STATUSES = ['draft']
|
||||
|
||||
export type GameVersionTag = {
|
||||
version: string
|
||||
version_type: string
|
||||
date: string
|
||||
major: boolean
|
||||
version: string
|
||||
version_type: string
|
||||
date: string
|
||||
major: boolean
|
||||
}
|
||||
|
||||
export type DisplayProjectType =
|
||||
| 'mod'
|
||||
| 'plugin'
|
||||
| 'datapack'
|
||||
| 'resourcepack'
|
||||
| 'modpack'
|
||||
| 'shader'
|
||||
| 'mod'
|
||||
| 'plugin'
|
||||
| 'datapack'
|
||||
| 'resourcepack'
|
||||
| 'modpack'
|
||||
| 'shader'
|
||||
|
||||
export type PlatformTag = {
|
||||
icon: string
|
||||
name: string
|
||||
supported_project_types: DisplayProjectType[]
|
||||
icon: string
|
||||
name: string
|
||||
supported_project_types: DisplayProjectType[]
|
||||
}
|
||||
|
||||
export function getVersionsToDisplay(project, allGameVersions: GameVersionTag[]) {
|
||||
return formatVersionsForDisplay(project.game_versions.slice(), allGameVersions)
|
||||
return formatVersionsForDisplay(project.game_versions.slice(), allGameVersions)
|
||||
}
|
||||
|
||||
export function formatVersionsForDisplay(
|
||||
gameVersions: string[],
|
||||
allGameVersions: GameVersionTag[],
|
||||
gameVersions: string[],
|
||||
allGameVersions: GameVersionTag[],
|
||||
) {
|
||||
const inputVersions = gameVersions.slice()
|
||||
const allVersions = allGameVersions.slice()
|
||||
const inputVersions = gameVersions.slice()
|
||||
const allVersions = allGameVersions.slice()
|
||||
|
||||
const allSnapshots = allVersions.filter((version) => version.version_type === 'snapshot')
|
||||
const allReleases = allVersions.filter((version) => version.version_type === 'release')
|
||||
const allLegacy = allVersions.filter(
|
||||
(version) => version.version_type !== 'snapshot' && version.version_type !== 'release',
|
||||
)
|
||||
const allSnapshots = allVersions.filter((version) => version.version_type === 'snapshot')
|
||||
const allReleases = allVersions.filter((version) => version.version_type === 'release')
|
||||
const allLegacy = allVersions.filter(
|
||||
(version) => version.version_type !== 'snapshot' && version.version_type !== 'release',
|
||||
)
|
||||
|
||||
{
|
||||
const indices = allVersions.reduce((map, gameVersion, index) => {
|
||||
map[gameVersion.version] = index
|
||||
return map
|
||||
}, {})
|
||||
inputVersions.sort((a, b) => indices[a] - indices[b])
|
||||
}
|
||||
{
|
||||
const indices = allVersions.reduce((map, gameVersion, index) => {
|
||||
map[gameVersion.version] = index
|
||||
return map
|
||||
}, {})
|
||||
inputVersions.sort((a, b) => indices[a] - indices[b])
|
||||
}
|
||||
|
||||
const releaseVersions = inputVersions.filter((projVer) =>
|
||||
allReleases.some((gameVer) => gameVer.version === projVer),
|
||||
)
|
||||
const releaseVersions = inputVersions.filter((projVer) =>
|
||||
allReleases.some((gameVer) => gameVer.version === projVer),
|
||||
)
|
||||
|
||||
const dateString = allReleases.find((version) => version.version === releaseVersions[0])?.date
|
||||
const dateString = allReleases.find((version) => version.version === releaseVersions[0])?.date
|
||||
|
||||
const latestReleaseVersionDate = dateString ? Date.parse(dateString) : 0
|
||||
const latestSnapshot = inputVersions.find((projVer) =>
|
||||
allSnapshots.some(
|
||||
(gameVer) =>
|
||||
gameVer.version === projVer &&
|
||||
(!latestReleaseVersionDate || latestReleaseVersionDate < Date.parse(gameVer.date)),
|
||||
),
|
||||
)
|
||||
const latestReleaseVersionDate = dateString ? Date.parse(dateString) : 0
|
||||
const latestSnapshot = inputVersions.find((projVer) =>
|
||||
allSnapshots.some(
|
||||
(gameVer) =>
|
||||
gameVer.version === projVer &&
|
||||
(!latestReleaseVersionDate || latestReleaseVersionDate < Date.parse(gameVer.date)),
|
||||
),
|
||||
)
|
||||
|
||||
const allReleasesGrouped = groupVersions(
|
||||
allReleases.map((release) => release.version),
|
||||
false,
|
||||
)
|
||||
const projectVersionsGrouped = groupVersions(releaseVersions, true)
|
||||
const allReleasesGrouped = groupVersions(
|
||||
allReleases.map((release) => release.version),
|
||||
false,
|
||||
)
|
||||
const projectVersionsGrouped = groupVersions(releaseVersions, true)
|
||||
|
||||
const releaseVersionsAsRanges = projectVersionsGrouped.map(({ major, minor }) => {
|
||||
if (minor.length === 1) {
|
||||
return formatMinecraftMinorVersion(major, minor[0])
|
||||
}
|
||||
const releaseVersionsAsRanges = projectVersionsGrouped.map(({ major, minor }) => {
|
||||
if (minor.length === 1) {
|
||||
return formatMinecraftMinorVersion(major, minor[0])
|
||||
}
|
||||
|
||||
const range = allReleasesGrouped.find((x) => x.major === major)
|
||||
const range = allReleasesGrouped.find((x) => x.major === major)
|
||||
|
||||
if (range?.minor.every((value, index) => value === minor[index])) {
|
||||
return `${major}.x`
|
||||
}
|
||||
if (range?.minor.every((value, index) => value === minor[index])) {
|
||||
return `${major}.x`
|
||||
}
|
||||
|
||||
return `${formatMinecraftMinorVersion(major, minor[0])}–${formatMinecraftMinorVersion(major, minor[minor.length - 1])}`
|
||||
})
|
||||
return `${formatMinecraftMinorVersion(major, minor[0])}–${formatMinecraftMinorVersion(major, minor[minor.length - 1])}`
|
||||
})
|
||||
|
||||
const legacyVersionsAsRanges = groupConsecutiveIndices(
|
||||
inputVersions.filter((projVer) => allLegacy.some((gameVer) => gameVer.version === projVer)),
|
||||
allLegacy,
|
||||
)
|
||||
const legacyVersionsAsRanges = groupConsecutiveIndices(
|
||||
inputVersions.filter((projVer) => allLegacy.some((gameVer) => gameVer.version === projVer)),
|
||||
allLegacy,
|
||||
)
|
||||
|
||||
let output = [...legacyVersionsAsRanges]
|
||||
let output = [...legacyVersionsAsRanges]
|
||||
|
||||
// show all snapshots if there's no release versions
|
||||
if (releaseVersionsAsRanges.length === 0) {
|
||||
const snapshotVersionsAsRanges = groupConsecutiveIndices(
|
||||
inputVersions.filter((projVer) =>
|
||||
allSnapshots.some((gameVer) => gameVer.version === projVer),
|
||||
),
|
||||
allSnapshots,
|
||||
)
|
||||
output = [...snapshotVersionsAsRanges, ...output]
|
||||
} else {
|
||||
output = [...releaseVersionsAsRanges, ...output]
|
||||
}
|
||||
// show all snapshots if there's no release versions
|
||||
if (releaseVersionsAsRanges.length === 0) {
|
||||
const snapshotVersionsAsRanges = groupConsecutiveIndices(
|
||||
inputVersions.filter((projVer) =>
|
||||
allSnapshots.some((gameVer) => gameVer.version === projVer),
|
||||
),
|
||||
allSnapshots,
|
||||
)
|
||||
output = [...snapshotVersionsAsRanges, ...output]
|
||||
} else {
|
||||
output = [...releaseVersionsAsRanges, ...output]
|
||||
}
|
||||
|
||||
if (latestSnapshot && !output.includes(latestSnapshot)) {
|
||||
output = [latestSnapshot, ...output]
|
||||
}
|
||||
return output
|
||||
if (latestSnapshot && !output.includes(latestSnapshot)) {
|
||||
output = [latestSnapshot, ...output]
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
const mcVersionRegex = /^([0-9]+.[0-9]+)(.[0-9]+)?$/
|
||||
|
||||
type VersionRange = {
|
||||
major: string
|
||||
minor: number[]
|
||||
major: string
|
||||
minor: number[]
|
||||
}
|
||||
|
||||
function groupVersions(versions: string[], consecutive = false) {
|
||||
return versions
|
||||
.slice()
|
||||
.reverse()
|
||||
.reduce((ranges: VersionRange[], version: string) => {
|
||||
const matchesVersion = version.match(mcVersionRegex)
|
||||
return versions
|
||||
.slice()
|
||||
.reverse()
|
||||
.reduce((ranges: VersionRange[], version: string) => {
|
||||
const matchesVersion = version.match(mcVersionRegex)
|
||||
|
||||
if (matchesVersion) {
|
||||
const majorVersion = matchesVersion[1]
|
||||
const minorVersion = matchesVersion[2]
|
||||
const minorNumeric = minorVersion ? parseInt(minorVersion.replace('.', '')) : 0
|
||||
if (matchesVersion) {
|
||||
const majorVersion = matchesVersion[1]
|
||||
const minorVersion = matchesVersion[2]
|
||||
const minorNumeric = minorVersion ? parseInt(minorVersion.replace('.', '')) : 0
|
||||
|
||||
const prevInRange = ranges.find(
|
||||
(x) => x.major === majorVersion && (!consecutive || x.minor.at(-1) === minorNumeric - 1),
|
||||
)
|
||||
if (prevInRange) {
|
||||
prevInRange.minor.push(minorNumeric)
|
||||
return ranges
|
||||
}
|
||||
const prevInRange = ranges.find(
|
||||
(x) => x.major === majorVersion && (!consecutive || x.minor.at(-1) === minorNumeric - 1),
|
||||
)
|
||||
if (prevInRange) {
|
||||
prevInRange.minor.push(minorNumeric)
|
||||
return ranges
|
||||
}
|
||||
|
||||
return [...ranges, { major: majorVersion, minor: [minorNumeric] }]
|
||||
}
|
||||
return [...ranges, { major: majorVersion, minor: [minorNumeric] }]
|
||||
}
|
||||
|
||||
return ranges
|
||||
}, [])
|
||||
.reverse()
|
||||
return ranges
|
||||
}, [])
|
||||
.reverse()
|
||||
}
|
||||
|
||||
function groupConsecutiveIndices(versions: string[], referenceList: GameVersionTag[]) {
|
||||
if (!versions || versions.length === 0) {
|
||||
return []
|
||||
}
|
||||
if (!versions || versions.length === 0) {
|
||||
return []
|
||||
}
|
||||
|
||||
const referenceMap = new Map()
|
||||
referenceList.forEach((item, index) => {
|
||||
referenceMap.set(item.version, index)
|
||||
})
|
||||
const referenceMap = new Map()
|
||||
referenceList.forEach((item, index) => {
|
||||
referenceMap.set(item.version, index)
|
||||
})
|
||||
|
||||
const sortedList: string[] = versions
|
||||
.slice()
|
||||
.sort((a, b) => referenceMap.get(a) - referenceMap.get(b))
|
||||
const sortedList: string[] = versions
|
||||
.slice()
|
||||
.sort((a, b) => referenceMap.get(a) - referenceMap.get(b))
|
||||
|
||||
const ranges: string[] = []
|
||||
let start = sortedList[0]
|
||||
let previous = sortedList[0]
|
||||
const ranges: string[] = []
|
||||
let start = sortedList[0]
|
||||
let previous = sortedList[0]
|
||||
|
||||
for (let i = 1; i < sortedList.length; i++) {
|
||||
const current = sortedList[i]
|
||||
if (referenceMap.get(current) !== referenceMap.get(previous) + 1) {
|
||||
ranges.push(validateRange(`${previous}–${start}`))
|
||||
start = current
|
||||
}
|
||||
previous = current
|
||||
}
|
||||
for (let i = 1; i < sortedList.length; i++) {
|
||||
const current = sortedList[i]
|
||||
if (referenceMap.get(current) !== referenceMap.get(previous) + 1) {
|
||||
ranges.push(validateRange(`${previous}–${start}`))
|
||||
start = current
|
||||
}
|
||||
previous = current
|
||||
}
|
||||
|
||||
ranges.push(validateRange(`${previous}–${start}`))
|
||||
ranges.push(validateRange(`${previous}–${start}`))
|
||||
|
||||
return ranges
|
||||
return ranges
|
||||
}
|
||||
|
||||
function validateRange(range: string): string {
|
||||
switch (range) {
|
||||
case 'rd-132211–b1.8.1':
|
||||
return 'All legacy versions'
|
||||
case 'a1.0.4–b1.8.1':
|
||||
return 'All alpha and beta versions'
|
||||
case 'a1.0.4–a1.2.6':
|
||||
return 'All alpha versions'
|
||||
case 'b1.0–b1.8.1':
|
||||
return 'All beta versions'
|
||||
case 'rd-132211–inf20100618':
|
||||
return 'All pre-alpha versions'
|
||||
}
|
||||
const splitRange = range.split('–')
|
||||
if (splitRange && splitRange[0] === splitRange[1]) {
|
||||
return splitRange[0]
|
||||
}
|
||||
return range
|
||||
switch (range) {
|
||||
case 'rd-132211–b1.8.1':
|
||||
return 'All legacy versions'
|
||||
case 'a1.0.4–b1.8.1':
|
||||
return 'All alpha and beta versions'
|
||||
case 'a1.0.4–a1.2.6':
|
||||
return 'All alpha versions'
|
||||
case 'b1.0–b1.8.1':
|
||||
return 'All beta versions'
|
||||
case 'rd-132211–inf20100618':
|
||||
return 'All pre-alpha versions'
|
||||
}
|
||||
const splitRange = range.split('–')
|
||||
if (splitRange && splitRange[0] === splitRange[1]) {
|
||||
return splitRange[0]
|
||||
}
|
||||
return range
|
||||
}
|
||||
|
||||
function formatMinecraftMinorVersion(major: string, minor: number): string {
|
||||
return minor === 0 ? major : `${major}.${minor}`
|
||||
return minor === 0 ? major : `${major}.${minor}`
|
||||
}
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
export * from './modrinth-servers-multi-error'
|
||||
export * from './modrinth-servers-fetch-error'
|
||||
export * from './modrinth-server-error'
|
||||
export * from './modrinth-servers-fetch-error'
|
||||
export * from './modrinth-servers-multi-error'
|
||||
|
||||
@@ -1,59 +1,60 @@
|
||||
import { FetchError } from 'ofetch'
|
||||
import { V1ErrorInfo } from '../types'
|
||||
|
||||
import type { V1ErrorInfo } from '../types'
|
||||
|
||||
export class ModrinthServerError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly statusCode?: number,
|
||||
public readonly originalError?: Error,
|
||||
public readonly module?: string,
|
||||
public readonly v1Error?: V1ErrorInfo,
|
||||
) {
|
||||
let errorMessage = message
|
||||
let method = 'GET'
|
||||
let path = ''
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly statusCode?: number,
|
||||
public readonly originalError?: Error,
|
||||
public readonly module?: string,
|
||||
public readonly v1Error?: V1ErrorInfo,
|
||||
) {
|
||||
let errorMessage = message
|
||||
let method = 'GET'
|
||||
let path = ''
|
||||
|
||||
if (originalError instanceof FetchError) {
|
||||
const matches = message.match(/\[([A-Z]+)\]\s+"([^"]+)":/)
|
||||
if (matches) {
|
||||
method = matches[1]
|
||||
path = matches[2].replace(/https?:\/\/[^/]+\/[^/]+\/v\d+\//, '')
|
||||
}
|
||||
if (originalError instanceof FetchError) {
|
||||
const matches = message.match(/\[([A-Z]+)\]\s+"([^"]+)":/)
|
||||
if (matches) {
|
||||
method = matches[1]
|
||||
path = matches[2].replace(/https?:\/\/[^/]+\/[^/]+\/v\d+\//, '')
|
||||
}
|
||||
|
||||
const statusMessage = (() => {
|
||||
if (!statusCode) return 'Unknown Error'
|
||||
switch (statusCode) {
|
||||
case 400:
|
||||
return 'Bad Request'
|
||||
case 401:
|
||||
return 'Unauthorized'
|
||||
case 403:
|
||||
return 'Forbidden'
|
||||
case 404:
|
||||
return 'Not Found'
|
||||
case 408:
|
||||
return 'Request Timeout'
|
||||
case 429:
|
||||
return 'Too Many Requests'
|
||||
case 500:
|
||||
return 'Internal Server Error'
|
||||
case 502:
|
||||
return 'Bad Gateway'
|
||||
case 503:
|
||||
return 'Service Unavailable'
|
||||
case 504:
|
||||
return 'Gateway Timeout'
|
||||
default:
|
||||
return `HTTP ${statusCode}`
|
||||
}
|
||||
})()
|
||||
const statusMessage = (() => {
|
||||
if (!statusCode) return 'Unknown Error'
|
||||
switch (statusCode) {
|
||||
case 400:
|
||||
return 'Bad Request'
|
||||
case 401:
|
||||
return 'Unauthorized'
|
||||
case 403:
|
||||
return 'Forbidden'
|
||||
case 404:
|
||||
return 'Not Found'
|
||||
case 408:
|
||||
return 'Request Timeout'
|
||||
case 429:
|
||||
return 'Too Many Requests'
|
||||
case 500:
|
||||
return 'Internal Server Error'
|
||||
case 502:
|
||||
return 'Bad Gateway'
|
||||
case 503:
|
||||
return 'Service Unavailable'
|
||||
case 504:
|
||||
return 'Gateway Timeout'
|
||||
default:
|
||||
return `HTTP ${statusCode}`
|
||||
}
|
||||
})()
|
||||
|
||||
errorMessage = `[${method}] ${statusMessage} (${statusCode}) while fetching ${path}${module ? ` in ${module}` : ''}`
|
||||
} else {
|
||||
errorMessage = `${message}${statusCode ? ` (${statusCode})` : ''}${module ? ` in ${module}` : ''}`
|
||||
}
|
||||
errorMessage = `[${method}] ${statusMessage} (${statusCode}) while fetching ${path}${module ? ` in ${module}` : ''}`
|
||||
} else {
|
||||
errorMessage = `${message}${statusCode ? ` (${statusCode})` : ''}${module ? ` in ${module}` : ''}`
|
||||
}
|
||||
|
||||
super(errorMessage)
|
||||
this.name = 'ModrinthServersFetchError'
|
||||
}
|
||||
super(errorMessage)
|
||||
this.name = 'ModrinthServersFetchError'
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
export class ModrinthServersFetchError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public statusCode?: number,
|
||||
public originalError?: Error,
|
||||
) {
|
||||
super(message)
|
||||
this.name = 'ModrinthFetchError'
|
||||
}
|
||||
constructor(
|
||||
message: string,
|
||||
public statusCode?: number,
|
||||
public originalError?: Error,
|
||||
) {
|
||||
super(message)
|
||||
this.name = 'ModrinthFetchError'
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,27 +1,25 @@
|
||||
export class ModrinthServersMultiError extends Error {
|
||||
public readonly errors: Map<string, Error> = new Map()
|
||||
public readonly timestamp: number = Date.now()
|
||||
public readonly errors: Map<string, Error> = new Map()
|
||||
public readonly timestamp: number = Date.now()
|
||||
|
||||
constructor(message?: string) {
|
||||
super(message || 'Multiple errors occurred')
|
||||
this.name = 'MultipleErrors'
|
||||
}
|
||||
constructor(message?: string) {
|
||||
super(message || 'Multiple errors occurred')
|
||||
this.name = 'MultipleErrors'
|
||||
}
|
||||
|
||||
addError(module: string, error: Error) {
|
||||
this.errors.set(module, error)
|
||||
this.message = this.buildErrorMessage()
|
||||
}
|
||||
addError(module: string, error: Error) {
|
||||
this.errors.set(module, error)
|
||||
this.message = this.buildErrorMessage()
|
||||
}
|
||||
|
||||
hasErrors() {
|
||||
return this.errors.size > 0
|
||||
}
|
||||
hasErrors() {
|
||||
return this.errors.size > 0
|
||||
}
|
||||
|
||||
private buildErrorMessage(): string {
|
||||
return (
|
||||
Array.from(this.errors.entries())
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
.map(([_module, error]) => error.message)
|
||||
.join('\n')
|
||||
)
|
||||
}
|
||||
private buildErrorMessage(): string {
|
||||
return Array.from(this.errors.entries())
|
||||
|
||||
.map(([_module, error]) => error.message)
|
||||
.join('\n')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
import { ModrinthServerError } from '../errors'
|
||||
import type { ModrinthServerError } from '../errors'
|
||||
|
||||
export interface V1ErrorInfo {
|
||||
context?: string
|
||||
error: string
|
||||
description: string
|
||||
context?: string
|
||||
error: string
|
||||
description: string
|
||||
}
|
||||
|
||||
export interface JWTAuth {
|
||||
url: string
|
||||
token: string
|
||||
url: string
|
||||
token: string
|
||||
}
|
||||
|
||||
export interface ModuleError {
|
||||
error: ModrinthServerError
|
||||
timestamp: number
|
||||
error: ModrinthServerError
|
||||
timestamp: number
|
||||
}
|
||||
|
||||
export type ModuleName = 'general' | 'content' | 'backups' | 'network' | 'startup' | 'ws' | 'fs'
|
||||
|
||||
@@ -1,28 +1,28 @@
|
||||
import type { WSBackupTask, WSBackupState } from './websocket'
|
||||
import type { WSBackupState, WSBackupTask } from './websocket'
|
||||
|
||||
export interface Backup {
|
||||
id: string
|
||||
name: string
|
||||
created_at: string
|
||||
locked: boolean
|
||||
automated: boolean
|
||||
interrupted: boolean
|
||||
ongoing: boolean
|
||||
task: {
|
||||
[K in WSBackupTask]?: {
|
||||
progress: number
|
||||
state: WSBackupState
|
||||
}
|
||||
}
|
||||
id: string
|
||||
name: string
|
||||
created_at: string
|
||||
locked: boolean
|
||||
automated: boolean
|
||||
interrupted: boolean
|
||||
ongoing: boolean
|
||||
task: {
|
||||
[K in WSBackupTask]?: {
|
||||
progress: number
|
||||
state: WSBackupState
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface AutoBackupSettings {
|
||||
enabled: boolean
|
||||
interval: number
|
||||
enabled: boolean
|
||||
interval: number
|
||||
}
|
||||
|
||||
export interface ServerBackup {
|
||||
id: string
|
||||
name: string
|
||||
created_at: string
|
||||
id: string
|
||||
name: string
|
||||
created_at: string
|
||||
}
|
||||
|
||||
@@ -1,59 +1,59 @@
|
||||
import type { Project } from '../../types'
|
||||
import { Allocation } from './server'
|
||||
import { ServerBackup } from './backup'
|
||||
import { Mod } from './content'
|
||||
import type { ServerBackup } from './backup'
|
||||
import type { Mod } from './content'
|
||||
import type { Allocation } from './server'
|
||||
|
||||
export type ServerNotice = {
|
||||
id: number
|
||||
message: string
|
||||
title?: string
|
||||
level: 'info' | 'warn' | 'critical' | 'survey'
|
||||
dismissable: boolean
|
||||
announce_at: string
|
||||
expires: string
|
||||
assigned: {
|
||||
kind: 'server' | 'node'
|
||||
id: string
|
||||
name: string
|
||||
}[]
|
||||
dismissed_by: {
|
||||
server: string
|
||||
dismissed_on: string
|
||||
}[]
|
||||
id: number
|
||||
message: string
|
||||
title?: string
|
||||
level: 'info' | 'warn' | 'critical' | 'survey'
|
||||
dismissable: boolean
|
||||
announce_at: string
|
||||
expires: string
|
||||
assigned: {
|
||||
kind: 'server' | 'node'
|
||||
id: string
|
||||
name: string
|
||||
}[]
|
||||
dismissed_by: {
|
||||
server: string
|
||||
dismissed_on: string
|
||||
}[]
|
||||
}
|
||||
|
||||
export interface Server {
|
||||
server_id: string
|
||||
name: string
|
||||
status: string
|
||||
net: {
|
||||
ip: string
|
||||
port: number
|
||||
domain: string
|
||||
allocations: Allocation[]
|
||||
}
|
||||
game: string
|
||||
loader: string | null
|
||||
loader_version: string | null
|
||||
mc_version: string | null
|
||||
backup_quota: number
|
||||
used_backup_quota: number
|
||||
backups: ServerBackup[]
|
||||
mods: Mod[]
|
||||
project: Project | null
|
||||
suspension_reason: string | null
|
||||
image: string | null
|
||||
upstream?: {
|
||||
kind: 'modpack'
|
||||
project_id: string
|
||||
version_id: string
|
||||
}
|
||||
motd: string
|
||||
flows: {
|
||||
intro?: boolean
|
||||
}
|
||||
server_id: string
|
||||
name: string
|
||||
status: string
|
||||
net: {
|
||||
ip: string
|
||||
port: number
|
||||
domain: string
|
||||
allocations: Allocation[]
|
||||
}
|
||||
game: string
|
||||
loader: string | null
|
||||
loader_version: string | null
|
||||
mc_version: string | null
|
||||
backup_quota: number
|
||||
used_backup_quota: number
|
||||
backups: ServerBackup[]
|
||||
mods: Mod[]
|
||||
project: Project | null
|
||||
suspension_reason: string | null
|
||||
image: string | null
|
||||
upstream?: {
|
||||
kind: 'modpack'
|
||||
project_id: string
|
||||
version_id: string
|
||||
}
|
||||
motd: string
|
||||
flows: {
|
||||
intro?: boolean
|
||||
}
|
||||
}
|
||||
|
||||
export interface Servers {
|
||||
servers: Server[]
|
||||
servers: Server[]
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
export interface Mod {
|
||||
filename: string
|
||||
project_id: string | undefined
|
||||
version_id: string | undefined
|
||||
name: string | undefined
|
||||
version_number: string | undefined
|
||||
icon_url: string | undefined
|
||||
owner: string | undefined
|
||||
disabled: boolean
|
||||
installing: boolean
|
||||
filename: string
|
||||
project_id: string | undefined
|
||||
version_id: string | undefined
|
||||
name: string | undefined
|
||||
version_number: string | undefined
|
||||
icon_url: string | undefined
|
||||
owner: string | undefined
|
||||
disabled: boolean
|
||||
installing: boolean
|
||||
}
|
||||
|
||||
export type ContentType = 'mod' | 'plugin'
|
||||
|
||||
@@ -1,33 +1,33 @@
|
||||
import type { FSQueuedOp, FilesystemOp } from './websocket'
|
||||
import { JWTAuth } from './api'
|
||||
import type { JWTAuth } from './api'
|
||||
import type { FilesystemOp, FSQueuedOp } from './websocket'
|
||||
|
||||
export interface DirectoryItem {
|
||||
name: string
|
||||
type: 'directory' | 'file'
|
||||
count?: number
|
||||
modified: number
|
||||
created: number
|
||||
path: string
|
||||
name: string
|
||||
type: 'directory' | 'file'
|
||||
count?: number
|
||||
modified: number
|
||||
created: number
|
||||
path: string
|
||||
}
|
||||
|
||||
export interface FileUploadQuery {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
promise: Promise<any>
|
||||
onProgress: (
|
||||
callback: (progress: { loaded: number; total: number; progress: number }) => void,
|
||||
) => void
|
||||
cancel: () => void
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
promise: Promise<any>
|
||||
onProgress: (
|
||||
callback: (progress: { loaded: number; total: number; progress: number }) => void,
|
||||
) => void
|
||||
cancel: () => void
|
||||
}
|
||||
|
||||
export interface DirectoryResponse {
|
||||
items: DirectoryItem[]
|
||||
total: number
|
||||
current?: number
|
||||
items: DirectoryItem[]
|
||||
total: number
|
||||
current?: number
|
||||
}
|
||||
|
||||
export interface FSModule {
|
||||
auth: JWTAuth
|
||||
ops: FilesystemOp[]
|
||||
queuedOps: FSQueuedOp[]
|
||||
opsQueuedForModification: string[]
|
||||
auth: JWTAuth
|
||||
ops: FilesystemOp[]
|
||||
queuedOps: FSQueuedOp[]
|
||||
opsQueuedForModification: string[]
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
export * from './api'
|
||||
export * from './content'
|
||||
export * from './server'
|
||||
export * from './backup'
|
||||
export * from './filesystem'
|
||||
export * from './websocket'
|
||||
export * from './stats'
|
||||
export * from './common'
|
||||
export * from './content'
|
||||
export * from './filesystem'
|
||||
export * from './server'
|
||||
export * from './stats'
|
||||
export * from './websocket'
|
||||
|
||||
@@ -2,53 +2,53 @@ import type { Project } from '../../types'
|
||||
import type { ServerNotice } from './common'
|
||||
|
||||
export interface ServerGeneral {
|
||||
server_id: string
|
||||
name: string
|
||||
net: {
|
||||
ip: string
|
||||
port: number
|
||||
domain: string
|
||||
}
|
||||
game: string
|
||||
backup_quota: number
|
||||
used_backup_quota: number
|
||||
status: string
|
||||
suspension_reason: 'moderated' | 'paymentfailed' | 'cancelled' | 'upgrading' | 'other' | string
|
||||
loader: string
|
||||
loader_version: string
|
||||
mc_version: string
|
||||
upstream: {
|
||||
kind: 'modpack' | 'mod' | 'resourcepack'
|
||||
version_id: string
|
||||
project_id: string
|
||||
} | null
|
||||
motd?: string
|
||||
image?: string
|
||||
project?: Project
|
||||
sftp_username: string
|
||||
sftp_password: string
|
||||
sftp_host: string
|
||||
datacenter?: string
|
||||
notices?: ServerNotice[]
|
||||
node: {
|
||||
token: string
|
||||
instance: string
|
||||
}
|
||||
flows?: {
|
||||
intro?: boolean
|
||||
}
|
||||
server_id: string
|
||||
name: string
|
||||
net: {
|
||||
ip: string
|
||||
port: number
|
||||
domain: string
|
||||
}
|
||||
game: string
|
||||
backup_quota: number
|
||||
used_backup_quota: number
|
||||
status: string
|
||||
suspension_reason: 'moderated' | 'paymentfailed' | 'cancelled' | 'upgrading' | 'other' | string
|
||||
loader: string
|
||||
loader_version: string
|
||||
mc_version: string
|
||||
upstream: {
|
||||
kind: 'modpack' | 'mod' | 'resourcepack'
|
||||
version_id: string
|
||||
project_id: string
|
||||
} | null
|
||||
motd?: string
|
||||
image?: string
|
||||
project?: Project
|
||||
sftp_username: string
|
||||
sftp_password: string
|
||||
sftp_host: string
|
||||
datacenter?: string
|
||||
notices?: ServerNotice[]
|
||||
node: {
|
||||
token: string
|
||||
instance: string
|
||||
}
|
||||
flows?: {
|
||||
intro?: boolean
|
||||
}
|
||||
}
|
||||
|
||||
export interface Allocation {
|
||||
port: number
|
||||
name: string
|
||||
port: number
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface Startup {
|
||||
invocation: string
|
||||
original_invocation: string
|
||||
jdk_version: 'lts8' | 'lts11' | 'lts17' | 'lts21'
|
||||
jdk_build: 'corretto' | 'temurin' | 'graal'
|
||||
invocation: string
|
||||
original_invocation: string
|
||||
jdk_version: 'lts8' | 'lts11' | 'lts17' | 'lts21'
|
||||
jdk_build: 'corretto' | 'temurin' | 'graal'
|
||||
}
|
||||
|
||||
export type PowerAction = 'Start' | 'Stop' | 'Restart' | 'Kill'
|
||||
@@ -56,21 +56,21 @@ export type JDKVersion = 'lts8' | 'lts11' | 'lts17' | 'lts21'
|
||||
export type JDKBuild = 'corretto' | 'temurin' | 'graal'
|
||||
|
||||
export type Loaders =
|
||||
| 'Fabric'
|
||||
| 'Quilt'
|
||||
| 'Forge'
|
||||
| 'NeoForge'
|
||||
| 'Paper'
|
||||
| 'Spigot'
|
||||
| 'Bukkit'
|
||||
| 'Vanilla'
|
||||
| 'Purpur'
|
||||
| 'Fabric'
|
||||
| 'Quilt'
|
||||
| 'Forge'
|
||||
| 'NeoForge'
|
||||
| 'Paper'
|
||||
| 'Spigot'
|
||||
| 'Bukkit'
|
||||
| 'Vanilla'
|
||||
| 'Purpur'
|
||||
|
||||
export type ServerState =
|
||||
| 'starting'
|
||||
| 'running'
|
||||
| 'restarting'
|
||||
| 'stopping'
|
||||
| 'stopped'
|
||||
| 'crashed'
|
||||
| 'unknown'
|
||||
| 'starting'
|
||||
| 'running'
|
||||
| 'restarting'
|
||||
| 'stopping'
|
||||
| 'stopped'
|
||||
| 'crashed'
|
||||
| 'unknown'
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
export interface Stats {
|
||||
current: {
|
||||
cpu_percent: number
|
||||
ram_usage_bytes: number
|
||||
ram_total_bytes: number
|
||||
storage_usage_bytes: number
|
||||
storage_total_bytes: number
|
||||
}
|
||||
past: {
|
||||
cpu_percent: number
|
||||
ram_usage_bytes: number
|
||||
ram_total_bytes: number
|
||||
storage_usage_bytes: number
|
||||
storage_total_bytes: number
|
||||
}
|
||||
graph: {
|
||||
cpu: number[]
|
||||
ram: number[]
|
||||
}
|
||||
current: {
|
||||
cpu_percent: number
|
||||
ram_usage_bytes: number
|
||||
ram_total_bytes: number
|
||||
storage_usage_bytes: number
|
||||
storage_total_bytes: number
|
||||
}
|
||||
past: {
|
||||
cpu_percent: number
|
||||
ram_usage_bytes: number
|
||||
ram_total_bytes: number
|
||||
storage_usage_bytes: number
|
||||
storage_total_bytes: number
|
||||
}
|
||||
graph: {
|
||||
cpu: number[]
|
||||
ram: number[]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,124 +1,124 @@
|
||||
import type { Stats } from './stats'
|
||||
import type { ServerState } from './server'
|
||||
import type { Stats } from './stats'
|
||||
|
||||
export interface WSAuth {
|
||||
url: string
|
||||
token: string
|
||||
url: string
|
||||
token: string
|
||||
}
|
||||
|
||||
export interface WSLogEvent {
|
||||
event: 'log'
|
||||
message: string
|
||||
event: 'log'
|
||||
message: string
|
||||
}
|
||||
|
||||
type CurrentStats = Stats['current']
|
||||
|
||||
export interface WSStatsEvent extends CurrentStats {
|
||||
event: 'stats'
|
||||
event: 'stats'
|
||||
}
|
||||
|
||||
export interface WSAuthExpiringEvent {
|
||||
event: 'auth-expiring'
|
||||
event: 'auth-expiring'
|
||||
}
|
||||
|
||||
export interface WSPowerStateEvent {
|
||||
event: 'power-state'
|
||||
state: ServerState
|
||||
// if state "crashed"
|
||||
oom_killed?: boolean
|
||||
exit_code?: number
|
||||
event: 'power-state'
|
||||
state: ServerState
|
||||
// if state "crashed"
|
||||
oom_killed?: boolean
|
||||
exit_code?: number
|
||||
}
|
||||
|
||||
export interface WSAuthIncorrectEvent {
|
||||
event: 'auth-incorrect'
|
||||
event: 'auth-incorrect'
|
||||
}
|
||||
|
||||
export interface WSInstallationResultOkEvent {
|
||||
event: 'installation-result'
|
||||
result: 'ok'
|
||||
event: 'installation-result'
|
||||
result: 'ok'
|
||||
}
|
||||
|
||||
export interface WSInstallationResultErrEvent {
|
||||
event: 'installation-result'
|
||||
result: 'err'
|
||||
reason: string
|
||||
event: 'installation-result'
|
||||
result: 'err'
|
||||
reason: string
|
||||
}
|
||||
|
||||
export type WSInstallationResultEvent = WSInstallationResultOkEvent | WSInstallationResultErrEvent
|
||||
|
||||
export interface WSAuthOkEvent {
|
||||
event: 'auth-ok'
|
||||
event: 'auth-ok'
|
||||
}
|
||||
|
||||
export interface WSUptimeEvent {
|
||||
event: 'uptime'
|
||||
uptime: number // seconds
|
||||
event: 'uptime'
|
||||
uptime: number // seconds
|
||||
}
|
||||
|
||||
export interface WSNewModEvent {
|
||||
event: 'new-mod'
|
||||
event: 'new-mod'
|
||||
}
|
||||
|
||||
export type WSBackupTask = 'file' | 'create' | 'restore'
|
||||
export type WSBackupState = 'ongoing' | 'done' | 'failed' | 'cancelled' | 'unchanged'
|
||||
|
||||
export interface WSBackupProgressEvent {
|
||||
event: 'backup-progress'
|
||||
task: WSBackupTask
|
||||
id: string
|
||||
progress: number // percentage
|
||||
state: WSBackupState
|
||||
ready: boolean
|
||||
event: 'backup-progress'
|
||||
task: WSBackupTask
|
||||
id: string
|
||||
progress: number // percentage
|
||||
state: WSBackupState
|
||||
ready: boolean
|
||||
}
|
||||
|
||||
export type FSQueuedOpUnarchive = {
|
||||
op: 'unarchive'
|
||||
src: string
|
||||
op: 'unarchive'
|
||||
src: string
|
||||
}
|
||||
|
||||
export type FSQueuedOp = FSQueuedOpUnarchive
|
||||
|
||||
export type FSOpUnarchive = {
|
||||
op: 'unarchive'
|
||||
progress: number // Note: 1 does not mean it's done
|
||||
id: string // UUID
|
||||
op: 'unarchive'
|
||||
progress: number // Note: 1 does not mean it's done
|
||||
id: string // UUID
|
||||
|
||||
mime: string
|
||||
src: string
|
||||
state:
|
||||
| 'queued'
|
||||
| 'ongoing'
|
||||
| 'cancelled'
|
||||
| 'done'
|
||||
| 'failed-corrupted'
|
||||
| 'failed-invalid-path'
|
||||
| 'failed-cf-no-serverpack'
|
||||
| 'failed-cf-not-available'
|
||||
| 'failed-not-reachable'
|
||||
mime: string
|
||||
src: string
|
||||
state:
|
||||
| 'queued'
|
||||
| 'ongoing'
|
||||
| 'cancelled'
|
||||
| 'done'
|
||||
| 'failed-corrupted'
|
||||
| 'failed-invalid-path'
|
||||
| 'failed-cf-no-serverpack'
|
||||
| 'failed-cf-not-available'
|
||||
| 'failed-not-reachable'
|
||||
|
||||
current_file: string | null
|
||||
failed_path?: string
|
||||
bytes_processed: number
|
||||
files_processed: number
|
||||
started: string
|
||||
current_file: string | null
|
||||
failed_path?: string
|
||||
bytes_processed: number
|
||||
files_processed: number
|
||||
started: string
|
||||
}
|
||||
|
||||
export type FilesystemOp = FSOpUnarchive
|
||||
|
||||
export interface WSFilesystemOpsEvent {
|
||||
event: 'filesystem-ops'
|
||||
all: FilesystemOp[]
|
||||
event: 'filesystem-ops'
|
||||
all: FilesystemOp[]
|
||||
}
|
||||
|
||||
export type WSEvent =
|
||||
| WSLogEvent
|
||||
| WSStatsEvent
|
||||
| WSPowerStateEvent
|
||||
| WSAuthExpiringEvent
|
||||
| WSAuthIncorrectEvent
|
||||
| WSInstallationResultEvent
|
||||
| WSAuthOkEvent
|
||||
| WSUptimeEvent
|
||||
| WSNewModEvent
|
||||
| WSBackupProgressEvent
|
||||
| WSFilesystemOpsEvent
|
||||
| WSLogEvent
|
||||
| WSStatsEvent
|
||||
| WSPowerStateEvent
|
||||
| WSAuthExpiringEvent
|
||||
| WSAuthIncorrectEvent
|
||||
| WSInstallationResultEvent
|
||||
| WSAuthOkEvent
|
||||
| WSUptimeEvent
|
||||
| WSNewModEvent
|
||||
| WSBackupProgressEvent
|
||||
| WSFilesystemOpsEvent
|
||||
|
||||
@@ -3,175 +3,175 @@ import type { GLTF } from 'three/examples/jsm/loaders/GLTFLoader.js'
|
||||
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
|
||||
|
||||
export interface SkinRendererConfig {
|
||||
textureColorSpace?: THREE.ColorSpace
|
||||
textureFlipY?: boolean
|
||||
textureMagFilter?: THREE.MagnificationTextureFilter
|
||||
textureMinFilter?: THREE.MinificationTextureFilter
|
||||
textureColorSpace?: THREE.ColorSpace
|
||||
textureFlipY?: boolean
|
||||
textureMagFilter?: THREE.MagnificationTextureFilter
|
||||
textureMinFilter?: THREE.MinificationTextureFilter
|
||||
}
|
||||
|
||||
const modelCache: Map<string, GLTF> = new Map()
|
||||
const textureCache: Map<string, THREE.Texture> = new Map()
|
||||
|
||||
export async function loadModel(modelUrl: string): Promise<GLTF> {
|
||||
if (modelCache.has(modelUrl)) {
|
||||
return modelCache.get(modelUrl)!
|
||||
}
|
||||
if (modelCache.has(modelUrl)) {
|
||||
return modelCache.get(modelUrl)!
|
||||
}
|
||||
|
||||
const loader = new GLTFLoader()
|
||||
return new Promise<GLTF>((resolve, reject) => {
|
||||
loader.load(
|
||||
modelUrl,
|
||||
(gltf) => {
|
||||
modelCache.set(modelUrl, gltf)
|
||||
resolve(gltf)
|
||||
},
|
||||
undefined,
|
||||
reject,
|
||||
)
|
||||
})
|
||||
const loader = new GLTFLoader()
|
||||
return new Promise<GLTF>((resolve, reject) => {
|
||||
loader.load(
|
||||
modelUrl,
|
||||
(gltf) => {
|
||||
modelCache.set(modelUrl, gltf)
|
||||
resolve(gltf)
|
||||
},
|
||||
undefined,
|
||||
reject,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
export async function loadTexture(
|
||||
textureUrl: string,
|
||||
config: SkinRendererConfig = {},
|
||||
textureUrl: string,
|
||||
config: SkinRendererConfig = {},
|
||||
): Promise<THREE.Texture> {
|
||||
const cacheKey = `${textureUrl}_${JSON.stringify(config)}`
|
||||
const cacheKey = `${textureUrl}_${JSON.stringify(config)}`
|
||||
|
||||
if (textureCache.has(cacheKey)) {
|
||||
return textureCache.get(cacheKey)!
|
||||
}
|
||||
if (textureCache.has(cacheKey)) {
|
||||
return textureCache.get(cacheKey)!
|
||||
}
|
||||
|
||||
return new Promise<THREE.Texture>((resolve) => {
|
||||
const textureLoader = new THREE.TextureLoader()
|
||||
textureLoader.load(textureUrl, (texture) => {
|
||||
texture.colorSpace = config.textureColorSpace ?? THREE.SRGBColorSpace
|
||||
texture.flipY = config.textureFlipY ?? false
|
||||
texture.magFilter = config.textureMagFilter ?? THREE.NearestFilter
|
||||
texture.minFilter = config.textureMinFilter ?? THREE.NearestFilter
|
||||
return new Promise<THREE.Texture>((resolve) => {
|
||||
const textureLoader = new THREE.TextureLoader()
|
||||
textureLoader.load(textureUrl, (texture) => {
|
||||
texture.colorSpace = config.textureColorSpace ?? THREE.SRGBColorSpace
|
||||
texture.flipY = config.textureFlipY ?? false
|
||||
texture.magFilter = config.textureMagFilter ?? THREE.NearestFilter
|
||||
texture.minFilter = config.textureMinFilter ?? THREE.NearestFilter
|
||||
|
||||
textureCache.set(cacheKey, texture)
|
||||
resolve(texture)
|
||||
})
|
||||
})
|
||||
textureCache.set(cacheKey, texture)
|
||||
resolve(texture)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
export function applyTexture(model: THREE.Object3D, texture: THREE.Texture): void {
|
||||
model.traverse((child) => {
|
||||
if ((child as THREE.Mesh).isMesh) {
|
||||
const mesh = child as THREE.Mesh
|
||||
const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material]
|
||||
model.traverse((child) => {
|
||||
if ((child as THREE.Mesh).isMesh) {
|
||||
const mesh = child as THREE.Mesh
|
||||
const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material]
|
||||
|
||||
materials.forEach((mat: THREE.Material) => {
|
||||
if (mat instanceof THREE.MeshStandardMaterial) {
|
||||
if (mat.name !== 'cape') {
|
||||
mat.map = texture
|
||||
mat.metalness = 0
|
||||
mat.color.set(0xffffff)
|
||||
mat.toneMapped = false
|
||||
mat.flatShading = true
|
||||
mat.roughness = 1
|
||||
mat.needsUpdate = true
|
||||
mat.depthTest = true
|
||||
mat.side = THREE.DoubleSide
|
||||
mat.alphaTest = 0.1
|
||||
mat.depthWrite = true
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
materials.forEach((mat: THREE.Material) => {
|
||||
if (mat instanceof THREE.MeshStandardMaterial) {
|
||||
if (mat.name !== 'cape') {
|
||||
mat.map = texture
|
||||
mat.metalness = 0
|
||||
mat.color.set(0xffffff)
|
||||
mat.toneMapped = false
|
||||
mat.flatShading = true
|
||||
mat.roughness = 1
|
||||
mat.needsUpdate = true
|
||||
mat.depthTest = true
|
||||
mat.side = THREE.DoubleSide
|
||||
mat.alphaTest = 0.1
|
||||
mat.depthWrite = true
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function applyCapeTexture(
|
||||
model: THREE.Object3D,
|
||||
texture: THREE.Texture | null,
|
||||
transparentTexture?: THREE.Texture,
|
||||
model: THREE.Object3D,
|
||||
texture: THREE.Texture | null,
|
||||
transparentTexture?: THREE.Texture,
|
||||
): void {
|
||||
model.traverse((child) => {
|
||||
if ((child as THREE.Mesh).isMesh) {
|
||||
const mesh = child as THREE.Mesh
|
||||
const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material]
|
||||
model.traverse((child) => {
|
||||
if ((child as THREE.Mesh).isMesh) {
|
||||
const mesh = child as THREE.Mesh
|
||||
const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material]
|
||||
|
||||
materials.forEach((mat: THREE.Material) => {
|
||||
if (mat instanceof THREE.MeshStandardMaterial) {
|
||||
if (mat.name === 'cape') {
|
||||
mat.map = texture || transparentTexture || null
|
||||
mat.transparent = !texture || transparentTexture ? true : false
|
||||
mat.metalness = 0
|
||||
mat.color.set(0xffffff)
|
||||
mat.toneMapped = false
|
||||
mat.flatShading = true
|
||||
mat.roughness = 1
|
||||
mat.needsUpdate = true
|
||||
mat.depthTest = true
|
||||
mat.depthWrite = true
|
||||
mat.side = THREE.DoubleSide
|
||||
mat.alphaTest = 0.1
|
||||
mat.visible = !!texture
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
materials.forEach((mat: THREE.Material) => {
|
||||
if (mat instanceof THREE.MeshStandardMaterial) {
|
||||
if (mat.name === 'cape') {
|
||||
mat.map = texture || transparentTexture || null
|
||||
mat.transparent = !texture || transparentTexture ? true : false
|
||||
mat.metalness = 0
|
||||
mat.color.set(0xffffff)
|
||||
mat.toneMapped = false
|
||||
mat.flatShading = true
|
||||
mat.roughness = 1
|
||||
mat.needsUpdate = true
|
||||
mat.depthTest = true
|
||||
mat.depthWrite = true
|
||||
mat.side = THREE.DoubleSide
|
||||
mat.alphaTest = 0.1
|
||||
mat.visible = !!texture
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function findBodyNode(model: THREE.Object3D): THREE.Object3D | null {
|
||||
let bodyNode: THREE.Object3D | null = null
|
||||
let bodyNode: THREE.Object3D | null = null
|
||||
|
||||
model.traverse((node) => {
|
||||
if (node.name === 'Body') {
|
||||
bodyNode = node
|
||||
}
|
||||
})
|
||||
model.traverse((node) => {
|
||||
if (node.name === 'Body') {
|
||||
bodyNode = node
|
||||
}
|
||||
})
|
||||
|
||||
return bodyNode
|
||||
return bodyNode
|
||||
}
|
||||
|
||||
export function createTransparentTexture(): THREE.Texture {
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = canvas.height = 1
|
||||
const ctx = canvas.getContext('2d') as CanvasRenderingContext2D
|
||||
ctx.clearRect(0, 0, 1, 1)
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = canvas.height = 1
|
||||
const ctx = canvas.getContext('2d') as CanvasRenderingContext2D
|
||||
ctx.clearRect(0, 0, 1, 1)
|
||||
|
||||
const texture = new THREE.CanvasTexture(canvas)
|
||||
texture.needsUpdate = true
|
||||
texture.colorSpace = THREE.SRGBColorSpace
|
||||
texture.flipY = false
|
||||
texture.magFilter = THREE.NearestFilter
|
||||
texture.minFilter = THREE.NearestFilter
|
||||
const texture = new THREE.CanvasTexture(canvas)
|
||||
texture.needsUpdate = true
|
||||
texture.colorSpace = THREE.SRGBColorSpace
|
||||
texture.flipY = false
|
||||
texture.magFilter = THREE.NearestFilter
|
||||
texture.minFilter = THREE.NearestFilter
|
||||
|
||||
return texture
|
||||
return texture
|
||||
}
|
||||
|
||||
export async function setupSkinModel(
|
||||
modelUrl: string,
|
||||
textureUrl: string,
|
||||
capeTextureUrl?: string,
|
||||
config: SkinRendererConfig = {},
|
||||
modelUrl: string,
|
||||
textureUrl: string,
|
||||
capeTextureUrl?: string,
|
||||
config: SkinRendererConfig = {},
|
||||
): Promise<{
|
||||
model: THREE.Object3D
|
||||
bodyNode: THREE.Object3D | null
|
||||
model: THREE.Object3D
|
||||
bodyNode: THREE.Object3D | null
|
||||
}> {
|
||||
const [gltf, texture] = await Promise.all([loadModel(modelUrl), loadTexture(textureUrl, config)])
|
||||
const [gltf, texture] = await Promise.all([loadModel(modelUrl), loadTexture(textureUrl, config)])
|
||||
|
||||
const model = gltf.scene.clone()
|
||||
applyTexture(model, texture)
|
||||
const model = gltf.scene.clone()
|
||||
applyTexture(model, texture)
|
||||
|
||||
if (capeTextureUrl) {
|
||||
const capeTexture = await loadTexture(capeTextureUrl, config)
|
||||
applyCapeTexture(model, capeTexture)
|
||||
}
|
||||
if (capeTextureUrl) {
|
||||
const capeTexture = await loadTexture(capeTextureUrl, config)
|
||||
applyCapeTexture(model, capeTexture)
|
||||
}
|
||||
|
||||
const bodyNode = findBodyNode(model)
|
||||
const bodyNode = findBodyNode(model)
|
||||
|
||||
return { model, bodyNode }
|
||||
return { model, bodyNode }
|
||||
}
|
||||
|
||||
export function disposeCaches(): void {
|
||||
Array.from(textureCache.values()).forEach((texture) => {
|
||||
texture.dispose()
|
||||
})
|
||||
Array.from(textureCache.values()).forEach((texture) => {
|
||||
texture.dispose()
|
||||
})
|
||||
|
||||
textureCache.clear()
|
||||
modelCache.clear()
|
||||
textureCache.clear()
|
||||
modelCache.clear()
|
||||
}
|
||||
|
||||
@@ -1,9 +1,3 @@
|
||||
{
|
||||
"extends": "tsconfig/base.json",
|
||||
"include": [".", ".eslintrc.js"],
|
||||
"exclude": ["dist", "build", "node_modules"],
|
||||
"compilerOptions": {
|
||||
"lib": ["esnext", "dom"],
|
||||
"noImplicitAny": false
|
||||
}
|
||||
"extends": "@modrinth/tooling-config/typescript/vue.json"
|
||||
}
|
||||
|
||||
@@ -11,21 +11,21 @@ export type UnapprovedStatus = 'draft' | 'processing' | 'rejected' | 'withheld'
|
||||
export type ProjectStatus = ApprovedStatus | UnapprovedStatus | 'unknown'
|
||||
|
||||
export type DonationPlatform =
|
||||
| { short: 'patreon'; name: 'Patreon' }
|
||||
| { short: 'bmac'; name: 'Buy Me A Coffee' }
|
||||
| { short: 'paypal'; name: 'PayPal' }
|
||||
| { short: 'github'; name: 'GitHub Sponsors' }
|
||||
| { short: 'ko-fi'; name: 'Ko-fi' }
|
||||
| { short: 'other'; name: 'Other' }
|
||||
| { short: 'patreon'; name: 'Patreon' }
|
||||
| { short: 'bmac'; name: 'Buy Me A Coffee' }
|
||||
| { short: 'paypal'; name: 'PayPal' }
|
||||
| { short: 'github'; name: 'GitHub Sponsors' }
|
||||
| { short: 'ko-fi'; name: 'Ko-fi' }
|
||||
| { short: 'other'; name: 'Other' }
|
||||
|
||||
export type ProjectType =
|
||||
| 'mod'
|
||||
| 'modpack'
|
||||
| 'resourcepack'
|
||||
| 'shader'
|
||||
| 'plugin'
|
||||
| 'datapack'
|
||||
| 'project'
|
||||
| 'mod'
|
||||
| 'modpack'
|
||||
| 'resourcepack'
|
||||
| 'shader'
|
||||
| 'plugin'
|
||||
| 'datapack'
|
||||
| 'project'
|
||||
export type MonetizationStatus = 'monetized' | 'demonetized' | 'force-demonetized'
|
||||
|
||||
export type GameVersion = string
|
||||
@@ -34,213 +34,213 @@ export type Category = string
|
||||
export type CategoryOrPlatform = Category | Platform
|
||||
|
||||
export interface DonationLink<T extends DonationPlatform> {
|
||||
id: T['short']
|
||||
platform: T['name']
|
||||
url: string
|
||||
id: T['short']
|
||||
platform: T['name']
|
||||
url: string
|
||||
}
|
||||
|
||||
export interface GalleryImage {
|
||||
url: string
|
||||
featured: boolean
|
||||
created: string
|
||||
ordering: number
|
||||
url: string
|
||||
featured: boolean
|
||||
created: string
|
||||
ordering: number
|
||||
|
||||
title?: string
|
||||
description?: string
|
||||
title?: string
|
||||
description?: string
|
||||
}
|
||||
|
||||
export interface ProjectV3 {
|
||||
id: ModrinthId
|
||||
slug?: string
|
||||
project_types: string[]
|
||||
games: string[]
|
||||
team_id: ModrinthId
|
||||
organization?: ModrinthId
|
||||
name: string
|
||||
summary: string
|
||||
description: string
|
||||
id: ModrinthId
|
||||
slug?: string
|
||||
project_types: string[]
|
||||
games: string[]
|
||||
team_id: ModrinthId
|
||||
organization?: ModrinthId
|
||||
name: string
|
||||
summary: string
|
||||
description: string
|
||||
|
||||
published: string
|
||||
updated: string
|
||||
approved?: string
|
||||
queued?: string
|
||||
published: string
|
||||
updated: string
|
||||
approved?: string
|
||||
queued?: string
|
||||
|
||||
status: ProjectStatus
|
||||
requested_status?: ProjectStatus
|
||||
status: ProjectStatus
|
||||
requested_status?: ProjectStatus
|
||||
|
||||
/** @deprecated moved to threads system */
|
||||
moderator_message?: {
|
||||
message: string
|
||||
body?: string
|
||||
}
|
||||
/** @deprecated moved to threads system */
|
||||
moderator_message?: {
|
||||
message: string
|
||||
body?: string
|
||||
}
|
||||
|
||||
license: {
|
||||
id: string
|
||||
name: string
|
||||
url?: string
|
||||
}
|
||||
license: {
|
||||
id: string
|
||||
name: string
|
||||
url?: string
|
||||
}
|
||||
|
||||
downloads: number
|
||||
followers: number
|
||||
downloads: number
|
||||
followers: number
|
||||
|
||||
categories: string[]
|
||||
additional_categories: string[]
|
||||
loaders: string[]
|
||||
categories: string[]
|
||||
additional_categories: string[]
|
||||
loaders: string[]
|
||||
|
||||
versions: ModrinthId[]
|
||||
icon_url?: string
|
||||
versions: ModrinthId[]
|
||||
icon_url?: string
|
||||
|
||||
link_urls: Record<
|
||||
string,
|
||||
{
|
||||
platform: string
|
||||
donation: boolean
|
||||
url: string
|
||||
}
|
||||
>
|
||||
link_urls: Record<
|
||||
string,
|
||||
{
|
||||
platform: string
|
||||
donation: boolean
|
||||
url: string
|
||||
}
|
||||
>
|
||||
|
||||
gallery: {
|
||||
url: string
|
||||
raw_url: string
|
||||
featured: boolean
|
||||
name?: string
|
||||
description?: string
|
||||
created: string
|
||||
ordering: number
|
||||
}[]
|
||||
gallery: {
|
||||
url: string
|
||||
raw_url: string
|
||||
featured: boolean
|
||||
name?: string
|
||||
description?: string
|
||||
created: string
|
||||
ordering: number
|
||||
}[]
|
||||
|
||||
color?: number
|
||||
thread_id: ModrinthId
|
||||
monetization_status: MonetizationStatus
|
||||
side_types_migration_review_status: 'reviewed' | 'pending'
|
||||
color?: number
|
||||
thread_id: ModrinthId
|
||||
monetization_status: MonetizationStatus
|
||||
side_types_migration_review_status: 'reviewed' | 'pending'
|
||||
|
||||
[key: string]: unknown
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export type SideTypesMigrationReviewStatus = 'reviewed' | 'pending'
|
||||
|
||||
export interface Project {
|
||||
id: ModrinthId
|
||||
project_type: ProjectType
|
||||
slug: string
|
||||
title: string
|
||||
description: string
|
||||
status: ProjectStatus
|
||||
requested_status: RequestableStatus
|
||||
monetization_status: MonetizationStatus
|
||||
id: ModrinthId
|
||||
project_type: ProjectType
|
||||
slug: string
|
||||
title: string
|
||||
description: string
|
||||
status: ProjectStatus
|
||||
requested_status: RequestableStatus
|
||||
monetization_status: MonetizationStatus
|
||||
|
||||
body: string
|
||||
icon_url?: string
|
||||
color?: number
|
||||
body: string
|
||||
icon_url?: string
|
||||
color?: number
|
||||
|
||||
categories: Category[]
|
||||
additional_categories: Category[]
|
||||
categories: Category[]
|
||||
additional_categories: Category[]
|
||||
|
||||
downloads: number
|
||||
followers: number
|
||||
downloads: number
|
||||
followers: number
|
||||
|
||||
client_side: Environment
|
||||
server_side: Environment
|
||||
client_side: Environment
|
||||
server_side: Environment
|
||||
|
||||
team?: ModrinthId
|
||||
team_id: ModrinthId
|
||||
thread_id: ModrinthId
|
||||
organization: ModrinthId
|
||||
team?: ModrinthId
|
||||
team_id: ModrinthId
|
||||
thread_id: ModrinthId
|
||||
organization: ModrinthId
|
||||
|
||||
issues_url: string | null
|
||||
source_url: string | null
|
||||
wiki_url: string | null
|
||||
discord_url: string | null
|
||||
donation_urls: DonationLink<DonationPlatform>[]
|
||||
issues_url: string | null
|
||||
source_url: string | null
|
||||
wiki_url: string | null
|
||||
discord_url: string | null
|
||||
donation_urls: DonationLink<DonationPlatform>[]
|
||||
|
||||
published: string
|
||||
created?: string
|
||||
updated: string
|
||||
approved: string
|
||||
queued: string
|
||||
published: string
|
||||
created?: string
|
||||
updated: string
|
||||
approved: string
|
||||
queued: string
|
||||
|
||||
game_versions: GameVersion[]
|
||||
loaders: Platform[]
|
||||
game_versions: GameVersion[]
|
||||
loaders: Platform[]
|
||||
|
||||
versions: ModrinthId[]
|
||||
gallery?: GalleryImage[]
|
||||
versions: ModrinthId[]
|
||||
gallery?: GalleryImage[]
|
||||
|
||||
license: {
|
||||
id: string
|
||||
name: string
|
||||
url?: string
|
||||
}
|
||||
license: {
|
||||
id: string
|
||||
name: string
|
||||
url?: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface SearchResult {
|
||||
id: ModrinthId
|
||||
project_type: ProjectType
|
||||
slug: string
|
||||
title: string
|
||||
description: string
|
||||
monetization_status: MonetizationStatus
|
||||
id: ModrinthId
|
||||
project_type: ProjectType
|
||||
slug: string
|
||||
title: string
|
||||
description: string
|
||||
monetization_status: MonetizationStatus
|
||||
|
||||
icon_url?: string
|
||||
color?: number
|
||||
icon_url?: string
|
||||
color?: number
|
||||
|
||||
categories: CategoryOrPlatform[]
|
||||
display_categories: CategoryOrPlatform[]
|
||||
versions: GameVersion[]
|
||||
latest_version: GameVersion
|
||||
categories: CategoryOrPlatform[]
|
||||
display_categories: CategoryOrPlatform[]
|
||||
versions: GameVersion[]
|
||||
latest_version: GameVersion
|
||||
|
||||
downloads: number
|
||||
follows: number
|
||||
downloads: number
|
||||
follows: number
|
||||
|
||||
client_side: Environment
|
||||
server_side: Environment
|
||||
client_side: Environment
|
||||
server_side: Environment
|
||||
|
||||
author: string
|
||||
author: string
|
||||
|
||||
date_created: string
|
||||
date_modified: string
|
||||
date_created: string
|
||||
date_modified: string
|
||||
|
||||
gallery: string[]
|
||||
featured_gallery?: string[]
|
||||
gallery: string[]
|
||||
featured_gallery?: string[]
|
||||
|
||||
license: string
|
||||
license: string
|
||||
}
|
||||
|
||||
export type Organization = {
|
||||
id: ModrinthId
|
||||
slug: string
|
||||
name: string
|
||||
team_id: ModrinthId
|
||||
description: string
|
||||
icon_url: string
|
||||
color: number
|
||||
members: OrganizationMember[]
|
||||
id: ModrinthId
|
||||
slug: string
|
||||
name: string
|
||||
team_id: ModrinthId
|
||||
description: string
|
||||
icon_url: string
|
||||
color: number
|
||||
members: OrganizationMember[]
|
||||
}
|
||||
|
||||
export type OrganizationPermissions = number
|
||||
|
||||
export type OrganizationMember = {
|
||||
team_id: ModrinthId
|
||||
user: User
|
||||
role: string
|
||||
is_owner: boolean
|
||||
permissions: TeamMemberPermissions
|
||||
organization_permissions: OrganizationPermissions
|
||||
accepted: boolean
|
||||
payouts_split: number
|
||||
ordering: number
|
||||
team_id: ModrinthId
|
||||
user: User
|
||||
role: string
|
||||
is_owner: boolean
|
||||
permissions: TeamMemberPermissions
|
||||
organization_permissions: OrganizationPermissions
|
||||
accepted: boolean
|
||||
payouts_split: number
|
||||
ordering: number
|
||||
}
|
||||
|
||||
export type Collection = {
|
||||
id: ModrinthId
|
||||
user: User
|
||||
name: string
|
||||
description: string
|
||||
icon_url: string
|
||||
color: number
|
||||
status: CollectionStatus
|
||||
created: string
|
||||
updated: string
|
||||
projects: ModrinthId[]
|
||||
id: ModrinthId
|
||||
user: User
|
||||
name: string
|
||||
description: string
|
||||
icon_url: string
|
||||
color: number
|
||||
status: CollectionStatus
|
||||
created: string
|
||||
updated: string
|
||||
projects: ModrinthId[]
|
||||
}
|
||||
|
||||
export type CollectionStatus = 'listed' | 'unlisted' | 'private' | 'unknown'
|
||||
@@ -248,18 +248,18 @@ export type CollectionStatus = 'listed' | 'unlisted' | 'private' | 'unknown'
|
||||
export type DependencyType = 'required' | 'optional' | 'incompatible' | 'embedded'
|
||||
|
||||
export interface VersionDependency {
|
||||
dependency_type: DependencyType
|
||||
file_name?: string
|
||||
dependency_type: DependencyType
|
||||
file_name?: string
|
||||
}
|
||||
|
||||
export interface ProjectDependency {
|
||||
dependency_type: DependencyType
|
||||
project_id?: string
|
||||
dependency_type: DependencyType
|
||||
project_id?: string
|
||||
}
|
||||
|
||||
export interface FileDependency {
|
||||
dependency_type: DependencyType
|
||||
file_name?: string
|
||||
dependency_type: DependencyType
|
||||
file_name?: string
|
||||
}
|
||||
|
||||
export type Dependency = VersionDependency | ProjectDependency | FileDependency
|
||||
@@ -268,282 +268,282 @@ export type VersionStatus = 'listed' | 'archived' | 'draft' | 'unlisted' | 'sche
|
||||
export type FileType = 'required-resource-pack' | 'optional-resource-pack'
|
||||
|
||||
export interface VersionFileHash {
|
||||
sha512: string
|
||||
sha1: string
|
||||
sha512: string
|
||||
sha1: string
|
||||
}
|
||||
|
||||
export interface VersionFile {
|
||||
hashes: VersionFileHash[]
|
||||
url: string
|
||||
filename: string
|
||||
primary: boolean
|
||||
size: number
|
||||
file_type?: FileType
|
||||
hashes: VersionFileHash[]
|
||||
url: string
|
||||
filename: string
|
||||
primary: boolean
|
||||
size: number
|
||||
file_type?: FileType
|
||||
}
|
||||
|
||||
export interface Version {
|
||||
name: string
|
||||
version_number: string
|
||||
changelog?: string
|
||||
dependencies: Dependency[]
|
||||
game_versions: GameVersion[]
|
||||
version_type: VersionChannel
|
||||
loaders: Platform[]
|
||||
featured: boolean
|
||||
status: VersionStatus
|
||||
id: ModrinthId
|
||||
project_id: ModrinthId
|
||||
author_id: ModrinthId
|
||||
date_published: string
|
||||
downloads: number
|
||||
files: VersionFile[]
|
||||
name: string
|
||||
version_number: string
|
||||
changelog?: string
|
||||
dependencies: Dependency[]
|
||||
game_versions: GameVersion[]
|
||||
version_type: VersionChannel
|
||||
loaders: Platform[]
|
||||
featured: boolean
|
||||
status: VersionStatus
|
||||
id: ModrinthId
|
||||
project_id: ModrinthId
|
||||
author_id: ModrinthId
|
||||
date_published: string
|
||||
downloads: number
|
||||
files: VersionFile[]
|
||||
}
|
||||
|
||||
export interface PayoutData {
|
||||
balance: number
|
||||
payout_wallet: 'paypal' | 'venmo'
|
||||
payout_wallet_type: 'email' | 'phone' | 'user_handle'
|
||||
payout_address: string
|
||||
balance: number
|
||||
payout_wallet: 'paypal' | 'venmo'
|
||||
payout_wallet_type: 'email' | 'phone' | 'user_handle'
|
||||
payout_address: string
|
||||
}
|
||||
|
||||
export type UserRole = 'admin' | 'moderator' | 'pyro' | 'developer'
|
||||
|
||||
export enum UserBadge {
|
||||
MIDAS = 1 << 0,
|
||||
EARLY_MODPACK_ADOPTER = 1 << 1,
|
||||
EARLY_RESPACK_ADOPTER = 1 << 2,
|
||||
EARLY_PLUGIN_ADOPTER = 1 << 3,
|
||||
ALPHA_TESTER = 1 << 4,
|
||||
CONTRIBUTOR = 1 << 5,
|
||||
TRANSLATOR = 1 << 6,
|
||||
MIDAS = 1 << 0,
|
||||
EARLY_MODPACK_ADOPTER = 1 << 1,
|
||||
EARLY_RESPACK_ADOPTER = 1 << 2,
|
||||
EARLY_PLUGIN_ADOPTER = 1 << 3,
|
||||
ALPHA_TESTER = 1 << 4,
|
||||
CONTRIBUTOR = 1 << 5,
|
||||
TRANSLATOR = 1 << 6,
|
||||
}
|
||||
|
||||
export type UserBadges = number
|
||||
|
||||
export interface User {
|
||||
username: string
|
||||
email?: string
|
||||
bio?: string
|
||||
payout_data?: PayoutData
|
||||
id: ModrinthId
|
||||
avatar_url: string
|
||||
created: string
|
||||
role: UserRole
|
||||
badges: UserBadges
|
||||
auth_providers?: string[]
|
||||
email_verified?: boolean
|
||||
has_password?: boolean
|
||||
has_totp?: boolean
|
||||
username: string
|
||||
email?: string
|
||||
bio?: string
|
||||
payout_data?: PayoutData
|
||||
id: ModrinthId
|
||||
avatar_url: string
|
||||
created: string
|
||||
role: UserRole
|
||||
badges: UserBadges
|
||||
auth_providers?: string[]
|
||||
email_verified?: boolean
|
||||
has_password?: boolean
|
||||
has_totp?: boolean
|
||||
}
|
||||
|
||||
export enum TeamMemberPermission {
|
||||
UPLOAD_VERSION = 1 << 0,
|
||||
DELETE_VERSION = 1 << 1,
|
||||
EDIT_DETAILS = 1 << 2,
|
||||
EDIT_BODY = 1 << 3,
|
||||
MANAGE_INVITES = 1 << 4,
|
||||
REMOVE_MEMBER = 1 << 5,
|
||||
EDIT_MEMBER = 1 << 6,
|
||||
DELETE_PROJECT = 1 << 7,
|
||||
VIEW_ANALYTICS = 1 << 8,
|
||||
VIEW_PAYOUTS = 1 << 9,
|
||||
UPLOAD_VERSION = 1 << 0,
|
||||
DELETE_VERSION = 1 << 1,
|
||||
EDIT_DETAILS = 1 << 2,
|
||||
EDIT_BODY = 1 << 3,
|
||||
MANAGE_INVITES = 1 << 4,
|
||||
REMOVE_MEMBER = 1 << 5,
|
||||
EDIT_MEMBER = 1 << 6,
|
||||
DELETE_PROJECT = 1 << 7,
|
||||
VIEW_ANALYTICS = 1 << 8,
|
||||
VIEW_PAYOUTS = 1 << 9,
|
||||
}
|
||||
|
||||
export type TeamMemberPermissions = number
|
||||
|
||||
export interface TeamMember {
|
||||
team_id: ModrinthId
|
||||
user: User
|
||||
role: string
|
||||
permissions: TeamMemberPermissions
|
||||
accepted: boolean
|
||||
payouts_split: number
|
||||
ordering: number
|
||||
is_owner: boolean
|
||||
team_id: ModrinthId
|
||||
user: User
|
||||
role: string
|
||||
permissions: TeamMemberPermissions
|
||||
accepted: boolean
|
||||
payouts_split: number
|
||||
ordering: number
|
||||
is_owner: boolean
|
||||
}
|
||||
|
||||
export type Report = {
|
||||
id: ModrinthId
|
||||
item_id: ModrinthId
|
||||
item_type: 'project' | 'version' | 'user'
|
||||
report_type: string
|
||||
reporter: ModrinthId
|
||||
thread_id: ModrinthId
|
||||
closed: boolean
|
||||
created: string
|
||||
body: string
|
||||
id: ModrinthId
|
||||
item_id: ModrinthId
|
||||
item_type: 'project' | 'version' | 'user'
|
||||
report_type: string
|
||||
reporter: ModrinthId
|
||||
thread_id: ModrinthId
|
||||
closed: boolean
|
||||
created: string
|
||||
body: string
|
||||
}
|
||||
|
||||
// Threads
|
||||
export interface Thread {
|
||||
id: string
|
||||
type: ThreadType
|
||||
project_id: string | null
|
||||
report_id: string | null
|
||||
messages: ThreadMessage[]
|
||||
members: User[]
|
||||
id: string
|
||||
type: ThreadType
|
||||
project_id: string | null
|
||||
report_id: string | null
|
||||
messages: ThreadMessage[]
|
||||
members: User[]
|
||||
}
|
||||
|
||||
export type ThreadType = 'project' | 'report' | 'direct_message'
|
||||
|
||||
export interface ThreadMessage {
|
||||
id: string | null
|
||||
author_id: string | null
|
||||
body: MessageBody
|
||||
created: string
|
||||
hide_identity: boolean
|
||||
id: string | null
|
||||
author_id: string | null
|
||||
body: MessageBody
|
||||
created: string
|
||||
hide_identity: boolean
|
||||
}
|
||||
|
||||
export type MessageBody =
|
||||
| TextMessageBody
|
||||
| StatusChangeMessageBody
|
||||
| ThreadClosureMessageBody
|
||||
| ThreadReopenMessageBody
|
||||
| DeletedMessageBody
|
||||
| TextMessageBody
|
||||
| StatusChangeMessageBody
|
||||
| ThreadClosureMessageBody
|
||||
| ThreadReopenMessageBody
|
||||
| DeletedMessageBody
|
||||
|
||||
export interface TextMessageBody {
|
||||
type: 'text'
|
||||
body: string
|
||||
private: boolean
|
||||
replying_to: string | null
|
||||
associated_images: string[]
|
||||
type: 'text'
|
||||
body: string
|
||||
private: boolean
|
||||
replying_to: string | null
|
||||
associated_images: string[]
|
||||
}
|
||||
|
||||
export interface StatusChangeMessageBody {
|
||||
type: 'status_change'
|
||||
new_status: ProjectStatus
|
||||
old_status: ProjectStatus
|
||||
type: 'status_change'
|
||||
new_status: ProjectStatus
|
||||
old_status: ProjectStatus
|
||||
}
|
||||
|
||||
export interface ThreadClosureMessageBody {
|
||||
type: 'thread_closure'
|
||||
type: 'thread_closure'
|
||||
}
|
||||
|
||||
export interface ThreadReopenMessageBody {
|
||||
type: 'thread_reopen'
|
||||
type: 'thread_reopen'
|
||||
}
|
||||
|
||||
export interface DeletedMessageBody {
|
||||
type: 'deleted'
|
||||
private: boolean
|
||||
type: 'deleted'
|
||||
private: boolean
|
||||
}
|
||||
|
||||
// Moderation
|
||||
export interface ModerationModpackPermissionApprovalType {
|
||||
id:
|
||||
| 'yes'
|
||||
| 'no'
|
||||
| 'with-attribution'
|
||||
| 'unidentified'
|
||||
| 'with-attribution-and-source'
|
||||
| 'permanent-no'
|
||||
name: string
|
||||
id:
|
||||
| 'yes'
|
||||
| 'no'
|
||||
| 'with-attribution'
|
||||
| 'unidentified'
|
||||
| 'with-attribution-and-source'
|
||||
| 'permanent-no'
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface ModerationPermissionType {
|
||||
id: 'yes' | 'no'
|
||||
name: string
|
||||
id: 'yes' | 'no'
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface ModerationBaseModpackItem {
|
||||
sha1: string
|
||||
file_name: string
|
||||
type: 'unknown' | 'flame' | 'identified'
|
||||
status: ModerationModpackPermissionApprovalType['id'] | null
|
||||
approved: ModerationPermissionType['id'] | null
|
||||
sha1: string
|
||||
file_name: string
|
||||
type: 'unknown' | 'flame' | 'identified'
|
||||
status: ModerationModpackPermissionApprovalType['id'] | null
|
||||
approved: ModerationPermissionType['id'] | null
|
||||
}
|
||||
|
||||
export interface ModerationUnknownModpackItem extends ModerationBaseModpackItem {
|
||||
type: 'unknown'
|
||||
proof: string
|
||||
url: string
|
||||
title: string
|
||||
type: 'unknown'
|
||||
proof: string
|
||||
url: string
|
||||
title: string
|
||||
}
|
||||
|
||||
export interface ModerationFlameModpackItem extends ModerationBaseModpackItem {
|
||||
type: 'flame'
|
||||
id: string
|
||||
title: string
|
||||
url: string
|
||||
type: 'flame'
|
||||
id: string
|
||||
title: string
|
||||
url: string
|
||||
}
|
||||
|
||||
export interface ModerationIdentifiedModpackItem extends ModerationBaseModpackItem {
|
||||
type: 'identified'
|
||||
proof?: string
|
||||
url?: string
|
||||
title?: string
|
||||
type: 'identified'
|
||||
proof?: string
|
||||
url?: string
|
||||
title?: string
|
||||
}
|
||||
|
||||
export type ModerationModpackItem =
|
||||
| ModerationUnknownModpackItem
|
||||
| ModerationFlameModpackItem
|
||||
| ModerationIdentifiedModpackItem
|
||||
| ModerationUnknownModpackItem
|
||||
| ModerationFlameModpackItem
|
||||
| ModerationIdentifiedModpackItem
|
||||
|
||||
export interface ModerationModpackResponse {
|
||||
identified?: Record<
|
||||
string,
|
||||
{
|
||||
file_name: string
|
||||
status: ModerationModpackPermissionApprovalType['id']
|
||||
}
|
||||
>
|
||||
unknown_files?: Record<string, string>
|
||||
flame_files?: Record<
|
||||
string,
|
||||
{
|
||||
file_name: string
|
||||
id: string
|
||||
title?: string
|
||||
url?: string
|
||||
}
|
||||
>
|
||||
identified?: Record<
|
||||
string,
|
||||
{
|
||||
file_name: string
|
||||
status: ModerationModpackPermissionApprovalType['id']
|
||||
}
|
||||
>
|
||||
unknown_files?: Record<string, string>
|
||||
flame_files?: Record<
|
||||
string,
|
||||
{
|
||||
file_name: string
|
||||
id: string
|
||||
title?: string
|
||||
url?: string
|
||||
}
|
||||
>
|
||||
}
|
||||
|
||||
export interface ModerationJudgement {
|
||||
type: 'flame' | 'unknown' | 'identified'
|
||||
status: string | null
|
||||
id?: string
|
||||
link?: string
|
||||
title?: string
|
||||
proof?: string
|
||||
file_name?: string
|
||||
type: 'flame' | 'unknown' | 'identified'
|
||||
status: string | null
|
||||
id?: string
|
||||
link?: string
|
||||
title?: string
|
||||
proof?: string
|
||||
file_name?: string
|
||||
}
|
||||
|
||||
export interface ModerationJudgements {
|
||||
[sha1: string]: ModerationJudgement
|
||||
[sha1: string]: ModerationJudgement
|
||||
}
|
||||
|
||||
// Delphi
|
||||
export interface DelphiReport {
|
||||
id: string
|
||||
project: Project
|
||||
version: Version
|
||||
priority_score: number
|
||||
detected_at: string
|
||||
trace_type:
|
||||
| 'reflection_indirection'
|
||||
| 'xor_obfuscation'
|
||||
| 'included_libraries'
|
||||
| 'suspicious_binaries'
|
||||
| 'corrupt_classes'
|
||||
| 'suspicious_classes'
|
||||
| 'url_usage'
|
||||
| 'classloader_usage'
|
||||
| 'processbuilder_usage'
|
||||
| 'runtime_exec_usage'
|
||||
| 'jni_usage'
|
||||
| 'main_method'
|
||||
| 'native_loading'
|
||||
| 'malformed_jar'
|
||||
| 'nested_jar_too_deep'
|
||||
| 'failed_decompilation'
|
||||
| 'analysis_failure'
|
||||
| 'malware_easyforme'
|
||||
| 'malware_simplyloader'
|
||||
file_path: string
|
||||
// pending = not reviewed yet.
|
||||
// approved = approved as malicious, removed from modrinth
|
||||
// rejected = not approved as malicious, remains on modrinth?
|
||||
status: 'pending' | 'approved' | 'rejected'
|
||||
content?: string
|
||||
id: string
|
||||
project: Project
|
||||
version: Version
|
||||
priority_score: number
|
||||
detected_at: string
|
||||
trace_type:
|
||||
| 'reflection_indirection'
|
||||
| 'xor_obfuscation'
|
||||
| 'included_libraries'
|
||||
| 'suspicious_binaries'
|
||||
| 'corrupt_classes'
|
||||
| 'suspicious_classes'
|
||||
| 'url_usage'
|
||||
| 'classloader_usage'
|
||||
| 'processbuilder_usage'
|
||||
| 'runtime_exec_usage'
|
||||
| 'jni_usage'
|
||||
| 'main_method'
|
||||
| 'native_loading'
|
||||
| 'malformed_jar'
|
||||
| 'nested_jar_too_deep'
|
||||
| 'failed_decompilation'
|
||||
| 'analysis_failure'
|
||||
| 'malware_easyforme'
|
||||
| 'malware_simplyloader'
|
||||
file_path: string
|
||||
// pending = not reviewed yet.
|
||||
// approved = approved as malicious, removed from modrinth
|
||||
// rejected = not approved as malicious, remains on modrinth?
|
||||
status: 'pending' | 'approved' | 'rejected'
|
||||
content?: string
|
||||
}
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
|
||||
export const getUserLink = (user) => {
|
||||
return `/user/${user.username}`
|
||||
return `/user/${user.username}`
|
||||
}
|
||||
|
||||
export const isStaff = (user) => {
|
||||
return user && STAFF_ROLES.includes(user.role)
|
||||
return user && STAFF_ROLES.includes(user.role)
|
||||
}
|
||||
|
||||
export const isAdmin = (user) => {
|
||||
return user && user.role === 'admin'
|
||||
return user && user.role === 'admin'
|
||||
}
|
||||
|
||||
export const STAFF_ROLES = ['moderator', 'admin']
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
|
||||
// @ts-nocheck
|
||||
|
||||
import dayjs from 'dayjs'
|
||||
@@ -9,367 +9,367 @@ export const external = (cosmetics) => (cosmetics.externalLinksNewTab ? '_blank'
|
||||
// Only use on the complete list of versions for a project,
|
||||
// partial lists will generate the wrong version slugs
|
||||
export const computeVersions = (versions, members) => {
|
||||
const visitedVersions = []
|
||||
const returnVersions = []
|
||||
const authorMembers = {}
|
||||
const visitedVersions = []
|
||||
const returnVersions = []
|
||||
const authorMembers = {}
|
||||
|
||||
for (const version of versions.sort(
|
||||
(a, b) => dayjs(a.date_published) - dayjs(b.date_published),
|
||||
)) {
|
||||
if (visitedVersions.includes(version.version_number)) {
|
||||
visitedVersions.push(version.version_number)
|
||||
version.displayUrlEnding = version.id
|
||||
} else {
|
||||
visitedVersions.push(version.version_number)
|
||||
version.displayUrlEnding = version.version_number
|
||||
}
|
||||
version.primaryFile = version.files.find((file) => file.primary) ?? version.files[0]
|
||||
for (const version of versions.sort(
|
||||
(a, b) => dayjs(a.date_published) - dayjs(b.date_published),
|
||||
)) {
|
||||
if (visitedVersions.includes(version.version_number)) {
|
||||
visitedVersions.push(version.version_number)
|
||||
version.displayUrlEnding = version.id
|
||||
} else {
|
||||
visitedVersions.push(version.version_number)
|
||||
version.displayUrlEnding = version.version_number
|
||||
}
|
||||
version.primaryFile = version.files.find((file) => file.primary) ?? version.files[0]
|
||||
|
||||
if (!version.primaryFile) {
|
||||
version.primaryFile = {
|
||||
hashes: {
|
||||
sha1: '',
|
||||
sha512: '',
|
||||
},
|
||||
url: '#',
|
||||
filename: 'unknown',
|
||||
primary: false,
|
||||
size: 0,
|
||||
file_type: null,
|
||||
}
|
||||
}
|
||||
if (!version.primaryFile) {
|
||||
version.primaryFile = {
|
||||
hashes: {
|
||||
sha1: '',
|
||||
sha512: '',
|
||||
},
|
||||
url: '#',
|
||||
filename: 'unknown',
|
||||
primary: false,
|
||||
size: 0,
|
||||
file_type: null,
|
||||
}
|
||||
}
|
||||
|
||||
version.author = authorMembers[version.author_id]
|
||||
if (!version.author) {
|
||||
version.author = members.find((x) => x.user.id === version.author_id)
|
||||
authorMembers[version.author_id] = version.author
|
||||
}
|
||||
version.author = authorMembers[version.author_id]
|
||||
if (!version.author) {
|
||||
version.author = members.find((x) => x.user.id === version.author_id)
|
||||
authorMembers[version.author_id] = version.author
|
||||
}
|
||||
|
||||
returnVersions.push(version)
|
||||
}
|
||||
returnVersions.push(version)
|
||||
}
|
||||
|
||||
return returnVersions
|
||||
.reverse()
|
||||
.map((version, index) => {
|
||||
const nextVersion = returnVersions[index + 1]
|
||||
if (nextVersion && version.changelog && nextVersion.changelog === version.changelog) {
|
||||
return { duplicate: true, ...version }
|
||||
}
|
||||
return { duplicate: false, ...version }
|
||||
})
|
||||
.sort((a, b) => dayjs(b.date_published) - dayjs(a.date_published))
|
||||
return returnVersions
|
||||
.reverse()
|
||||
.map((version, index) => {
|
||||
const nextVersion = returnVersions[index + 1]
|
||||
if (nextVersion && version.changelog && nextVersion.changelog === version.changelog) {
|
||||
return { duplicate: true, ...version }
|
||||
}
|
||||
return { duplicate: false, ...version }
|
||||
})
|
||||
.sort((a, b) => dayjs(b.date_published) - dayjs(a.date_published))
|
||||
}
|
||||
|
||||
export const sortedCategories = (tags) => {
|
||||
return tags.categories.slice().sort((a, b) => {
|
||||
const headerCompare = a.header.localeCompare(b.header)
|
||||
if (headerCompare !== 0) {
|
||||
return headerCompare
|
||||
}
|
||||
if (a.header === 'resolutions' && b.header === 'resolutions') {
|
||||
return a.name.replace(/\D/g, '') - b.name.replace(/\D/g, '')
|
||||
} else if (a.header === 'performance impact' && b.header === 'performance impact') {
|
||||
const x = ['potato', 'low', 'medium', 'high', 'screenshot']
|
||||
return tags.categories.slice().sort((a, b) => {
|
||||
const headerCompare = a.header.localeCompare(b.header)
|
||||
if (headerCompare !== 0) {
|
||||
return headerCompare
|
||||
}
|
||||
if (a.header === 'resolutions' && b.header === 'resolutions') {
|
||||
return a.name.replace(/\D/g, '') - b.name.replace(/\D/g, '')
|
||||
} else if (a.header === 'performance impact' && b.header === 'performance impact') {
|
||||
const x = ['potato', 'low', 'medium', 'high', 'screenshot']
|
||||
|
||||
return x.indexOf(a.name) - x.indexOf(b.name)
|
||||
}
|
||||
return 0
|
||||
})
|
||||
return x.indexOf(a.name) - x.indexOf(b.name)
|
||||
}
|
||||
return 0
|
||||
})
|
||||
}
|
||||
|
||||
export const formatNumber = (number, abbreviate = true) => {
|
||||
const x = Number(number)
|
||||
if (x >= 1000000 && abbreviate) {
|
||||
return `${(x / 1000000).toFixed(2).toString()}M`
|
||||
} else if (x >= 10000 && abbreviate) {
|
||||
return `${(x / 1000).toFixed(1).toString()}k`
|
||||
}
|
||||
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
|
||||
const x = Number(number)
|
||||
if (x >= 1000000 && abbreviate) {
|
||||
return `${(x / 1000000).toFixed(2).toString()}M`
|
||||
} else if (x >= 10000 && abbreviate) {
|
||||
return `${(x / 1000).toFixed(1).toString()}k`
|
||||
}
|
||||
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
|
||||
}
|
||||
|
||||
export function formatDate(
|
||||
date: dayjs.Dayjs,
|
||||
options: Intl.DateTimeFormatOptions = {
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
year: 'numeric',
|
||||
},
|
||||
date: dayjs.Dayjs,
|
||||
options: Intl.DateTimeFormatOptions = {
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
year: 'numeric',
|
||||
},
|
||||
): string {
|
||||
return date.toDate().toLocaleDateString(undefined, options)
|
||||
return date.toDate().toLocaleDateString(undefined, options)
|
||||
}
|
||||
|
||||
export function formatMoney(number, abbreviate = false) {
|
||||
const x = Number(number)
|
||||
if (x >= 1000000 && abbreviate) {
|
||||
return `$${(x / 1000000).toFixed(2).toString()}M`
|
||||
} else if (x >= 10000 && abbreviate) {
|
||||
return `$${(x / 1000).toFixed(2).toString()}k`
|
||||
}
|
||||
return `$${x
|
||||
.toFixed(2)
|
||||
.toString()
|
||||
.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}`
|
||||
const x = Number(number)
|
||||
if (x >= 1000000 && abbreviate) {
|
||||
return `$${(x / 1000000).toFixed(2).toString()}M`
|
||||
} else if (x >= 10000 && abbreviate) {
|
||||
return `$${(x / 1000).toFixed(2).toString()}k`
|
||||
}
|
||||
return `$${x
|
||||
.toFixed(2)
|
||||
.toString()
|
||||
.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}`
|
||||
}
|
||||
|
||||
export const formatBytes = (bytes, decimals = 2) => {
|
||||
if (bytes === 0) return '0 Bytes'
|
||||
if (bytes === 0) return '0 Bytes'
|
||||
|
||||
const k = 1024
|
||||
const dm = decimals < 0 ? 0 : decimals
|
||||
const sizes = ['Bytes', 'KiB', 'MiB', 'GiB']
|
||||
const k = 1024
|
||||
const dm = decimals < 0 ? 0 : decimals
|
||||
const sizes = ['Bytes', 'KiB', 'MiB', 'GiB']
|
||||
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||
|
||||
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`
|
||||
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`
|
||||
}
|
||||
|
||||
export const capitalizeString = (name) => {
|
||||
return name ? name.charAt(0).toUpperCase() + name.slice(1) : name
|
||||
return name ? name.charAt(0).toUpperCase() + name.slice(1) : name
|
||||
}
|
||||
|
||||
export const formatWallet = (name) => {
|
||||
if (name === 'paypal') {
|
||||
return 'PayPal'
|
||||
}
|
||||
return capitalizeString(name)
|
||||
if (name === 'paypal') {
|
||||
return 'PayPal'
|
||||
}
|
||||
return capitalizeString(name)
|
||||
}
|
||||
|
||||
export const formatProjectType = (name) => {
|
||||
if (name === 'resourcepack') {
|
||||
return 'Resource Pack'
|
||||
} else if (name === 'datapack') {
|
||||
return 'Data Pack'
|
||||
}
|
||||
if (name === 'resourcepack') {
|
||||
return 'Resource Pack'
|
||||
} else if (name === 'datapack') {
|
||||
return 'Data Pack'
|
||||
}
|
||||
|
||||
return capitalizeString(name)
|
||||
return capitalizeString(name)
|
||||
}
|
||||
|
||||
export const formatCategory = (name) => {
|
||||
if (name === 'modloader') {
|
||||
return "Risugami's ModLoader"
|
||||
} else if (name === 'bungeecord') {
|
||||
return 'BungeeCord'
|
||||
} else if (name === 'liteloader') {
|
||||
return 'LiteLoader'
|
||||
} else if (name === 'neoforge') {
|
||||
return 'NeoForge'
|
||||
} else if (name === 'game-mechanics') {
|
||||
return 'Game Mechanics'
|
||||
} else if (name === 'worldgen') {
|
||||
return 'World Generation'
|
||||
} else if (name === 'core-shaders') {
|
||||
return 'Core Shaders'
|
||||
} else if (name === 'gui') {
|
||||
return 'GUI'
|
||||
} else if (name === '8x-') {
|
||||
return '8x or lower'
|
||||
} else if (name === '512x+') {
|
||||
return '512x or higher'
|
||||
} else if (name === 'kitchen-sink') {
|
||||
return 'Kitchen Sink'
|
||||
} else if (name === 'path-tracing') {
|
||||
return 'Path Tracing'
|
||||
} else if (name === 'pbr') {
|
||||
return 'PBR'
|
||||
} else if (name === 'datapack') {
|
||||
return 'Data Pack'
|
||||
} else if (name === 'colored-lighting') {
|
||||
return 'Colored Lighting'
|
||||
} else if (name === 'optifine') {
|
||||
return 'OptiFine'
|
||||
} else if (name === 'bta-babric') {
|
||||
return 'BTA (Babric)'
|
||||
} else if (name === 'legacy-fabric') {
|
||||
return 'Legacy Fabric'
|
||||
} else if (name === 'java-agent') {
|
||||
return 'Java Agent'
|
||||
} else if (name === 'nilloader') {
|
||||
return 'NilLoader'
|
||||
} else if (name === 'mrpack') {
|
||||
return 'Modpack'
|
||||
} else if (name === 'minecraft') {
|
||||
return 'Resource Pack'
|
||||
} else if (name === 'vanilla') {
|
||||
return 'Vanilla Shader'
|
||||
}
|
||||
return capitalizeString(name)
|
||||
if (name === 'modloader') {
|
||||
return "Risugami's ModLoader"
|
||||
} else if (name === 'bungeecord') {
|
||||
return 'BungeeCord'
|
||||
} else if (name === 'liteloader') {
|
||||
return 'LiteLoader'
|
||||
} else if (name === 'neoforge') {
|
||||
return 'NeoForge'
|
||||
} else if (name === 'game-mechanics') {
|
||||
return 'Game Mechanics'
|
||||
} else if (name === 'worldgen') {
|
||||
return 'World Generation'
|
||||
} else if (name === 'core-shaders') {
|
||||
return 'Core Shaders'
|
||||
} else if (name === 'gui') {
|
||||
return 'GUI'
|
||||
} else if (name === '8x-') {
|
||||
return '8x or lower'
|
||||
} else if (name === '512x+') {
|
||||
return '512x or higher'
|
||||
} else if (name === 'kitchen-sink') {
|
||||
return 'Kitchen Sink'
|
||||
} else if (name === 'path-tracing') {
|
||||
return 'Path Tracing'
|
||||
} else if (name === 'pbr') {
|
||||
return 'PBR'
|
||||
} else if (name === 'datapack') {
|
||||
return 'Data Pack'
|
||||
} else if (name === 'colored-lighting') {
|
||||
return 'Colored Lighting'
|
||||
} else if (name === 'optifine') {
|
||||
return 'OptiFine'
|
||||
} else if (name === 'bta-babric') {
|
||||
return 'BTA (Babric)'
|
||||
} else if (name === 'legacy-fabric') {
|
||||
return 'Legacy Fabric'
|
||||
} else if (name === 'java-agent') {
|
||||
return 'Java Agent'
|
||||
} else if (name === 'nilloader') {
|
||||
return 'NilLoader'
|
||||
} else if (name === 'mrpack') {
|
||||
return 'Modpack'
|
||||
} else if (name === 'minecraft') {
|
||||
return 'Resource Pack'
|
||||
} else if (name === 'vanilla') {
|
||||
return 'Vanilla Shader'
|
||||
}
|
||||
return capitalizeString(name)
|
||||
}
|
||||
|
||||
export const formatCategoryHeader = (name) => {
|
||||
return capitalizeString(name)
|
||||
return capitalizeString(name)
|
||||
}
|
||||
|
||||
export const formatProjectStatus = (name) => {
|
||||
if (name === 'approved') {
|
||||
return 'Public'
|
||||
} else if (name === 'processing') {
|
||||
return 'Under review'
|
||||
}
|
||||
if (name === 'approved') {
|
||||
return 'Public'
|
||||
} else if (name === 'processing') {
|
||||
return 'Under review'
|
||||
}
|
||||
|
||||
return capitalizeString(name)
|
||||
return capitalizeString(name)
|
||||
}
|
||||
|
||||
export const formatVersions = (versionArray, gameVersions) => {
|
||||
const allVersions = gameVersions.slice().reverse()
|
||||
const allReleases = allVersions.filter((x) => x.version_type === 'release')
|
||||
const allVersions = gameVersions.slice().reverse()
|
||||
const allReleases = allVersions.filter((x) => x.version_type === 'release')
|
||||
|
||||
const intervals = []
|
||||
let currentInterval = 0
|
||||
const intervals = []
|
||||
let currentInterval = 0
|
||||
|
||||
for (let i = 0; i < versionArray.length; i++) {
|
||||
const index = allVersions.findIndex((x) => x.version === versionArray[i])
|
||||
const releaseIndex = allReleases.findIndex((x) => x.version === versionArray[i])
|
||||
for (let i = 0; i < versionArray.length; i++) {
|
||||
const index = allVersions.findIndex((x) => x.version === versionArray[i])
|
||||
const releaseIndex = allReleases.findIndex((x) => x.version === versionArray[i])
|
||||
|
||||
if (i === 0) {
|
||||
intervals.push([[versionArray[i], index, releaseIndex]])
|
||||
} else {
|
||||
const intervalBase = intervals[currentInterval]
|
||||
if (i === 0) {
|
||||
intervals.push([[versionArray[i], index, releaseIndex]])
|
||||
} else {
|
||||
const intervalBase = intervals[currentInterval]
|
||||
|
||||
if (
|
||||
(index - intervalBase[intervalBase.length - 1][1] === 1 ||
|
||||
releaseIndex - intervalBase[intervalBase.length - 1][2] === 1) &&
|
||||
(allVersions[intervalBase[0][1]].version_type === 'release' ||
|
||||
allVersions[index].version_type !== 'release')
|
||||
) {
|
||||
intervalBase[1] = [versionArray[i], index, releaseIndex]
|
||||
} else {
|
||||
currentInterval += 1
|
||||
intervals[currentInterval] = [[versionArray[i], index, releaseIndex]]
|
||||
}
|
||||
}
|
||||
}
|
||||
if (
|
||||
(index - intervalBase[intervalBase.length - 1][1] === 1 ||
|
||||
releaseIndex - intervalBase[intervalBase.length - 1][2] === 1) &&
|
||||
(allVersions[intervalBase[0][1]].version_type === 'release' ||
|
||||
allVersions[index].version_type !== 'release')
|
||||
) {
|
||||
intervalBase[1] = [versionArray[i], index, releaseIndex]
|
||||
} else {
|
||||
currentInterval += 1
|
||||
intervals[currentInterval] = [[versionArray[i], index, releaseIndex]]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const newIntervals = []
|
||||
for (let i = 0; i < intervals.length; i++) {
|
||||
const interval = intervals[i]
|
||||
const newIntervals = []
|
||||
for (let i = 0; i < intervals.length; i++) {
|
||||
const interval = intervals[i]
|
||||
|
||||
if (interval.length === 2 && interval[0][2] !== -1 && interval[1][2] === -1) {
|
||||
let lastSnapshot = null
|
||||
for (let j = interval[1][1]; j > interval[0][1]; j--) {
|
||||
if (allVersions[j].version_type === 'release') {
|
||||
newIntervals.push([
|
||||
interval[0],
|
||||
[
|
||||
allVersions[j].version,
|
||||
j,
|
||||
allReleases.findIndex((x) => x.version === allVersions[j].version),
|
||||
],
|
||||
])
|
||||
if (interval.length === 2 && interval[0][2] !== -1 && interval[1][2] === -1) {
|
||||
let lastSnapshot = null
|
||||
for (let j = interval[1][1]; j > interval[0][1]; j--) {
|
||||
if (allVersions[j].version_type === 'release') {
|
||||
newIntervals.push([
|
||||
interval[0],
|
||||
[
|
||||
allVersions[j].version,
|
||||
j,
|
||||
allReleases.findIndex((x) => x.version === allVersions[j].version),
|
||||
],
|
||||
])
|
||||
|
||||
if (lastSnapshot !== null && lastSnapshot !== j + 1) {
|
||||
newIntervals.push([[allVersions[lastSnapshot].version, lastSnapshot, -1], interval[1]])
|
||||
} else {
|
||||
newIntervals.push([interval[1]])
|
||||
}
|
||||
if (lastSnapshot !== null && lastSnapshot !== j + 1) {
|
||||
newIntervals.push([[allVersions[lastSnapshot].version, lastSnapshot, -1], interval[1]])
|
||||
} else {
|
||||
newIntervals.push([interval[1]])
|
||||
}
|
||||
|
||||
break
|
||||
} else {
|
||||
lastSnapshot = j
|
||||
}
|
||||
}
|
||||
} else {
|
||||
newIntervals.push(interval)
|
||||
}
|
||||
}
|
||||
break
|
||||
} else {
|
||||
lastSnapshot = j
|
||||
}
|
||||
}
|
||||
} else {
|
||||
newIntervals.push(interval)
|
||||
}
|
||||
}
|
||||
|
||||
const output = []
|
||||
const output = []
|
||||
|
||||
for (const interval of newIntervals) {
|
||||
if (interval.length === 2) {
|
||||
output.push(`${interval[0][0]}–${interval[1][0]}`)
|
||||
} else {
|
||||
output.push(interval[0][0])
|
||||
}
|
||||
}
|
||||
for (const interval of newIntervals) {
|
||||
if (interval.length === 2) {
|
||||
output.push(`${interval[0][0]}–${interval[1][0]}`)
|
||||
} else {
|
||||
output.push(interval[0][0])
|
||||
}
|
||||
}
|
||||
|
||||
return (output.length === 0 ? versionArray : output).join(', ')
|
||||
return (output.length === 0 ? versionArray : output).join(', ')
|
||||
}
|
||||
|
||||
export function cycleValue(value, values) {
|
||||
const index = values.indexOf(value) + 1
|
||||
return values[index % values.length]
|
||||
const index = values.indexOf(value) + 1
|
||||
return values[index % values.length]
|
||||
}
|
||||
|
||||
export const fileIsValid = (file, validationOptions) => {
|
||||
const { maxSize, alertOnInvalid } = validationOptions
|
||||
if (maxSize !== null && maxSize !== undefined && file.size > maxSize) {
|
||||
if (alertOnInvalid) {
|
||||
alert(`File ${file.name} is too big! Must be less than ${formatBytes(maxSize)}`)
|
||||
}
|
||||
return false
|
||||
}
|
||||
const { maxSize, alertOnInvalid } = validationOptions
|
||||
if (maxSize !== null && maxSize !== undefined && file.size > maxSize) {
|
||||
if (alertOnInvalid) {
|
||||
alert(`File ${file.name} is too big! Must be less than ${formatBytes(maxSize)}`)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
return true
|
||||
}
|
||||
|
||||
export const acceptFileFromProjectType = (projectType) => {
|
||||
switch (projectType) {
|
||||
case 'mod':
|
||||
return '.jar,.zip,.litemod,application/java-archive,application/x-java-archive,application/zip'
|
||||
case 'plugin':
|
||||
return '.jar,.zip,application/java-archive,application/x-java-archive,application/zip'
|
||||
case 'resourcepack':
|
||||
return '.zip,application/zip'
|
||||
case 'shader':
|
||||
return '.zip,application/zip'
|
||||
case 'datapack':
|
||||
return '.zip,application/zip'
|
||||
case 'modpack':
|
||||
return '.mrpack,application/x-modrinth-modpack+zip,application/zip'
|
||||
default:
|
||||
return '*'
|
||||
}
|
||||
switch (projectType) {
|
||||
case 'mod':
|
||||
return '.jar,.zip,.litemod,application/java-archive,application/x-java-archive,application/zip'
|
||||
case 'plugin':
|
||||
return '.jar,.zip,application/java-archive,application/x-java-archive,application/zip'
|
||||
case 'resourcepack':
|
||||
return '.zip,application/zip'
|
||||
case 'shader':
|
||||
return '.zip,application/zip'
|
||||
case 'datapack':
|
||||
return '.zip,application/zip'
|
||||
case 'modpack':
|
||||
return '.mrpack,application/x-modrinth-modpack+zip,application/zip'
|
||||
default:
|
||||
return '*'
|
||||
}
|
||||
}
|
||||
|
||||
// Sorts alphabetically, but correctly identifies 8x, 128x, 256x, etc
|
||||
// identifier[0], then if it ties, identifier[1], etc
|
||||
export const sortByNameOrNumber = (sortable, identifiers) => {
|
||||
sortable.sort((a, b) => {
|
||||
for (const identifier of identifiers) {
|
||||
const aNum = parseFloat(a[identifier])
|
||||
const bNum = parseFloat(b[identifier])
|
||||
if (isNaN(aNum) && isNaN(bNum)) {
|
||||
// Both are strings, sort alphabetically
|
||||
const stringComp = a[identifier].localeCompare(b[identifier])
|
||||
if (stringComp != 0) return stringComp
|
||||
} else if (!isNaN(aNum) && !isNaN(bNum)) {
|
||||
// Both are numbers, sort numerically
|
||||
const numComp = aNum - bNum
|
||||
if (numComp != 0) return numComp
|
||||
} else {
|
||||
// One is a number and one is a string, numbers go first
|
||||
const numStringComp = isNaN(aNum) ? 1 : -1
|
||||
if (numStringComp != 0) return numStringComp
|
||||
}
|
||||
}
|
||||
return 0
|
||||
})
|
||||
return sortable
|
||||
sortable.sort((a, b) => {
|
||||
for (const identifier of identifiers) {
|
||||
const aNum = parseFloat(a[identifier])
|
||||
const bNum = parseFloat(b[identifier])
|
||||
if (isNaN(aNum) && isNaN(bNum)) {
|
||||
// Both are strings, sort alphabetically
|
||||
const stringComp = a[identifier].localeCompare(b[identifier])
|
||||
if (stringComp != 0) return stringComp
|
||||
} else if (!isNaN(aNum) && !isNaN(bNum)) {
|
||||
// Both are numbers, sort numerically
|
||||
const numComp = aNum - bNum
|
||||
if (numComp != 0) return numComp
|
||||
} else {
|
||||
// One is a number and one is a string, numbers go first
|
||||
const numStringComp = isNaN(aNum) ? 1 : -1
|
||||
if (numStringComp != 0) return numStringComp
|
||||
}
|
||||
}
|
||||
return 0
|
||||
})
|
||||
return sortable
|
||||
}
|
||||
|
||||
export const getArrayOrString = (x: string[] | string): string[] => {
|
||||
if (typeof x === 'string') {
|
||||
return [x]
|
||||
} else {
|
||||
return x
|
||||
}
|
||||
if (typeof x === 'string') {
|
||||
return [x]
|
||||
} else {
|
||||
return x
|
||||
}
|
||||
}
|
||||
|
||||
export function getPingLevel(ping: number) {
|
||||
if (ping < 120) {
|
||||
return 5
|
||||
} else if (ping < 200) {
|
||||
return 4
|
||||
} else if (ping < 300) {
|
||||
return 3
|
||||
} else if (ping < 400) {
|
||||
return 2
|
||||
} else {
|
||||
return 1
|
||||
}
|
||||
if (ping < 120) {
|
||||
return 5
|
||||
} else if (ping < 200) {
|
||||
return 4
|
||||
} else if (ping < 300) {
|
||||
return 3
|
||||
} else if (ping < 400) {
|
||||
return 2
|
||||
} else {
|
||||
return 1
|
||||
}
|
||||
}
|
||||
|
||||
export function arrayBufferToBase64(buffer: Uint8Array | ArrayBuffer): string {
|
||||
const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer)
|
||||
return btoa(String.fromCharCode(...bytes))
|
||||
const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer)
|
||||
return btoa(String.fromCharCode(...bytes))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user