cordo 2.20.1 → 2.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/package.json +1 -1
  2. package/src/components/builtin/button.ts +11 -7
  3. package/src/components/builtin/checkbox-group.ts +55 -33
  4. package/src/components/builtin/container.ts +37 -7
  5. package/src/components/builtin/file-upload.ts +50 -24
  6. package/src/components/builtin/gallery.ts +12 -4
  7. package/src/components/builtin/image.ts +3 -1
  8. package/src/components/builtin/link-button.ts +9 -7
  9. package/src/components/builtin/menu-item.ts +107 -0
  10. package/src/components/builtin/menu-link.ts +69 -0
  11. package/src/components/builtin/modal.ts +12 -9
  12. package/src/components/builtin/overflow-menu.ts +56 -0
  13. package/src/components/builtin/radio-group.ts +21 -17
  14. package/src/components/builtin/row.ts +41 -9
  15. package/src/components/builtin/section.ts +24 -6
  16. package/src/components/builtin/select-string.ts +59 -32
  17. package/src/components/builtin/text-input.ts +33 -24
  18. package/src/components/builtin/text.ts +3 -1
  19. package/src/components/component.ts +23 -5
  20. package/src/components/index.ts +7 -0
  21. package/src/components/limits.ts +156 -0
  22. package/src/components/mods/debug-id-to-label.ts +1 -1
  23. package/src/components/mods/debug-print.ts +2 -1
  24. package/src/components/mods/disable-all-components.ts +17 -5
  25. package/src/core/files/command.ts +9 -8
  26. package/src/core/files/config.ts +39 -7
  27. package/src/core/files/route.ts +12 -4
  28. package/src/core/gateway.ts +2 -1
  29. package/src/core/hooks.ts +2 -1
  30. package/src/core/index.ts +2 -1
  31. package/src/core/routing/filesystem.ts +2 -1
  32. package/src/core/routing/resolve.ts +3 -2
  33. package/src/core/routing/respond.ts +8 -5
  34. package/src/errors/handle.ts +3 -2
  35. package/src/functions/compiler.ts +25 -3
  36. package/src/lib/constants.ts +35 -2
  37. package/src/lib/limits.ts +98 -0
  38. package/src/lib/logger.ts +28 -0
  39. package/src/plugin/djs.ts +2 -1
  40. package/tsconfig.json +1 -4
  41. package/src/lib/ids.test.ts +0 -47
@@ -3,6 +3,9 @@ import { Hooks } from '../../core/hooks'
3
3
  import { FunctCompiler } from '../../functions/compiler'
4
4
  import { value } from '../../functions'
5
5
  import { CordoMagic } from '../../core/magic'
6
+ import { MaxLengthConstants } from '../../lib/constants'
7
+ import { LibLimits } from '../../lib/limits'
8
+ import { LibLogger } from '../../lib/logger'
6
9
 
7
10
 
