cordo 2.12.2 → 2.13.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +5 -5
- package/src/core/files/command.ts +301 -0
- package/src/core/files/config.ts +24 -17
- package/src/core/files/lockfile.ts +4 -1
- package/src/core/files/route.ts +3 -3
- package/src/core/gateway.ts +13 -4
- package/src/core/index.ts +7 -4
- package/src/core/routing/filesystem.ts +38 -5
- package/src/core/routing/resolve.ts +1 -1
- package/src/core/routing/respond.ts +2 -2
- package/src/functions/index.ts +8 -0
- package/src/lib/constants.ts +1 -0
- package/src/lib/localization.ts +37 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cordo",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.13.2",
|
|
4
4
|
"description": "A framework for handling complex discord api interactions",
|
|
5
5
|
"exports": {
|
|
6
6
|
".": "./src/index.ts",
|
|
@@ -26,19 +26,18 @@
|
|
|
26
26
|
},
|
|
27
27
|
"repository": {
|
|
28
28
|
"type": "git",
|
|
29
|
-
"url": "
|
|
29
|
+
"url": "https://github.com/maanex/cordo.git"
|
|
30
30
|
},
|
|
31
31
|
"author": "Andreas May <andreas@maanex.me>",
|
|
32
32
|
"license": "ISC",
|
|
33
33
|
"bugs": {
|
|
34
|
-
"url": "https://github.com/
|
|
34
|
+
"url": "https://github.com/maanex/cordo/issues"
|
|
35
35
|
},
|
|
36
|
-
"homepage": "https://github.com/
|
|
36
|
+
"homepage": "https://github.com/maanex/cordo#readme",
|
|
37
37
|
"dependencies": {
|
|
38
38
|
"@types/bun": "^1.2.10",
|
|
39
39
|
"axios": "^0.21.4",
|
|
40
40
|
"defu": "^6.1.4",
|
|
41
|
-
"discord-api-types": "^0.38.42",
|
|
42
41
|
"discord-interactions": "^2.4.1",
|
|
43
42
|
"type-fest": "^4.34.1"
|
|
44
43
|
},
|
|
@@ -48,6 +47,7 @@
|
|
|
48
47
|
"@types/node": "^17.0.8",
|
|
49
48
|
"@typescript-eslint/eslint-plugin": "^4.28.3",
|
|
50
49
|
"@typescript-eslint/parser": "^4.28.3",
|
|
50
|
+
"discord-api-types": "^0.38.53",
|
|
51
51
|
"discord.js": "^14.18.0",
|
|
52
52
|
"eslint": "^7.30.0",
|
|
53
53
|
"eslint-config-maanex": "^1.1.2",
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
import type { Permissions } from 'discord-api-types/globals'
|
|
2
|
+
import { ChannelType, ApplicationCommandOptionType, ApplicationCommandType, type APIApplicationCommandOption } from 'discord-api-types/v10'
|
|
3
|
+
import type { LocalizedString } from '../../lib/localization'
|
|
4
|
+
import { CordoGateway } from '../gateway'
|
|
5
|
+
import { RoutingResolve } from '../routing/resolve'
|
|
6
|
+
import type { CordoRoute } from './route'
|
|
7
|
+
|
|
8
|
+
type CommandOption = {
|
|
9
|
+
name: string | LocalizedString
|
|
10
|
+
description: string | LocalizedString
|
|
11
|
+
required?: boolean
|
|
12
|
+
} & ({
|
|
13
|
+
type: 'string'
|
|
14
|
+
minLength?: number
|
|
15
|
+
maxLength?: number
|
|
16
|
+
choices: Array<{
|
|
17
|
+
name: string | LocalizedString
|
|
18
|
+
value: string
|
|
19
|
+
}>
|
|
20
|
+
} | {
|
|
21
|
+
type: 'integer'
|
|
22
|
+
minValue?: number
|
|
23
|
+
maxValue?: number
|
|
24
|
+
autocomplete?: boolean
|
|
25
|
+
choices?: Array<{
|
|
26
|
+
name: string | LocalizedString
|
|
27
|
+
value: number
|
|
28
|
+
}>
|
|
29
|
+
} | {
|
|
30
|
+
type: 'boolean'
|
|
31
|
+
} | {
|
|
32
|
+
type: 'user'
|
|
33
|
+
} | {
|
|
34
|
+
type: 'channel'
|
|
35
|
+
channelTypes?: ChannelType[]
|
|
36
|
+
} | {
|
|
37
|
+
type: 'role'
|
|
38
|
+
} | {
|
|
39
|
+
type: 'mentionable'
|
|
40
|
+
} | {
|
|
41
|
+
type: 'number'
|
|
42
|
+
minValue?: number
|
|
43
|
+
maxValue?: number
|
|
44
|
+
autocomplete?: boolean
|
|
45
|
+
choices: Array<{
|
|
46
|
+
name: string | LocalizedString
|
|
47
|
+
value: number
|
|
48
|
+
}>
|
|
49
|
+
} | {
|
|
50
|
+
type: 'attachment'
|
|
51
|
+
fileTypes?: Array<'image' | 'video' | 'audio' | `.${string}`>
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
const CordoCommandSymbol = Symbol.for('CordoCommand')
|
|
55
|
+
|
|
56
|
+
type CommandInput = {
|
|
57
|
+
type: 'chat' | 'message' | 'user' | 'entrypoint'
|
|
58
|
+
name?: string | LocalizedString
|
|
59
|
+
description?: string | LocalizedString
|
|
60
|
+
defaultMemberPermissions?: Permissions
|
|
61
|
+
nsfw?: boolean
|
|
62
|
+
limitInstallTypes?: Array<'guild' | 'user'>
|
|
63
|
+
limitContexts?: Array<'guild' | 'dm' | 'group'>
|
|
64
|
+
|
|
65
|
+
options: CommandOption[]
|
|
66
|
+
|
|
67
|
+
route: CordoRoute | 'launch_activity'
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export type CordoCommand = {
|
|
71
|
+
[CordoCommandSymbol]: typeof CordoCommandSymbol
|
|
72
|
+
} & CommandInput
|
|
73
|
+
|
|
74
|
+
export function defineCordoCommand(command: CommandInput): CordoCommand {
|
|
75
|
+
return {
|
|
76
|
+
[CordoCommandSymbol]: CordoCommandSymbol,
|
|
77
|
+
...command
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export namespace CommandInternals {
|
|
82
|
+
export async function readCommand(filePath: string): Promise<CordoCommand | null> {
|
|
83
|
+
const content = await import(filePath)
|
|
84
|
+
|
|
85
|
+
if (!content || !content.default)
|
|
86
|
+
return null
|
|
87
|
+
|
|
88
|
+
if (!content.default[CordoCommandSymbol])
|
|
89
|
+
return null
|
|
90
|
+
|
|
91
|
+
return content.default
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const optionTypeMap: Record<string, ApplicationCommandOptionType> = {
|
|
95
|
+
string: ApplicationCommandOptionType.String,
|
|
96
|
+
integer: ApplicationCommandOptionType.Integer,
|
|
97
|
+
boolean: ApplicationCommandOptionType.Boolean,
|
|
98
|
+
user: ApplicationCommandOptionType.User,
|
|
99
|
+
channel: ApplicationCommandOptionType.Channel,
|
|
100
|
+
role: ApplicationCommandOptionType.Role,
|
|
101
|
+
mentionable: ApplicationCommandOptionType.Mentionable,
|
|
102
|
+
number: ApplicationCommandOptionType.Number,
|
|
103
|
+
attachment: ApplicationCommandOptionType.Attachment
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const commandTypeMap: Record<string, ApplicationCommandType> = {
|
|
107
|
+
chat: ApplicationCommandType.ChatInput,
|
|
108
|
+
user: ApplicationCommandType.User,
|
|
109
|
+
message: ApplicationCommandType.Message,
|
|
110
|
+
entrypoint: 4 // ApplicationCommandType.PrimaryEntryPoint
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function resolveLocalizedText(input: string | LocalizedString | undefined, fallback: string = ''): { value: string, localizations: Record<string, string> | undefined } {
|
|
114
|
+
if (typeof input === 'string') {
|
|
115
|
+
return { value: input, localizations: undefined }
|
|
116
|
+
} else if (input && typeof input === 'object') {
|
|
117
|
+
const localizations = { ...input }
|
|
118
|
+
delete (localizations as any).default
|
|
119
|
+
return { value: input.default, localizations }
|
|
120
|
+
}
|
|
121
|
+
return { value: fallback, localizations: undefined }
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function mapCommandOptionToApiOption(opt: any): APIApplicationCommandOption {
|
|
125
|
+
const { value: name, localizations: name_localizations } = resolveLocalizedText(opt.name)
|
|
126
|
+
const { value: description, localizations: description_localizations } = resolveLocalizedText(opt.description)
|
|
127
|
+
|
|
128
|
+
const res: any = {
|
|
129
|
+
type: optionTypeMap[opt.type] || ApplicationCommandOptionType.String,
|
|
130
|
+
name,
|
|
131
|
+
name_localizations,
|
|
132
|
+
description,
|
|
133
|
+
description_localizations,
|
|
134
|
+
required: opt.required,
|
|
135
|
+
autocomplete: opt.autocomplete,
|
|
136
|
+
min_value: opt.minValue,
|
|
137
|
+
max_value: opt.maxValue,
|
|
138
|
+
min_length: opt.minLength,
|
|
139
|
+
max_length: opt.maxLength,
|
|
140
|
+
file_types: opt.fileTypes,
|
|
141
|
+
channel_types: opt.channelTypes,
|
|
142
|
+
choices: opt.choices?.map((c: any) => {
|
|
143
|
+
const { value: name, localizations: name_localizations } = resolveLocalizedText(c.name)
|
|
144
|
+
return { name, name_localizations, value: c.value }
|
|
145
|
+
})
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
return res
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
interface CommandTree {
|
|
152
|
+
command?: CordoCommand
|
|
153
|
+
subcommands: Map<string, CommandTree>
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function buildApiOption(rawName: string, tree: CommandTree): APIApplicationCommandOption {
|
|
157
|
+
const { value: name, localizations: name_localizations } = resolveLocalizedText(tree.command?.name, rawName)
|
|
158
|
+
const { value: description, localizations: description_localizations } = resolveLocalizedText(tree.command?.description, 'No description provided')
|
|
159
|
+
|
|
160
|
+
const isGroup = tree.subcommands.size > 0
|
|
161
|
+
|
|
162
|
+
const options: any[] = []
|
|
163
|
+
if (isGroup) {
|
|
164
|
+
for (const [ subName, subTree ] of tree.subcommands.entries())
|
|
165
|
+
options.push(buildApiOption(subName, subTree))
|
|
166
|
+
} else if (tree.command?.options) {
|
|
167
|
+
options.push(...tree.command.options.map(mapCommandOptionToApiOption))
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
return {
|
|
171
|
+
type: isGroup
|
|
172
|
+
? ApplicationCommandOptionType.SubcommandGroup
|
|
173
|
+
: ApplicationCommandOptionType.Subcommand,
|
|
174
|
+
name,
|
|
175
|
+
name_localizations,
|
|
176
|
+
description,
|
|
177
|
+
description_localizations,
|
|
178
|
+
options: options.length > 0 ? options : undefined
|
|
179
|
+
} as any
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export async function syncCommands(commands: Map<string, CordoCommand>, guild?: string, options?: { maxRetries?: number }) {
|
|
183
|
+
if (!commands || commands.size === 0) {
|
|
184
|
+
console.warn('No commands to sync. Is cordo initialized and commands defined?')
|
|
185
|
+
return
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const rootCommands = new Map<string, CommandTree>()
|
|
189
|
+
|
|
190
|
+
for (const [ route, command ] of commands.entries()) {
|
|
191
|
+
const parts = route.split('/')
|
|
192
|
+
let currentLevel = rootCommands
|
|
193
|
+
|
|
194
|
+
for (let i = 0; i < parts.length; i++) {
|
|
195
|
+
const part = parts[i]
|
|
196
|
+
if (!currentLevel.has(part))
|
|
197
|
+
currentLevel.set(part, { subcommands: new Map() })
|
|
198
|
+
|
|
199
|
+
const node = currentLevel.get(part)!
|
|
200
|
+
if (i === parts.length - 1)
|
|
201
|
+
node.command = command
|
|
202
|
+
|
|
203
|
+
currentLevel = node.subcommands
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const apiCommands: any[] = []
|
|
208
|
+
|
|
209
|
+
for (const [ rootName, tree ] of rootCommands.entries()) {
|
|
210
|
+
let { value: name, localizations: nameLocalizations } = resolveLocalizedText(tree.command?.name, rootName)
|
|
211
|
+
|
|
212
|
+
if (tree.command) {
|
|
213
|
+
const commandTypeStr = tree.command.type === 'chat' ? 'slash' : tree.command.type
|
|
214
|
+
if (commandTypeStr === 'slash' || commandTypeStr === 'message' || commandTypeStr === 'user') {
|
|
215
|
+
const expectedRoute = RoutingResolve.getRouteForCommand(name, commandTypeStr as any).path.split('/').pop()
|
|
216
|
+
if (expectedRoute !== rootName) {
|
|
217
|
+
console.error(`Command name '${name}' resolves to route '${expectedRoute}' which does not match actual route '${rootName}'. Using route name instead.`)
|
|
218
|
+
name = rootName
|
|
219
|
+
nameLocalizations = undefined
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const { value: description, localizations: descriptionLocalizations } = resolveLocalizedText(
|
|
225
|
+
tree.command?.description,
|
|
226
|
+
tree.subcommands.size > 0 ? 'Command group' : 'No description provided'
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
const cmdType = tree.command ? (commandTypeMap[tree.command.type] || ApplicationCommandType.ChatInput) : ApplicationCommandType.ChatInput
|
|
230
|
+
|
|
231
|
+
const apiOptions: any[] = []
|
|
232
|
+
if (tree.subcommands.size > 0) {
|
|
233
|
+
for (const [ subName, subTree ] of tree.subcommands.entries())
|
|
234
|
+
apiOptions.push(buildApiOption(subName, subTree))
|
|
235
|
+
|
|
236
|
+
} else if (tree.command?.options) {
|
|
237
|
+
apiOptions.push(...tree.command.options.map(mapCommandOptionToApiOption))
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const apiCmd: any = {
|
|
241
|
+
name,
|
|
242
|
+
name_localizations: nameLocalizations,
|
|
243
|
+
description,
|
|
244
|
+
description_localizations: descriptionLocalizations,
|
|
245
|
+
type: cmdType,
|
|
246
|
+
options: apiOptions.length > 0 ? apiOptions : undefined
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
if (tree.command) {
|
|
250
|
+
apiCmd.default_member_permissions = tree.command.defaultMemberPermissions?.toString()
|
|
251
|
+
apiCmd.nsfw = tree.command.nsfw
|
|
252
|
+
apiCmd.contexts = tree.command.limitContexts ? tree.command.limitContexts.map(c => c === 'guild' ? 0 : c === 'dm' ? 1 : 2) : undefined
|
|
253
|
+
apiCmd.integration_types = tree.command.limitInstallTypes ? tree.command.limitInstallTypes.map(i => i === 'guild' ? 0 : 1) : undefined
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
apiCommands.push(apiCmd)
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const maxRetries = options?.maxRetries ?? 3
|
|
260
|
+
|
|
261
|
+
for (const apiCmd of apiCommands.values()) {
|
|
262
|
+
let retries = 0
|
|
263
|
+
|
|
264
|
+
while (true) {
|
|
265
|
+
const res = await CordoGateway.upsertCommand(apiCmd, guild)
|
|
266
|
+
|
|
267
|
+
if (res.status === 429) {
|
|
268
|
+
const retryAfter = res.headers['retry-after'] || res.data?.retry_after
|
|
269
|
+
const waitTime = retryAfter ? parseFloat(retryAfter) * 1000 : 5000
|
|
270
|
+
console.warn(`Rate limited (429) when syncing command '${apiCmd.name}'. Waiting ${waitTime}ms...`)
|
|
271
|
+
await new Promise(resolve => setTimeout(resolve, waitTime))
|
|
272
|
+
continue
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
if (res.status >= 400) {
|
|
276
|
+
console.error(`Error syncing command '${apiCmd.name}' [HTTP ${res.status}]: ${JSON.stringify(res.data)}`)
|
|
277
|
+
if (retries < maxRetries) {
|
|
278
|
+
retries++
|
|
279
|
+
const backoffTime = 1000 * retries
|
|
280
|
+
console.log(`Retrying (${retries}/${maxRetries}) in ${backoffTime}ms...`)
|
|
281
|
+
await new Promise(resolve => setTimeout(resolve, backoffTime))
|
|
282
|
+
continue
|
|
283
|
+
} else {
|
|
284
|
+
console.error(`Max retries reached for command '${apiCmd.name}'. Skipping.`)
|
|
285
|
+
break
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const remaining = res.headers['x-ratelimit-remaining']
|
|
290
|
+
const resetAfter = res.headers['x-ratelimit-reset-after']
|
|
291
|
+
if (remaining !== undefined && parseInt(remaining, 10) === 0 && resetAfter) {
|
|
292
|
+
const waitTime = parseFloat(resetAfter) * 1000
|
|
293
|
+
console.log(`Rate limit bucket depleted. Waiting ${waitTime}ms before next command...`)
|
|
294
|
+
await new Promise(resolve => setTimeout(resolve, waitTime))
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
break
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
package/src/core/files/config.ts
CHANGED
|
@@ -16,9 +16,15 @@ type HookFor<T, Context = never> = null | ((value: T, context: Context) => Promi
|
|
|
16
16
|
type TransformHookFor<T, Context = never> = null | ((value: T, context: Context) => T)
|
|
17
17
|
|
|
18
18
|
export type CordoConfig = {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
19
|
+
paths: {
|
|
20
|
+
root: string
|
|
21
|
+
routes: string
|
|
22
|
+
lockfile: string
|
|
23
|
+
types: string | null
|
|
24
|
+
}
|
|
25
|
+
defaults: {
|
|
26
|
+
commandRoutePrefix?: string
|
|
27
|
+
}
|
|
22
28
|
upstream: {
|
|
23
29
|
baseUrl: string
|
|
24
30
|
/** if an interaction was not replied to within X millis, cordo will send the appropriate defer/ack response. Set to 0 to disable */
|
|
@@ -28,9 +34,6 @@ export type CordoConfig = {
|
|
|
28
34
|
id: string
|
|
29
35
|
publicKey: string
|
|
30
36
|
}
|
|
31
|
-
paths: {
|
|
32
|
-
routes: string
|
|
33
|
-
}
|
|
34
37
|
/** hooks allow you to process certain data at certain points during cordo's internals. you can always return null to stop the flow of data at that point. */
|
|
35
38
|
hooks: {
|
|
36
39
|
/** gets called before cordo does anything with the interaction */
|
|
@@ -77,9 +80,15 @@ export function defineCordoConfig(conf: PartialDeep<CordoConfig> = {}): PartialD
|
|
|
77
80
|
export namespace ConfigInternals {
|
|
78
81
|
|
|
79
82
|
const defaultConfig: CordoConfig = {
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
+
paths: {
|
|
84
|
+
root: '.',
|
|
85
|
+
routes: './routes',
|
|
86
|
+
lockfile: './cordo.lock',
|
|
87
|
+
types: null,
|
|
88
|
+
},
|
|
89
|
+
defaults: {
|
|
90
|
+
commandRoutePrefix: 'command'
|
|
91
|
+
},
|
|
83
92
|
upstream: {
|
|
84
93
|
baseUrl: 'https://discord.com/api/v10',
|
|
85
94
|
autoDeferMs: 50
|
|
@@ -88,9 +97,6 @@ export namespace ConfigInternals {
|
|
|
88
97
|
id: '',
|
|
89
98
|
publicKey: ''
|
|
90
99
|
},
|
|
91
|
-
paths: {
|
|
92
|
-
routes: './routes'
|
|
93
|
-
},
|
|
94
100
|
hooks: {
|
|
95
101
|
onRawInteraction: null,
|
|
96
102
|
onBeforeHandle: null,
|
|
@@ -147,13 +153,14 @@ export namespace ConfigInternals {
|
|
|
147
153
|
export async function readAndParseConfig(): Promise<ParsedCordoConfig> {
|
|
148
154
|
const config = await readConfig()
|
|
149
155
|
|
|
150
|
-
config.
|
|
151
|
-
|
|
152
|
-
config.
|
|
153
|
-
|
|
156
|
+
config.paths.root = resolveRelativePath(config.paths.root)
|
|
157
|
+
|
|
158
|
+
config.paths.lockfile = resolveRelativePath(config.paths.lockfile, config.paths.root)
|
|
159
|
+
config.paths.types = config.paths.types
|
|
160
|
+
? resolveRelativePath(config.paths.types, config.paths.root)
|
|
154
161
|
: null
|
|
155
162
|
|
|
156
|
-
config.paths.routes = resolveRelativePath(config.paths.routes, config.
|
|
163
|
+
config.paths.routes = resolveRelativePath(config.paths.routes, config.paths.root)
|
|
157
164
|
|
|
158
165
|
return {
|
|
159
166
|
...config,
|
|
@@ -2,6 +2,7 @@ import { promises as fs } from 'node:fs'
|
|
|
2
2
|
import { LibIds } from '../../lib/ids'
|
|
3
3
|
import type { RouteInternals } from './route'
|
|
4
4
|
import type { ErrorBoundaryInternals } from './error-boundary'
|
|
5
|
+
import type { CordoCommand } from './command'
|
|
5
6
|
|
|
6
7
|
|
|
7
8
|
export namespace LockfileInternals {
|
|
@@ -17,6 +18,7 @@ export namespace LockfileInternals {
|
|
|
17
18
|
$runtime: {
|
|
18
19
|
routeImpls: Map<string, RouteInternals.ParsedRoute>
|
|
19
20
|
errorBoundaries: Array<ErrorBoundaryInternals.ParsedBoundary>
|
|
21
|
+
registeredCommands: Map<string, CordoCommand>
|
|
20
22
|
}
|
|
21
23
|
}
|
|
22
24
|
|
|
@@ -35,7 +37,8 @@ export namespace LockfileInternals {
|
|
|
35
37
|
lut: [],
|
|
36
38
|
$runtime: {
|
|
37
39
|
routeImpls: new Map(),
|
|
38
|
-
errorBoundaries: []
|
|
40
|
+
errorBoundaries: [],
|
|
41
|
+
registeredCommands: new Map()
|
|
39
42
|
}
|
|
40
43
|
}
|
|
41
44
|
}
|
package/src/core/files/route.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { APIEntitlement, APIInteractionGuildMember, APIMessage, APIPartialChannel, APIPartialGuild, APIUser } from "discord-api-types/v10"
|
|
2
2
|
import type { CordoInteraction } from "../interaction"
|
|
3
|
-
import { RouteAssumptionFailedError } from "../../errors"
|
|
4
3
|
import type { goto, run } from "../../functions"
|
|
5
4
|
import type { CordoComponent } from "../../components/component"
|
|
6
5
|
import type { CordoModifier } from "../../components/modifier"
|
|
6
|
+
import { RouteAssumptionFailedError } from "../../errors"
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
const CordoRouteSymbol = Symbol.for('CordoRoute')
|
|
@@ -117,7 +117,7 @@ export type RouteRequest = {
|
|
|
117
117
|
rawEntitlements: APIEntitlement[]
|
|
118
118
|
|
|
119
119
|
/** acknowledge the request but only provide a reply later */
|
|
120
|
-
ack: () => void
|
|
120
|
+
ack: (opts?: { private?: boolean }) => void
|
|
121
121
|
/** render the provided components */
|
|
122
122
|
render: (...response: RouteResponse) => void
|
|
123
123
|
/** open a modal with the provided components */
|
package/src/core/gateway.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ApplicationCommandOptionType, ApplicationCommandType, ComponentType, InteractionResponseType, InteractionType, type
|
|
1
|
+
import { ApplicationCommandOptionType, ApplicationCommandType, ComponentType, InteractionResponseType, InteractionType, type APIApplicationCommand, type APIInteraction } from "discord-api-types/v10"
|
|
2
2
|
import type { Method } from "axios"
|
|
3
3
|
import axios from "axios"
|
|
4
4
|
import { FunctCompiler } from "../functions/compiler"
|
|
@@ -72,7 +72,7 @@ export namespace CordoGateway {
|
|
|
72
72
|
}
|
|
73
73
|
|
|
74
74
|
/** if the payload is null the interaction will be defered if not done already */
|
|
75
|
-
export async function respondTo(i: CordoInteraction, payload: Record<string, any> | null) {
|
|
75
|
+
export async function respondTo(i: CordoInteraction, payload: Record<string, any> | null, opts?: { ephemeral?: boolean }) {
|
|
76
76
|
payload = await Hooks.callHook('onBeforeRespond', payload, { interaction: i })
|
|
77
77
|
|
|
78
78
|
const internals = InteractionInternals.get(i)
|
|
@@ -83,7 +83,7 @@ export namespace CordoGateway {
|
|
|
83
83
|
return internals.httpCallback(payload)
|
|
84
84
|
|
|
85
85
|
if (i.type === InteractionType.ApplicationCommand)
|
|
86
|
-
return internals.httpCallback({ type: InteractionResponseType.DeferredChannelMessageWithSource })
|
|
86
|
+
return internals.httpCallback({ type: InteractionResponseType.DeferredChannelMessageWithSource, data: { flags: opts?.ephemeral ? 1 << 6 : 0 } })
|
|
87
87
|
|
|
88
88
|
if (i.type === InteractionType.MessageComponent)
|
|
89
89
|
return internals.httpCallback({ type: InteractionResponseType.DeferredMessageUpdate })
|
|
@@ -96,7 +96,7 @@ export namespace CordoGateway {
|
|
|
96
96
|
return apiRequest('post', `/interactions/${i.id}/${i.token}/callback`, payload)
|
|
97
97
|
|
|
98
98
|
if (i.type === InteractionType.ApplicationCommand)
|
|
99
|
-
return apiRequest('post', `/interactions/${i.id}/${i.token}/callback`, { type: InteractionResponseType.DeferredChannelMessageWithSource })
|
|
99
|
+
return apiRequest('post', `/interactions/${i.id}/${i.token}/callback`, { type: InteractionResponseType.DeferredChannelMessageWithSource, data: { flags: opts?.ephemeral ? 1 << 6 : 0 } })
|
|
100
100
|
|
|
101
101
|
if (i.type === InteractionType.MessageComponent)
|
|
102
102
|
return apiRequest('post', `/interactions/${i.id}/${i.token}/callback`, { type: InteractionResponseType.DeferredMessageUpdate })
|
|
@@ -317,4 +317,13 @@ export namespace CordoGateway {
|
|
|
317
317
|
return true
|
|
318
318
|
}
|
|
319
319
|
|
|
320
|
+
export function upsertCommand(command: APIApplicationCommand, guild?: string) {
|
|
321
|
+
const config = CordoMagic.getConfig()
|
|
322
|
+
if (!config?.client.id)
|
|
323
|
+
throw new MissingContextError('Could not upsert command, no client id found in config context.')
|
|
324
|
+
|
|
325
|
+
const endpoint = guild ? `/applications/${config.client.id}/guilds/${guild}/commands` : `/applications/${config.client.id}/commands`
|
|
326
|
+
return apiRequest('post', endpoint, command)
|
|
327
|
+
}
|
|
328
|
+
|
|
320
329
|
}
|
package/src/core/index.ts
CHANGED
|
@@ -7,10 +7,12 @@ import { CordoGateway } from './gateway'
|
|
|
7
7
|
import { RoutingFilesystem } from './routing/filesystem'
|
|
8
8
|
import { CordoMagic } from './magic'
|
|
9
9
|
import type { CordoInteraction } from './interaction'
|
|
10
|
+
import { CommandInternals } from './files/command'
|
|
10
11
|
|
|
11
12
|
export { type DynamicTypes } from './dynamic-types'
|
|
12
13
|
export { type CordoConfig, defineCordoConfig } from './files/config'
|
|
13
14
|
export { type CordoRoute, type RouteRequest, defineCordoRoute, assertCordoRequest } from './files/route'
|
|
15
|
+
export { type CordoCommand, defineCordoCommand } from './files/command'
|
|
14
16
|
export { type CordoErrorBoundary, defineCordoErrorBoundary } from './files/error-boundary'
|
|
15
17
|
export { type CordoInteraction } from './interaction'
|
|
16
18
|
|
|
@@ -23,10 +25,10 @@ async function mountCordo(configOverrides?: PartialDeep<CordoConfig>) {
|
|
|
23
25
|
const fileConfig = await ConfigInternals.readAndParseConfig()
|
|
24
26
|
config = configOverrides ? defu(configOverrides, fileConfig) as ParsedCordoConfig : fileConfig
|
|
25
27
|
|
|
26
|
-
lockfile = await LockfileInternals.readOrCreateLockfile(config.lockfile)
|
|
27
|
-
await RoutingFilesystem.readFsTreeAndSyncLockfile(config.paths.routes, lockfile)
|
|
28
|
+
lockfile = await LockfileInternals.readOrCreateLockfile(config.paths.lockfile)
|
|
29
|
+
await RoutingFilesystem.readFsTreeAndSyncLockfile(config.paths.routes, lockfile, config)
|
|
28
30
|
|
|
29
|
-
LockfileInternals.writeLockfile(config.lockfile, lockfile, config.
|
|
31
|
+
LockfileInternals.writeLockfile(config.paths.lockfile, lockfile, config.paths.types)
|
|
30
32
|
}
|
|
31
33
|
|
|
32
34
|
function triggerInteraction(interaction: APIInteraction, opts: {
|
|
@@ -64,7 +66,7 @@ function registerConstants(constants: readonly string[]) {
|
|
|
64
66
|
}
|
|
65
67
|
|
|
66
68
|
if (changesMade)
|
|
67
|
-
return LockfileInternals.writeLockfile(config!.lockfile, lockfile!, config!.
|
|
69
|
+
return LockfileInternals.writeLockfile(config!.paths.lockfile, lockfile!, config!.paths.types)
|
|
68
70
|
else
|
|
69
71
|
return Promise.resolve()
|
|
70
72
|
}
|
|
@@ -76,6 +78,7 @@ export const Cordo = {
|
|
|
76
78
|
registerConstants,
|
|
77
79
|
triggerInteraction,
|
|
78
80
|
respondToRawInteraction: CordoGateway.respondTo,
|
|
81
|
+
syncCommands: (opts?: { maxRetries?: number }) => CommandInternals.syncCommands(lockfile!.$runtime.registeredCommands, undefined, opts)
|
|
79
82
|
}
|
|
80
83
|
Object.freeze(Cordo)
|
|
81
84
|
|
|
@@ -4,20 +4,24 @@ import { ErrorBoundaryInternals, type CordoErrorBoundary } from "../files/error-
|
|
|
4
4
|
import { RouteInternals, type CordoRoute } from "../files/route"
|
|
5
5
|
import { LockfileInternals } from "../files/lockfile"
|
|
6
6
|
import { LibIds } from "../../lib/ids"
|
|
7
|
+
import { CommandInternals, type CordoCommand } from "../files/command"
|
|
8
|
+
import type { ParsedCordoConfig } from "../files/config"
|
|
7
9
|
|
|
8
10
|
|
|
9
11
|
export namespace RoutingFilesystem {
|
|
10
12
|
|
|
11
|
-
export const supportedExtensions = [ 'js', 'ts' ]
|
|
13
|
+
export const supportedExtensions = [ 'js', 'ts', 'mjs', 'mts' ]
|
|
12
14
|
|
|
13
15
|
export type ParsedFsTree = {
|
|
14
16
|
routes: Array<{ path: string[]; route: CordoRoute }>
|
|
17
|
+
commands: Array<{ path: string[]; command: CordoCommand }>
|
|
15
18
|
errorBounds: Array<{ path: string[]; boundary: CordoErrorBoundary }>
|
|
16
19
|
}
|
|
17
20
|
|
|
18
|
-
export async function readFsTree(treeRoot: string, maxDepth = 20): Promise<ParsedFsTree> {
|
|
21
|
+
export async function readFsTree(treeRoot: string, config: ParsedCordoConfig, maxDepth = 20): Promise<ParsedFsTree> {
|
|
19
22
|
const out: ParsedFsTree = {
|
|
20
23
|
routes: [],
|
|
24
|
+
commands: [],
|
|
21
25
|
errorBounds: []
|
|
22
26
|
}
|
|
23
27
|
|
|
@@ -27,7 +31,7 @@ export namespace RoutingFilesystem {
|
|
|
27
31
|
const dir = await fs.opendir(treeRoot)
|
|
28
32
|
for await (const item of dir) {
|
|
29
33
|
if (item.isDirectory()) {
|
|
30
|
-
const subTree = await readFsTree(join(treeRoot, item.name), maxDepth - 1)
|
|
34
|
+
const subTree = await readFsTree(join(treeRoot, item.name), config, maxDepth - 1)
|
|
31
35
|
for (const child of subTree.routes) {
|
|
32
36
|
out.routes.push({
|
|
33
37
|
path: [ item.name, ...child.path ],
|
|
@@ -44,6 +48,25 @@ export namespace RoutingFilesystem {
|
|
|
44
48
|
if (!supportedExtensions.some(ext => item.name.endsWith(`.${ext}`)))
|
|
45
49
|
continue
|
|
46
50
|
|
|
51
|
+
const command = await CommandInternals.readCommand(join(treeRoot, item.name))
|
|
52
|
+
if (command) {
|
|
53
|
+
if (!treeRoot.startsWith(config.defaults.commandRoutePrefix ?? 'command'))
|
|
54
|
+
console.warn(`File ${join(treeRoot, item.name)} defined a command but is not in the command route prefix folder (${config.defaults.commandRoutePrefix ?? 'command'}). The command will probably not trigger the configured route when run.`)
|
|
55
|
+
|
|
56
|
+
out.commands.push({
|
|
57
|
+
path: [ item.name ],
|
|
58
|
+
command
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
if (typeof command.route !== 'string') {
|
|
62
|
+
out.routes.push({
|
|
63
|
+
path: [ item.name ],
|
|
64
|
+
route: command.route
|
|
65
|
+
})
|
|
66
|
+
}
|
|
67
|
+
continue
|
|
68
|
+
}
|
|
69
|
+
|
|
47
70
|
const route = await RouteInternals.readRoute(join(treeRoot, item.name))
|
|
48
71
|
if (route) {
|
|
49
72
|
out.routes.push({
|
|
@@ -67,8 +90,8 @@ export namespace RoutingFilesystem {
|
|
|
67
90
|
return out
|
|
68
91
|
}
|
|
69
92
|
|
|
70
|
-
export async function readFsTreeAndSyncLockfile(treeRoot: string, lockfile: LockfileInternals.ParsedLockfile): Promise<RouteInternals.ParsedRoute[]> {
|
|
71
|
-
const files = await readFsTree(treeRoot)
|
|
93
|
+
export async function readFsTreeAndSyncLockfile(treeRoot: string, lockfile: LockfileInternals.ParsedLockfile, config: ParsedCordoConfig): Promise<RouteInternals.ParsedRoute[]> {
|
|
94
|
+
const files = await readFsTree(treeRoot, config)
|
|
72
95
|
|
|
73
96
|
const out: RouteInternals.ParsedRoute[] = []
|
|
74
97
|
for (const file of files.routes) {
|
|
@@ -109,6 +132,16 @@ export namespace RoutingFilesystem {
|
|
|
109
132
|
})
|
|
110
133
|
}
|
|
111
134
|
|
|
135
|
+
const commandRoutePrefix = config?.defaults.commandRoutePrefix ?? 'command'
|
|
136
|
+
for (const file of files.commands) {
|
|
137
|
+
const filePath = file.path.join('/').startsWith(`${commandRoutePrefix}/`)
|
|
138
|
+
? file.path.join('/').slice(commandRoutePrefix.length + 1)
|
|
139
|
+
: file.path.join('/')
|
|
140
|
+
|
|
141
|
+
lockfile.$runtime.registeredCommands.set(filePath, file.command)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
|
|
112
145
|
return out
|
|
113
146
|
}
|
|
114
147
|
|
|
@@ -142,7 +142,7 @@ export namespace RoutingResolve {
|
|
|
142
142
|
: type === 'slash'
|
|
143
143
|
? command.replaceAll(' ', '/').toLowerCase() // slash commands: subcommands become subfolders
|
|
144
144
|
: command.replaceAll(' ', '-').replace(/[^\w-]/g, '').toLowerCase() // message/user commands: just sanitize
|
|
145
|
-
const routePath =
|
|
145
|
+
const routePath = `${CordoMagic.getConfig()?.defaults.commandRoutePrefix ?? 'command'}/${fileName}`
|
|
146
146
|
return {
|
|
147
147
|
route: getRouteFromPath(routePath, false),
|
|
148
148
|
path: routePath
|
|
@@ -145,8 +145,8 @@ export namespace RoutingRespond {
|
|
|
145
145
|
has: (key: string) => key in interaction.locals
|
|
146
146
|
},
|
|
147
147
|
|
|
148
|
-
ack: opts.disableRendering ? noOp : () => {
|
|
149
|
-
CordoGateway.respondTo(interaction, null)
|
|
148
|
+
ack: opts.disableRendering ? noOp : (ackOpts?: { private?: boolean }) => {
|
|
149
|
+
CordoGateway.respondTo(interaction, null, { ephemeral: ackOpts?.private })
|
|
150
150
|
},
|
|
151
151
|
render: opts.disableRendering ? noOp : (...response) => {
|
|
152
152
|
const rendered = renderRouteResponse(response, interaction, opts)
|
package/src/functions/index.ts
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
|
+
import { FunctCompiler } from './compiler'
|
|
2
|
+
|
|
1
3
|
export { goto } from './impl/goto'
|
|
2
4
|
export { run } from './impl/run'
|
|
3
5
|
export { value } from './impl/value'
|
|
4
6
|
|
|
5
7
|
export type { CordoFunct, CordoFunctRun } from './funct'
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
export namespace Extend {
|
|
11
|
+
export const toCustomId: typeof FunctCompiler.toCustomId = (...args) => FunctCompiler.toCustomId(...args)
|
|
12
|
+
export const parseCustomId: typeof FunctCompiler.parseCustomId = (...args) => FunctCompiler.parseCustomId(...args)
|
|
13
|
+
}
|
package/src/lib/constants.ts
CHANGED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
|
|
2
|
+
export type DiscordLocale = 'id'
|
|
3
|
+
| 'da'
|
|
4
|
+
| 'de'
|
|
5
|
+
| 'en-GB'
|
|
6
|
+
| 'en-US'
|
|
7
|
+
| 'es-ES'
|
|
8
|
+
| 'es-419'
|
|
9
|
+
| 'fr'
|
|
10
|
+
| 'hr'
|
|
11
|
+
| 'it'
|
|
12
|
+
| 'lt'
|
|
13
|
+
| 'hu'
|
|
14
|
+
| 'nl'
|
|
15
|
+
| 'no'
|
|
16
|
+
| 'pl'
|
|
17
|
+
| 'pt-BR'
|
|
18
|
+
| 'ro'
|
|
19
|
+
| 'fi'
|
|
20
|
+
| 'sv-SE'
|
|
21
|
+
| 'vi'
|
|
22
|
+
| 'tr'
|
|
23
|
+
| 'cs'
|
|
24
|
+
| 'el'
|
|
25
|
+
| 'bg'
|
|
26
|
+
| 'ru'
|
|
27
|
+
| 'uk'
|
|
28
|
+
| 'hi'
|
|
29
|
+
| 'th'
|
|
30
|
+
| 'zh-CN'
|
|
31
|
+
| 'ja'
|
|
32
|
+
| 'zh-TW'
|
|
33
|
+
| 'ko'
|
|
34
|
+
|
|
35
|
+
export type LocalizedString = Record<DiscordLocale, string> & {
|
|
36
|
+
default: string
|
|
37
|
+
}
|