-
Notifications
You must be signed in to change notification settings - Fork 437
Expand file tree
/
Copy pathutils.ts
More file actions
419 lines (361 loc) · 14.4 KB
/
utils.ts
File metadata and controls
419 lines (361 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
import type { Labrinth } from '@modrinth/api-client'
import type {
Action,
AdditionalTextInput,
ButtonAction,
ConditionalMessage,
ToggleAction,
} from './types/actions'
export interface ActionState {
selected: boolean
value?: Set<number> | number | string | unknown
}
export interface MessagePart {
weight: number
content: string
actionId: string
stageIndex: number
}
export type SerializedActionState = {
isSet?: boolean
} & ActionState
export function getActionIdForStage(
action: Action,
stageIndex: number,
actionIndex?: number,
enabledIndex?: number,
): string {
if (action.id) {
return `stage-${stageIndex}-${action.id}`
}
const suffix = enabledIndex !== undefined ? `-enabled-${enabledIndex}` : ''
return `stage-${stageIndex}-action-${actionIndex}${suffix}`
}
export function getActionId(action: Action, currentStage: number, index?: number): string {
return getActionIdForStage(action, currentStage, index)
}
export function getActionKey(
action: Action,
currentStage: number,
visibleActions: Action[],
): string {
const index = visibleActions.indexOf(action)
return `${currentStage}-${index}-${getActionId(action, currentStage)}`
}
export function serializeActionStates(states: Record<string, ActionState>): string {
const serializable: Record<string, SerializedActionState> = {}
for (const [key, state] of Object.entries(states)) {
serializable[key] = {
selected: state.selected,
value: state.value instanceof Set ? Array.from(state.value) : state.value,
isSet: state.value instanceof Set,
}
}
return JSON.stringify(serializable)
}
export function deserializeActionStates(data: string): Record<string, ActionState> {
try {
const parsed = JSON.parse(data)
const states: Record<string, ActionState> = {}
for (const [key, state] of Object.entries(parsed as Record<string, SerializedActionState>)) {
states[key] = {
selected: state.selected,
value: state.isSet ? new Set(state.value as unknown[]) : state.value,
}
}
return states
} catch {
return {}
}
}
export function initializeActionState(action: Action): ActionState {
if (action.type === 'toggle') {
return {
selected: action.defaultChecked || false,
}
} else if (action.type === 'dropdown') {
return {
selected: true,
value: action.defaultOption || 0,
}
} else if (action.type === 'multi-select-chips') {
return {
selected: false,
value: new Set<number>(),
}
} else {
return {
selected: false,
}
}
}
export function processMessage(
message: string,
action: Action,
stageIndex: number,
textInputValues: Record<string, string>,
): string {
let processedMessage = message
if (action.relevantExtraInput) {
action.relevantExtraInput.forEach((input, index) => {
if (input.variable) {
const inputKey = `stage-${stageIndex}-${action.id || `action-${index}`}-${index}`
const value = textInputValues[inputKey] || ''
const regex = new RegExp(`%${input.variable}%`, 'g')
processedMessage = processedMessage.replace(regex, value)
}
})
}
return processedMessage
}
export function findMatchingVariant(
variants: ConditionalMessage[],
selectedActionIds: string[],
allValidActionIds?: string[],
currentStageIndex?: number,
): ConditionalMessage | null {
for (const variant of variants) {
const conditions = variant.conditions
const meetsRequired =
!conditions.requiredActions ||
conditions.requiredActions.every((id) => {
let fullId = id
if (currentStageIndex !== undefined && !id.startsWith('stage-')) {
fullId = `stage-${currentStageIndex}-${id}`
}
if (allValidActionIds && !allValidActionIds.includes(fullId)) {
return false
}
return selectedActionIds.includes(fullId)
})
const meetsExcluded =
!conditions.excludedActions ||
!conditions.excludedActions.some((id) => {
let fullId = id
if (currentStageIndex !== undefined && !id.startsWith('stage-')) {
fullId = `stage-${currentStageIndex}-${id}`
}
return selectedActionIds.includes(fullId)
})
if (meetsRequired && meetsExcluded) {
return variant
}
}
return null
}
export async function getActionMessage(
action: ButtonAction | ToggleAction,
selectedActionIds: string[],
allValidActionIds?: string[],
): Promise<string> {
if (action.conditionalMessages && action.conditionalMessages.length > 0) {
const matchingConditional = findMatchingVariant(
action.conditionalMessages,
selectedActionIds,
allValidActionIds,
)
if (matchingConditional) {
return (await matchingConditional.message()) as string
}
}
return (await action.message()) as string
}
export function getVisibleInputs(
action: Action,
actionStates: Record<string, ActionState>,
): AdditionalTextInput[] {
if (!action.relevantExtraInput) return []
const selectedActionIds = Object.entries(actionStates)
.filter(([, state]) => state.selected)
.map(([id]) => id)
return action.relevantExtraInput.filter((input) => {
if (!input.showWhen) return true
const meetsRequired =
!input.showWhen.requiredActions ||
input.showWhen.requiredActions.every((id) => selectedActionIds.includes(id))
const meetsExcluded =
!input.showWhen.excludedActions ||
!input.showWhen.excludedActions.some((id) => selectedActionIds.includes(id))
return meetsRequired && meetsExcluded
})
}
export function expandVariables(
template: string,
project: Labrinth.Projects.v2.Project,
projectV3: Labrinth.Projects.v3.Project,
variables?: Record<string, string>,
): string {
variables ??= {
...flattenStaticVariables(),
...flattenProjectVariables(project),
...flattenProjectV3Variables(projectV3),
}
return Object.entries(variables).reduce((result, [key, value]) => {
const variable = `%${key}%`
return result.replace(new RegExp(variable, 'g'), value)
}, template)
}
export function kebabToTitleCase(input: string): string {
return input
.split('-')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ')
}
export function arrayOrNone(arr: string[]): string {
return arr.length > 0 ? arr.join(', ') : 'None'
}
export function formatProjectTypes(type: string, lower: boolean = false) {
let value = type
try {
value = value
.replaceAll('mod', 'Mod')
.replaceAll('resourcepack', 'Resource Pack')
.replaceAll('datapack', 'Data Pack')
.replaceAll('plugin', 'Plugin')
.replaceAll('shader', 'Shaders')
.replaceAll('minecraft_java_server', 'Server')
.replaceAll('minecraft_server', 'Server')
} catch {
return 'No project type'
}
if (lower === true) value = value.toLowerCase()
return value
}
export function flattenStaticVariables(): Record<string, string> {
const vars: Record<string, string> = {}
vars[`RULES`] = `[Modrinth's Content Rules](https://modrinth.com/legal/rules)`
vars[`TOS`] = `[Terms of Use](https://modrinth.com/legal/terms)`
vars[`COPYRIGHT_POLICY`] = `[Copyright Policy](https://modrinth.com/legal/copyright)`
vars[`SUPPORT`] =
`please visit the [Modrinth Help Center](https://support.modrinth.com/) and click the blue bubble to contact support.`
vars[`MODPACK_PERMISSIONS_GUIDE`] =
`our guide to [Obtaining Modpack Permissions](https://support.modrinth.com/en/articles/8797527-obtaining-modpack-permissions)`
vars[`MODPACKS_ON_MODRINTH`] =
`[Modpacks on Modrinth](https://support.modrinth.com/en/articles/8802250-modpacks-on-modrinth)`
vars[`ADVANCED_MARKDOWN`] =
`[Markdown Formatting Guide](https://support.modrinth.com/en/articles/8801962-advanced-markdown-formatting)`
vars[`LICENSING_GUIDE`] =
`our guide to [Licensing your Mods](https://modrinth.com/news/article/licensing-guide)`
vars[`NEW_ENVIRONMENTS_LINK`] = `https://modrinth.com/news/article/new-environments`
vars[`LEARN_MORE_ABOUT_SERVERS_FLINK`] =
`[learn more about server projects from our news feed](https://modrinth.com/news/article/introducing-server-projects/)`
return vars
}
export function flattenProjectVariables(
project: Labrinth.Projects.v2.Project,
): Record<string, string> {
const vars: Record<string, string> = {}
vars['PROJECT_ID'] = project.id
vars['PROJECT_TYPE'] = project.project_type
vars['PROJECT_SLUG'] = project.slug
vars['PROJECT_TITLE'] = project.title
vars['PROJECT_SUMMARY'] = project.description
vars['PROJECT_STATUS'] = project.status
vars['PROJECT_REQUESTED_STATUS'] = project.requested_status
vars['PROJECT_MONETIZATION_STATUS'] = project.monetization_status
vars['PROJECT_BODY'] = project.body
vars['PROJECT_ICON_URL'] = project.icon_url || ''
vars['PROJECT_ISSUES_URL'] = project.issues_url || 'None'
vars['PROJECT_SOURCE_URL'] = project.source_url || 'None'
vars['PROJECT_WIKI_URL'] = project.wiki_url || 'None'
vars['PROJECT_DISCORD_URL'] = project.discord_url || 'None'
vars['PROJECT_DOWNLOADS'] = project.downloads.toString()
vars['PROJECT_FOLLOWERS'] = project.followers.toString()
vars['PROJECT_COLOR'] = project.color?.toString() || ''
vars['PROJECT_CLIENT_SIDE'] = project.client_side
vars['PROJECT_SERVER_SIDE'] = project.server_side
vars['PROJECT_TEAM'] = project.team || 'None'
vars['PROJECT_THREAD_ID'] = project.thread_id
vars['PROJECT_ORGANIZATION'] = project.organization
vars['PROJECT_PUBLISHED'] = project.published
vars['PROJECT_UPDATED'] = project.updated
vars['PROJECT_APPROVED'] = project.approved
vars['PROJECT_QUEUED'] = project.queued
vars['PROJECT_LICENSE_ID'] = project.license.id
vars['PROJECT_LICENSE_NAME'] = project.license.name
vars['PROJECT_LICENSE_URL'] = project.license.url || 'None'
vars['PROJECT_CATEGORIES'] = arrayOrNone(project.categories)
vars['PROJECT_ADDITIONAL_CATEGORIES'] = arrayOrNone(project.additional_categories)
vars['PROJECT_GAME_VERSIONS'] = arrayOrNone(project.game_versions)
vars['PROJECT_LOADERS'] = arrayOrNone(project.loaders)
vars['PROJECT_VERSIONS'] = arrayOrNone(project.versions)
vars['PROJECT_CATEGORIES_COUNT'] = project.categories.length.toString()
vars['PROJECT_GAME_VERSIONS_COUNT'] = project.game_versions.length.toString()
vars['PROJECT_LOADERS_COUNT'] = project.loaders.length.toString()
vars['PROJECT_VERSIONS_COUNT'] = project.versions.length.toString()
vars['PROJECT_GALLERY_COUNT'] = (project.gallery?.length || 0).toString()
vars['PROJECT_DONATION_URLS_COUNT'] = project.donation_urls.length.toString()
project.donation_urls.forEach((donation, index) => {
vars[`PROJECT_DONATION_${index}_ID`] = donation.id
vars[`PROJECT_DONATION_${index}_PLATFORM`] = donation.platform
vars[`PROJECT_DONATION_${index}_URL`] = donation.url
})
project.gallery?.forEach((image, index) => {
vars[`PROJECT_GALLERY_${index}_URL`] = image.url
vars[`PROJECT_GALLERY_${index}_TITLE`] = image.title || ''
vars[`PROJECT_GALLERY_${index}_DESCRIPTION`] = image.description || ''
vars[`PROJECT_GALLERY_${index}_FEATURED`] = image.featured.toString()
})
// Navigation related variables
vars[`PROJECT_PERMANENT_LINK`] = `https://modrinth.com/project/${project.id}`
vars[`PROJECT_SETTINGS_LINK`] = `https://modrinth.com/project/${project.id}/settings`
vars[`PROJECT_SETTINGS_FLINK`] = `[Settings](https://modrinth.com/project/${project.id}/settings)`
vars[`PROJECT_TITLE_FLINK`] = `[Name](https://modrinth.com/project/${project.id}/settings)`
vars[`PROJECT_SLUG_FLINK`] = `[URL](https://modrinth.com/project/${project.id}/settings)`
vars[`PROJECT_SUMMARY_FLINK`] = `[Summary](https://modrinth.com/project/${project.id}/settings)`
vars[`PROJECT_ENVIRONMENT_FLINK`] =
`[Environment Information](https://modrinth.com/project/${project.id}/settings/environment)` // Depreciated
vars[`PROJECT_TAGS_LINK`] = `https://modrinth.com/project/${project.id}/settings/tags`
vars[`PROJECT_TAGS_FLINK`] = `[Tags](https://modrinth.com/project/${project.id}/settings/tags)`
vars[`PROJECT_DESCRIPTION_LINK`] =
`https://modrinth.com/project/${project.id}/settings/description`
vars[`PROJECT_DESCRIPTION_FLINK`] =
`[Description](https://modrinth.com/project/${project.id}/settings/description)`
vars[`PROJECT_LICENSE_LINK`] = `https://modrinth.com/project/${project.id}/settings/license`
vars[`PROJECT_LICENSE_FLINK`] =
`[License](https://modrinth.com/project/${project.id}/settings/license)`
vars[`PROJECT_LINKS_LINK`] = `https://modrinth.com/project/${project.id}/settings/links`
vars[`PROJECT_LINKS_FLINK`] =
`[External Links](https://modrinth.com/project/${project.id}/settings/links)`
vars[`PROJECT_GALLERY_LINK`] = `https://modrinth.com/project/${project.id}/gallery`
vars[`PROJECT_GALLERY_FLINK`] =
`[Gallery](https://modrinth.com/project/${project.id}/settings/gallery)`
vars[`PROJECT_VERSIONS_LINK`] = `https://modrinth.com/project/${project.id}/versions`
vars[`PROJECT_VERSIONS_FLINK`] =
`[Versions](https://modrinth.com/project/${project.id}/settings/versions)`
vars[`PROJECT_MODERATION_LINK`] = `https://modrinth.com/project/${project.id}/moderation`
vars[`PROJECT_MODERATION_FLINK`] =
`[moderation tab](https://modrinth.com/project/${project.id}/moderation)`
vars[`PROJECT_SERVER_SETTINGS`] = `https://modrinth.com/project/${project.id}/settings/server`
vars[`PROJECT_SERVER_SETTINGS_FLINK`] =
`[Server Settings](https://modrinth.com/project/${project.id}/settings/server)`
vars[`PROJECT_LANGUAGE_SETTINGS`] = `https://modrinth.com/project/${project.id}/settings/server`
vars[`PROJECT_LANGUAGE_SETTINGS_FLINK`] =
`[Language Settings](https://modrinth.com/project/${project.id}/settings/server)`
return vars
}
export function flattenProjectV3Variables(
projectV3: Labrinth.Projects.v3.Project,
): Record<string, string> {
const vars: Record<string, string> = {}
const environment = projectV3.environment ?? []
vars['PROJECT_V3_ENVIRONMENT_COUNT'] = environment.length.toString()
vars['PROJECT_V3_ALL_ENVIRONMENTS'] = environment.join(', ')
environment.forEach((env, index) => {
vars[`PROJECT_V3_ENVIRONMENT_${index}`] = env
})
vars['PROJECT_V3_REVIEW_STATUS'] = projectV3.side_types_migration_review_status
vars['PROJECT_V3_TYPES'] = projectV3.project_types.join(', ')
vars['PROJECT_TYPE_FORMATTED'] = formatProjectTypes(projectV3.project_types[0])
vars['PROJECT_TYPE_FORMATTED_LOWER'] = formatProjectTypes(projectV3.project_types[0], true)
vars['PROJECT_TYPES_FORMATTED'] = formatProjectTypes(projectV3.project_types.join(' / '))
vars['PROJECT_TYPES_FORMATTED_LOWER'] = formatProjectTypes(
projectV3.project_types.join(' / '),
true,
)
vars['PROJECT_SITE_URL'] = projectV3.link_urls?.site?.url || 'None'
vars['PROJECT_STORE_URL'] = projectV3.link_urls?.store?.url || 'None'
vars['PROJECT_LANGUAGES'] = projectV3.minecraft_server?.languages?.toString() || 'None'
vars['PROJECT_LANGUAGE_COUNT'] = (projectV3.minecraft_server?.languages?.length || 0).toString()
return vars
}