8
11
  export function textInput() {
@@ -20,17 +23,17 @@ export function textInput() {
20
23
  function getPlaceholder() {
21
24
  if (!placeholderVal)
22
25
  return undefined
23
- return Hooks.callHook(
26
+ return LibLimits.text(Hooks.callHook(
24
27
  'transformUserFacingText',
25
28
  placeholderVal,
26
29
  { component: 'TextInput', position: 'placeholder' }
27
- )
30
+ ), MaxLengthConstants.TEXT_INPUT_PLACEHOLDER, 'A text input placeholder')
28
31
  }
29
32
 
30
33
  function getLabel() {
31
34
  if (!labelVal) {
32
35
  if (!CordoMagic.getConfig()?.omitWarnings.includes('placeholderTextAppearance'))
33
- console.warn('A text input was rendered without a label provided. Cordo will use a placeholder label.')
36
+ LibLogger.warn('A text input was rendered without a label provided. Cordo will use a placeholder label.')
34
37
  return 'Your Response'
35
38
  }
36
39
  return Hooks.callHook(
@@ -54,29 +57,39 @@ export function textInput() {
54
57
  /** Will override cordo's custom_id generation. Not compatible with as() ids */
55
58
  overrideCustomId(customId: string) {
56
59
  if (ref && !CordoMagic.getConfig()?.omitWarnings.includes('customIdOverride'))
57
- console.warn('You are overriding the custom_id of a text input that has an as() id. Your as() id will be overridden.')
60
+ LibLogger.warn('You are overriding the custom_id of a text input that has an as() id. Your as() id will be overridden.')
58
61
  overrideCustomIdVal = customId
59
62
  return out
60
63
  }
61
64
  }
62
65
 
63
66
  const out = {
64
- ...createComponent('TextInput', () => ({
65
- type: ComponentType.TextInput,
66
- placeholder: getPlaceholder(),
67
- min_length: minLength,
68
- max_length: maxLength,
69
- required: requiredVal,
70
- style: sizeVal ?? 1,
71
- value: currentVal,
72
- custom_id: overrideCustomIdVal ?? FunctCompiler.toCustomId(ref ? [ value(ref) ] : []), // get a noop if no ref
73
- 'modal:label': getLabel(),
74
- 'modal:description': getDescription(),
75
- })),
67
+ ...createComponent('TextInput', ({ hirarchy }) => {
68
+ let min = minLength
69
+ if (min !== undefined && maxLength !== undefined && min > maxLength) {
70
+ LibLimits.warn('clampedValue', `min_length of a text input is ${min} but max_length is ${maxLength}. Cordo lowered min_length to ${maxLength}.`)
71
+ min = maxLength
72
+ }
73
+
74
+ return {
75
+ type: ComponentType.TextInput,
76
+ placeholder: getPlaceholder(),
77
+ min_length: min,
78
+ max_length: maxLength,
79
+ required: requiredVal,
80
+ style: sizeVal ?? 1,
81
+ value: LibLimits.text(currentVal, MaxLengthConstants.TEXT_INPUT_VALUE, 'The current value of a text input'),
82
+ custom_id: overrideCustomIdVal !== undefined
83
+ ? FunctCompiler.checkCustomIdOverride(overrideCustomIdVal)
84
+ : FunctCompiler.toCustomId(ref ? [ value(ref) ] : []), // get a noop if no ref
85
+ 'modal:label': hirarchy.includes('Modal') ? getLabel() : undefined,
86
+ 'modal:description': hirarchy.includes('Modal') ? getDescription() : undefined,
87
+ }
88
+ }),
76
89
 
77
90
  as: (id: string) => {
78
- if (overrideCustomIdVal && !CordoMagic.getConfig()?.omitWarnings.includes('customIdOverride'))
79
- console.warn('You are assigning an as() id to a text input that already has an overridden custom_id. Your provided id will be ignored.')
91
+ if (overrideCustomIdVal !== undefined && !CordoMagic.getConfig()?.omitWarnings.includes('customIdOverride'))
92
+ LibLogger.warn('You are assigning an as() id to a text input that already has an overridden custom_id. Your provided id will be ignored.')
80
93
  ref = id
81
94
  return out
82
95
  },
@@ -97,15 +110,11 @@ export function textInput() {
97
110
  return out
98
111
  },
99
112
  min: (num: number = 0) => {
100
- if (num < 0) num = 0
101
- if (num > 4000) num = 4000
102
- minLength = num
113
+ minLength = LibLimits.clamp(num, 0, MaxLengthConstants.TEXT_INPUT_VALUE, 'min_length of a text input')
103
114
  return out
104
115
  },
105
116
  max: (num: number = 4000) => {
106
- if (num < 1) num = 1
107
- if (num > 4000) num = 4000
108
- maxLength = num
117
+ maxLength = LibLimits.clamp(num, 1, MaxLengthConstants.TEXT_INPUT_VALUE, 'max_length of a text input')
109
118
  return out
110
119
  },
111
120
  required(required = true) {
@@ -1,5 +1,7 @@
1
1
  import { Hooks } from '../../core/hooks'
2
2
  import { ComponentType, createComponent } from '../component'
3
+ import { MaxLengthConstants } from '../../lib/constants'
4
+ import { LibLimits } from '../../lib/limits'
3
5
 
4
6
 
5
7
  export function text(...content: Array<string | { toString: () => string }>) {
@@ -22,7 +24,7 @@ export function text(...content: Array<string | { toString: () => string }>) {
22
24
  const out = {
23
25
  ...createComponent('TextDisplay', ({ attributes }) => ({
24
26
  type: ComponentType.TextDisplay,
25
- content: toString(attributes)
27
+ content: LibLimits.text(toString(attributes), MaxLengthConstants.TEXT_DISPLAY_CONTENT, 'A text')
26
28
  })),
27
29
 
28
30
  toString,
@@ -1,4 +1,5 @@
1
1
  import defu from "defu"
2
+ import { MaxLengthConstants } from "../lib/constants"
2
3
  import { row } from "./builtin/row"
3
4
  import { readModifier, type CordoModifier } from "./modifier"
4
5
  import type { AllowedComponents as ContainerAllowedComponents } from "./builtin/container"
@@ -28,6 +29,8 @@ export const ComponentType = {
28
29
  RadioGroup: 21,
29
30
  CheckboxGroup: 22,
30
31
  Checkbox: 23,
32
+ OverflowMenu: 25,
33
+ MenuActionItem: 26,
31
34
 
32
35
  Modal: -1, // This is a special type that is not used in the API, but for Cordo's internal use
33
36
  } as const
@@ -43,7 +46,8 @@ export type CordoComponent<Type extends StringComponentType = StringComponentTyp
43
46
  render: (meta: {
44
47
  hirarchy: Array<StringComponentType>
45
48
  attributes: Record<string, any>
46
- }) => Record<string, any> | null
49
+ /** may return a list of components if one cordo component has to be split into multiple discord components (e.g. a row with too many buttons) */
50
+ }) => Record<string, any> | Array<Record<string, any>> | null
47
51
  }
48
52
  visible: (value: boolean) => CordoComponent<Type>
49
53
  attributes: (attrs: Record<string, any>) => CordoComponent<Type>
@@ -89,12 +93,25 @@ export function isComponent(t: Record<string, any>): t is CordoComponent<StringC
89
93
  return !!t && CordoComponentSymbol in t
90
94
  }
91
95
 
96
+ /** renders a single component. Action rows with more than 5 buttons (or a select mixed with buttons) are split into multiple rows and thus return a list */
97
+ export function renderComponent(
98
+ c: CordoComponent<'ActionRow'>,
99
+ parent: StringComponentType | null,
100
+ hirarchy?: Array<StringComponentType>,
101
+ inheritAttributes?: Record<string, any>
102
+ ): Record<string, any> | Array<Record<string, any>> | null
103
+ export function renderComponent(
104
+ c: CordoComponent<StringComponentType> | CordoComponentPayload<StringComponentType>,
105
+ parent: StringComponentType | null,
106
+ hirarchy?: Array<StringComponentType>,
107
+ inheritAttributes?: Record<string, any>
108
+ ): Record<string, any> | null
92
109
  export function renderComponent(
93
110
  c: CordoComponent<StringComponentType> | CordoComponentPayload<StringComponentType>,
94
111
  parent: StringComponentType | null,
95
112
  hirarchy: Array<StringComponentType> = [],
96
113
  inheritAttributes: Record<string, any> = {}
97
- ) {
114
+ ): Record<string, any> | Array<Record<string, any>> | null {
98
115
  const extracted = CordoComponentSymbol in c ? readComponent(c) : c
99
116
  if (!extracted.visible)
100
117
  return null
@@ -144,7 +161,7 @@ export function renderComponentList(
144
161
  }
145
162
 
146
163
  if (parent !== 'ActionRow') {
147
- if (parsed.nativeName === 'Button') {
164
+ if (parsed.nativeName === 'Button' || parsed.nativeName === 'OverflowMenu') {
148
165
  rowBuilder.push(item)
149
166
  if (rowBuilder.length === 5) {
150
167
  pipeline.push(readComponent(row(...rowBuilder as any)))
@@ -183,14 +200,15 @@ export function renderComponentList(
183
200
  }
184
201
 
185
202
  let output = pipeline
186
- .map(c => renderComponent(c, parent, hirarchy, inheritAttributes))
203
+ .flatMap(c => renderComponent(c, parent, hirarchy, inheritAttributes))
187
204
  .filter(Boolean) as Record<string | any, any>[]
188
205
 
189
206
  // join adjacent text components
190
207
  let previousTextComponent: Record<string, any> | null = null
191
208
  output = output.filter((item) => {
192
209
  if (item.type === ComponentType.TextDisplay) {
193
- if (previousTextComponent) {
210
+ // only merge if the result stays within discord's limit
211
+ if (previousTextComponent && (previousTextComponent.content.length + 1 + item.content.length) <= MaxLengthConstants.TEXT_DISPLAY_CONTENT) {
194
212
  (previousTextComponent as any).content += '\n' + item.content
195
213
  return false
196
214
  } else {
@@ -8,6 +8,7 @@ import {
8
8
  renderComponent as _renderComponent,
9
9
  renderComponentList as _renderComponentList,
10
10
  } from './component'
11
+ import { ComponentLimits as _ComponentLimits } from './limits'
11
12
 
12
13
  export { button } from './builtin/button'
13
14
  export { checkboxGroup } from './builtin/checkbox-group'
@@ -18,7 +19,10 @@ export { fileUpload } from './builtin/file-upload'
18
19
  export { gallery } from './builtin/gallery'
19
20
  export { image } from './builtin/image'
20
21
  export { linkButton } from './builtin/link-button'
22
+ export { menuItem } from './builtin/menu-item'
23
+ export { menuLink } from './builtin/menu-link'
21
24
  export { modal } from './builtin/modal'
25
+ export { overflowMenu } from './builtin/overflow-menu'
22
26
  export { radioGroup } from './builtin/radio-group'
23
27
  export { row } from './builtin/row'
24
28
  export { section } from './builtin/section'
@@ -45,4 +49,7 @@ export namespace Extend {
45
49
  export const isComponent = _isComponent
46
50
  export const renderComponent = _renderComponent
47
51
  export const renderComponentList = _renderComponentList
52
+ /** apply these to your rendered components if you render messages yourself (e.g. in headless mode) */
53
+ export const enforceMessageLimits: typeof _ComponentLimits.enforceMessageLimits = (...args) => _ComponentLimits.enforceMessageLimits(...args)
54
+ export const enforceModalLimits: typeof _ComponentLimits.enforceModalLimits = (...args) => _ComponentLimits.enforceModalLimits(...args)
48
55
  }
@@ -0,0 +1,156 @@
1
+ import { FunctCompiler } from '../functions/compiler'
2
+ import { CountConstants, MaxLengthConstants } from '../lib/constants'
3
+ import { LibLimits } from '../lib/limits'
4
+ import { ComponentType } from './component'
5
+
6
+
7
+ type Rendered = Record<string, any>
8
+
9
+ /**
10
+ * Enforces limits that span the whole message or modal and thus cannot be checked by single components.
11
+ * Expects already rendered components, i.e. the output of renderComponentList.
12
+ */
13
+ export namespace ComponentLimits {
14
+
15
+ /** calls fn for every component in the tree, parents before their children */
16
+ function walk(list: Rendered[], fn: (c: Rendered) => void) {
17
+ for (const c of list) {
18
+ if (!c || typeof c !== 'object')
19
+ continue
20
+ fn(c)
21
+ walk(children(c), fn)
22
+ }
23
+ }
24
+
25
+ function children(c: Rendered): Rendered[] {
26
+ return [
27
+ ...(Array.isArray(c.components) ? c.components : []),
28
+ ...(c.accessory ? [ c.accessory ] : []),
29
+ ...(c.component ? [ c.component ] : []),
30
+ ...(Array.isArray(c.groups) ? c.groups.flatMap((g: Rendered) => g.components ?? []) : []),
31
+ ]
32
+ }
33
+
34
+ function countComponents(list: Rendered[]) {
35
+ let count = 0
36
+ walk(list, () => count++)
37
+ return count
38
+ }
39
+
40
+ /** custom_ids must be unique, duplicates are replaced with ids that do nothing */
41
+ function ensureUniqueCustomIds(list: Rendered[]) {
42
+ const seen = new Set<string>()
43
+ walk(list, (c) => {
44
+ if (typeof c.custom_id !== 'string')
45
+ return
46
+ if (seen.has(c.custom_id)) {
47
+ LibLimits.warn('invalidCustomId', `The custom_id '${c.custom_id}' is used more than once, Discord requires them to be unique. The duplicate will do nothing when used.`)
48
+ c.custom_id = FunctCompiler.toCustomId([])
49
+ }
50
+ seen.add(c.custom_id)
51
+ })
52
+ }
53
+
54
+ /** all text displays together may hold 4000 characters. Text after that is cut off, empty texts are removed */
55
+ function limitTotalText(list: Rendered[]) {
56
+ let total = 0
57
+ walk(list, (c) => {
58
+ if (c.type === ComponentType.TextDisplay)
59
+ total += c.content?.length ?? 0
60
+ })
61
+ if (total <= CountConstants.TOTAL_TEXT_LENGTH)
62
+ return list
63
+
64
+ LibLimits.warn('truncatedText', `All texts together are ${total} characters long, Discord allows ${CountConstants.TOTAL_TEXT_LENGTH}. Cordo cut off the text at the end.`)
65
+ let left = CountConstants.TOTAL_TEXT_LENGTH
66
+ walk(list, (c) => {
67
+ if (c.type !== ComponentType.TextDisplay)
68
+ return
69
+ c.content = (c.content ?? '').slice(0, left)
70
+ left -= c.content.length
71
+ })
72
+ return prune(list, { left: Infinity })
73
+ }
74
+
75
+ /**
76
+ * Keeps components in order until the budget runs out, then drops the rest.
77
+ * Also removes components that became invalid by losing their children (empty rows, sections without text, ...).
78
+ */
79
+ function prune(list: Rendered[], budget: { left: number }): Rendered[] {
80
+ const out: Rendered[] = []
81
+
82
+ for (const c of list) {
83
+ if (!c || typeof c !== 'object')
84
+ continue
85
+ if (c.type === ComponentType.TextDisplay && !c.content)
86
+ continue
87
+ if (budget.left <= 0)
88
+ continue
89
+
90
+ if (c.type === ComponentType.Section) {
91
+ // the section itself is counted last, so if only its text fits it can still be shown as a plain text
92
+ const before = budget.left
93
+ const texts = prune(c.components ?? [], budget)
94
+ if (!texts.length)
95
+ continue
96
+ const [ accessory ] = prune([ c.accessory ], budget)
97
+ if (accessory && budget.left > 0) {
98
+ budget.left--
99
+ out.push({ ...c, components: texts, accessory })
100
+ continue
101
+ }
102
+ budget.left = before - 1
103
+ out.push({
104
+ type: ComponentType.TextDisplay,
105
+ content: texts.map((t: Rendered) => t.content).join('\n').slice(0, MaxLengthConstants.TEXT_DISPLAY_CONTENT)
106
+ })
107
+ continue
108
+ }
109
+
110
+ budget.left--
111
+
112
+ if (c.type === ComponentType.ActionRow || c.type === ComponentType.Container) {
113
+ c.components = prune(c.components ?? [], budget)
114
+ if (!c.components.length) {
115
+ budget.left++
116
+ continue
117
+ }
118
+ } else if (c.type === ComponentType.OverflowMenu) {
119
+ c.groups = (c.groups ?? [])
120
+ .map((g: Rendered) => ({ ...g, components: prune(g.components ?? [], budget) }))
121
+ .filter((g: Rendered) => g.components.length > 0)
122
+ if (!c.groups.length) {
123
+ budget.left++
124
+ continue
125
+ }
126
+ }
127
+
128
+ out.push(c)
129
+ }
130
+
131
+ return out
132
+ }
133
+
134
+ /** keeps a rendered message within Discord's limits for the whole message */
135
+ export function enforceMessageLimits(components: Rendered[]): Rendered[] {
136
+ ensureUniqueCustomIds(components)
137
+ let out = limitTotalText(components)
138
+
139
+ const count = countComponents(out)
140
+ if (count > CountConstants.MESSAGE_COMPONENTS)
141
+ LibLimits.warn('truncatedList', `The message has ${count} components, Discord allows ${CountConstants.MESSAGE_COMPONENTS}. Cordo left out the components at the end.`)
142
+ out = prune(out, { left: CountConstants.MESSAGE_COMPONENTS })
143
+
144
+ return out
145
+ }
146
+
147
+ /** keeps a rendered modal's components within Discord's limits for the whole modal */
148
+ export function enforceModalLimits(components: Rendered[]): Rendered[] {
149
+ ensureUniqueCustomIds(components)
150
+ const out = LibLimits.list(limitTotalText(components), CountConstants.MODAL_COMPONENTS_MAX, 'A modal')
151
+ if (out.length < CountConstants.MODAL_COMPONENTS_MIN)
152
+ LibLimits.warn('invalidComponent', `A modal needs at least ${CountConstants.MODAL_COMPONENTS_MIN} component. Discord will reject it.`)
153
+ return out
154
+ }
155
+
156
+ }
@@ -6,7 +6,7 @@ function searchForButton(c: any): any {
6
6
  if (!c) return c
7
7
  if (Array.isArray(c)) return c.map(searchForButton)
8
8
  if (typeof c !== 'object') return c
9
- if (c.type === ComponentType.Button && 'custom_id' in c) {
9
+ if ((c.type === ComponentType.Button || c.type === ComponentType.MenuActionItem) && 'custom_id' in c) {
10
10
  c.label = c.custom_id
11
11
  return c
12
12
  }
@@ -1,4 +1,5 @@
1
1
  import { createModifier } from "../modifier"
2
+ import { LibLogger } from "../../lib/logger"
2
3
 
3
4
 
4
5
  export function debugPrint() {
@@ -6,7 +7,7 @@ export function debugPrint() {
6
7
  name: 'debug-print',
7
8
  hooks: {
8
9
  afterRender: (c) => {
9
- console.log(JSON.stringify(c, null, 2))
10
+ LibLogger.info(JSON.stringify(c, null, 2))
10
11
  return c
11
12
  }
12
13
  }
@@ -1,9 +1,11 @@
1
1
  import { ComponentType } from "../component"
2
2
  import { createModifier } from "../modifier"
3
+ import { LibLimits } from "../../lib/limits"
3
4
 
4
5
 
5
6
  const disableableComponents = [
6
7
  ComponentType.Button,
8
+ ComponentType.MenuActionItem,
7
9
  ComponentType.StringSelect,
8
10
  ComponentType.UserSelect,
9
11
  ComponentType.RoleSelect,
@@ -11,16 +13,22 @@ const disableableComponents = [
11
13
  ComponentType.ChannelSelect
12
14
  ]
13
15
 
14
- function iterateComponents(c: any): any {
16
+ /** returns whether components inside a modal were skipped */
17
+ function iterateComponents(c: any, skipped = { modal: false }): any {
15
18
  if (!c) return c
16
- if (Array.isArray(c)) return c.map(iterateComponents)
19
+ if (Array.isArray(c)) return c.map(item => iterateComponents(item, skipped))
17
20
  if (typeof c !== 'object') return c
21
+ if (c.type === ComponentType.Label) {
22
+ // labels only exist in modals and discord does not allow disabling components in modals
23
+ skipped.modal = true
24
+ return c
25
+ }
18
26
  if (disableableComponents.includes(c.type)) {
19
27
  c.disabled = true
20
28
  return c
21
29
  }
22
30
  for (const key of Object.keys(c))
23
- c[key] = iterateComponents(c[key])
31
+ c[key] = iterateComponents(c[key], skipped)
24
32
  return c
25
33
  }
26
34
 
@@ -29,8 +37,12 @@ export function disableAllComponents(disable = true) {
29
37
  name: 'disable-all-components',
30
38
  hooks: {
31
39
  afterRender: (c) => {
32
- if (disable)
33
- iterateComponents(c)
40
+ if (!disable)
41
+ return c
42
+ const skipped = { modal: false }
43
+ iterateComponents(c, skipped)
44
+ if (skipped.modal)
45
+ LibLimits.warn('unsupportedAttribute', 'disableAllComponents() was used in a modal, Discord does not allow disabling components there. Cordo left them enabled.')
34
46
  return c
35
47
  }
36
48
  }
@@ -6,6 +6,7 @@ import { CordoGateway } from '../gateway'
6
6
  import { RoutingResolve } from '../routing/resolve'
7
7
  import { CordoMagic } from '../magic'
8
8
  import type { CordoInteraction } from '../interaction'
9
+ import { LibLogger } from '../../lib/logger'
9
10
  import { LockfileInternals } from './lockfile'
10
11
  import type { CordoRoute } from './route'
11
12
 
@@ -193,7 +194,7 @@ export namespace CommandInternals {
193
194
 
194
195
  export async function syncCommands(commands: Map<string, CordoCommand> | undefined, guild?: string, options?: { maxRetries?: number }) {
195
196
  if (!commands || commands.size === 0) {
196
- console.warn('No commands to sync. Is cordo initialized and commands defined?')
197
+ LibLogger.warn('No commands to sync. Is cordo initialized and commands defined?')
197
198
  return
198
199
  }
199
200
 
@@ -234,7 +235,7 @@ export namespace CommandInternals {
234
235
  if (commandTypeStr === 'slash' || commandTypeStr === 'message' || commandTypeStr === 'user') {
235
236
  const expectedRoute = RoutingResolve.getRouteForCommand(name, commandTypeStr as any).path.split('/').pop()
236
237
  if (expectedRoute !== rootName) {
237
- console.error(`Command name '${name}' resolves to route '${expectedRoute}' which does not match actual route '${rootName}'. Using route name instead.`)
238
+ LibLogger.error(`Command name '${name}' resolves to route '${expectedRoute}' which does not match actual route '${rootName}'. Using route name instead.`)
238
239
  name = rootName
239
240
  nameLocalizations = undefined
240
241
  }
@@ -285,7 +286,7 @@ export namespace CommandInternals {
285
286
  if (CordoMagic.globalLockfile && CordoMagic.globalLockfile.reg.commandSyncHash === hash)
286
287
  return
287
288
 
288
- console.log(`[Cordo.syncCommands] Syncing ${apiCommands.length} command(s) to Discord...`)
289
+ LibLogger.info(`[Cordo.syncCommands] Syncing ${apiCommands.length} command(s) to Discord...`)
289
290
 
290
291
  let retries = 0
291
292
 
@@ -295,21 +296,21 @@ export namespace CommandInternals {
295
296
  if (res.status === 429) {
296
297
  const retryAfter = res.headers.get('retry-after') || res.data?.retry_after
297
298
  const waitTime = retryAfter ? parseFloat(retryAfter) * 1000 : 5000
298
- console.warn(`Rate limited (429) when bulk syncing commands. Waiting ${waitTime}ms...`)
299
+ LibLogger.warn(`Rate limited (429) when bulk syncing commands. Waiting ${waitTime}ms...`)
299
300
  await new Promise(resolve => setTimeout(resolve, waitTime))
300
301
  continue
301
302
  }
302
303
 
303
304
  if (res.status >= 400) {
304
- console.error(`Error bulk syncing commands [HTTP ${res.status}]: ${JSON.stringify(res.data)}`)
305
+ LibLogger.error(`Error bulk syncing commands [HTTP ${res.status}]: ${JSON.stringify(res.data)}`)
305
306
  if (retries < maxRetries) {
306
307
  retries++
307
308
  const backoffTime = 1000 * retries
308
- console.log(`Retrying (${retries}/${maxRetries}) in ${backoffTime}ms...`)
309
+ LibLogger.info(`Retrying (${retries}/${maxRetries}) in ${backoffTime}ms...`)
309
310
  await new Promise(resolve => setTimeout(resolve, backoffTime))
310
311
  continue
311
312
  } else {
312
- console.error('Max retries reached for bulk command sync. Skipping.')
313
+ LibLogger.error('Max retries reached for bulk command sync. Skipping.')
313
314
  break
314
315
  }
315
316
  }
@@ -319,7 +320,7 @@ export namespace CommandInternals {
319
320
  await LockfileInternals.writeLockfile(CordoMagic.globalConfig.paths.lockfile, CordoMagic.globalLockfile, CordoMagic.globalConfig.paths.types)
320
321
  }
321
322
 
322
- console.log(`[Cordo.syncCommands] Successfully synced ${apiCommands.length} command(s) to Discord.`)
323
+ LibLogger.info(`[Cordo.syncCommands] Successfully synced ${apiCommands.length} command(s) to Discord.`)
323
324
  break
324
325
  }
325
326
  }
@@ -7,6 +7,7 @@ import type { CordoInteraction } from '../interaction'
7
7
  import type { StringComponentType } from '../../components/component'
8
8
  import { parseFlags as runParseFlags, type FlagOpts as RunFlagOpts } from '../../functions/impl/run'
9
9
  import { parseFlags as gotoParseFlags, type FlagOpts as GotoFlagOpts } from '../../functions/impl/goto'
10
+ import type { CordoLogger } from '../../lib/logger'
10
11
  import type { RouteRequest } from './route'
11
12
 
12
13
 
@@ -80,6 +81,12 @@ export type CordoConfig = {
80
81
  goto: Required<GotoFlagOpts>
81
82
  }
82
83
 
84
+ /**
85
+ * Where cordo writes its logs. Defaults to console.
86
+ * Any logger with debug, info, warn and error methods works as is, e.g. consola, winston, pino, bunyan, log4js or loglevel.
87
+ */
88
+ logger: CordoLogger
89
+
83
90
  /** Cordo prints warnings for certain issues. You can omit specific warnings by adding them to this array. It is **not** recommended to blindly add warnings here without fully being aware what you are doing. */
84
91
  omitWarnings: Array<
85
92
  /** A component was assigned functs while also having a custom id override. This means the functs won't trigger */
@@ -87,7 +94,25 @@ export type CordoConfig = {
87
94
  /** A custom id had to be generated in headless mode. This means you rendered a component with functs assigned while in headless mode, resulting in the functs to not trigger. */
88
95
  'headlessCustomIdGeneration' |
89
96
  /** A an component attribute required by discord was not provided. Cordo filled in a default text for it to not break the component. */
90
- 'placeholderTextAppearance'
97
+ 'placeholderTextAppearance' |
98
+ /** A text was longer than Discord allows and Cordo cut it off. */
99
+ 'truncatedText' |
100
+ /** A list (options, items, components, ...) was longer than Discord allows and Cordo left out the rest. */
101
+ 'truncatedList' |
102
+ /** A number was outside of the range Discord allows and Cordo moved it into the range. */
103
+ 'clampedValue' |
104
+ /** A url is longer than Discord allows. Cordo keeps it as is, Discord will reject the message. */
105
+ 'longUrl' |
106
+ /** A custom_id was too long, empty, or used twice. Cordo cut it off or replaced it with one that does nothing when clicked. */
107
+ 'invalidCustomId' |
108
+ /** A color could not be read. Cordo left it out. */
109
+ 'invalidColor' |
110
+ /** Components were combined in a way Discord does not allow, e.g. a section without accessory. Cordo rearranged or replaced them. */
111
+ 'invalidLayout' |
112
+ /** An attribute was set that the component does not support where it is used, e.g. disabled on a select in a modal. Cordo left it out. */
113
+ 'unsupportedAttribute' |
114
+ /** A component is invalid and Cordo cannot fix it, e.g. a radio group with fewer than 2 options. Discord will reject it. */
115
+ 'invalidComponent'
91
116
  >
92
117
  }
93
118
 
@@ -107,7 +132,8 @@ export function defineCordoConfig(conf: PartialDeep<CordoConfig> = {}): PartialD
107
132
 
108
133
  export namespace ConfigInternals {
109
134
 
110
- const defaultConfig: CordoConfig = {
135
+ /** a function so every caller gets a fresh copy. structuredClone does not work here, the default logger holds functions */
136
+ const createDefaultConfig = (): CordoConfig => ({
111
137
  headless: false,
112
138
  paths: {
113
139
  root: '.',
@@ -150,8 +176,9 @@ export namespace ConfigInternals {
150
176
  privateErrorMessage: false
151
177
  }
152
178
  },
179
+ logger: console,
153
180
  omitWarnings: []
154
- }
181
+ })
155
182
 
156
183
  function locatePath() {
157
184
  if (process.env.CORDO_CONFIG_PATH)
@@ -166,14 +193,19 @@ export namespace ConfigInternals {
166
193
  const content = await import(filePath)
167
194
 
168
195
  if (!content || !content.default)
169
- return defaultConfig
196
+ return createDefaultConfig()
170
197
 
171
198
  if (!content.default[CordoConfigSymbol])
172
- return defaultConfig
199
+ return createDefaultConfig()
173
200
 
174
- return defu(content.default, defaultConfig)
201
+ const defaults = createDefaultConfig()
202
+ return {
203
+ ...defu(content.default, defaults),
204
+ // loggers are used as they are, merging would copy their methods off the object they belong to
205
+ logger: content.default.logger ?? defaults.logger
206
+ }
175
207
  } catch (ex) {
176
- return defaultConfig
208
+ return createDefaultConfig()
177
209
  }
178
210
  }
179
211
 
@@ -77,6 +77,12 @@ type RouteRequestFromButton = {
77
77
  selected: null
78
78
  }
79
79
 
80
+ type RouteRequestFromMenu = {
81
+ source: 'menu'
82
+ command: null
83
+ selected: null
84
+ }
85
+
80
86
  type RouteRequestFromSelect = {
81
87
  source: 'select'
82
88
  command: null
@@ -126,7 +132,7 @@ export type RouteRequest = {
126
132
  run: (...params: Parameters<typeof run>) => Promise<boolean | null>
127
133
  /** let a different route handle this. Returns whether successful, null if not run */
128
134
  goto: (...params: Parameters<typeof goto>) => Promise<boolean | null>
129
- } & (RouteRequestInGuild | RouteRequestInDM) & (RouteRequestFromCommand | RouteRequestFromButton | RouteRequestFromSelect | RouteRequestFromModal)
135
+ } & (RouteRequestInGuild | RouteRequestInDM) & (RouteRequestFromCommand | RouteRequestFromButton | RouteRequestFromMenu | RouteRequestFromSelect | RouteRequestFromModal)
130
136
 
131
137
  export type AsyncInteractionHandler = (i: RouteRequest) => RouteResponse | Promise<RouteResponse> | void | Promise<void> | boolean | Promise<boolean>
132
138
 
@@ -159,9 +165,11 @@ export function assertCordoRequest<
159
165
  ? RouteRequestFromCommand
160
166
  : Source extends 'button'
161
167
  ? RouteRequestFromButton
162
- : Source extends 'select'
163
- ? RouteRequestFromSelect
164
- : RouteRequestFromModal
168
+ : Source extends 'menu'
169
+ ? RouteRequestFromMenu
170
+ : Source extends 'select'
171
+ ? RouteRequestFromSelect
172
+ : RouteRequestFromModal
165
173
  ) {
166
174
  if (assumptions.location && request.location !== assumptions.location)
167
175
  throw new RouteAssumptionFailedError(request, assumptions)