cordo 2.15.2 → 2.16.1

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cordo",
3
- "version": "2.15.2",
3
+ "version": "2.16.1",
4
4
  "description": "A framework for handling complex discord api interactions",
5
5
  "exports": {
6
6
  ".": "./src/index.ts",
@@ -5,6 +5,7 @@ import { Hooks } from "../../core/hooks"
5
5
  import type { CordoFunct, CordoFunctRun } from "../../functions"
6
6
  import { FunctCompiler } from "../../functions/compiler"
7
7
  import { MaxLengthConstants } from "../../lib/constants"
8
+ import { CordoMagic } from "../../core/magic"
8
9
 
9
10
 
10
11
  export function button() {
@@ -13,10 +14,16 @@ export function button() {
13
14
  let disabledVal: boolean | undefined = undefined
14
15
  let styleVal = ButtonStyle.Secondary
15
16
  const functVal: CordoFunct[] = []
17
+ let overrideCustomIdVal: string | undefined = undefined
16
18
 
17
19
  function getLabel() {
18
- if (!labelVal)
19
- return emojiVal ? '' : 'Click'
20
+ if (!labelVal) {
21
+ if (emojiVal)
22
+ return ''
23
+ if (!CordoMagic.getConfig()?.omitWarnings.includes('placeholderTextAppearance'))
24
+ console.warn('A button was rendered with neither a label or an emoji provided. Cordo will use a placeholder label.')
25
+ return 'Click'
26
+ }
20
27
 
21
28
  return Hooks.callHook(
22
29
  'transformUserFacingText',
@@ -25,6 +32,16 @@ export function button() {
25
32
  )?.slice(0, MaxLengthConstants.BUTTON_LABEL)
26
33
  }
27
34
 
35
+ const advanced = {
36
+ /** Will override cordo's custom_id generation. Not compatible with onClick handlers */
37
+ overrideCustomId(customId: string) {
38
+ if (functVal.length > 0 && !CordoMagic.getConfig()?.omitWarnings.includes('customIdOverride'))
39
+ console.warn('You are overriding the custom_id of a button that has onClick handlers. This will prevent the onClick handlers from working.')
40
+ overrideCustomIdVal = customId
41
+ return out
42
+ }
43
+ }
44
+
28
45
  const out = {
29
46
  ...createComponent('Button', () => ({
30
47
  type: ComponentType.Button,
@@ -32,7 +49,7 @@ export function button() {
32
49
  emoji: emojiVal,
33
50
  style: styleVal,
34
51
  disabled: disabledVal,
35
- custom_id: FunctCompiler.toCustomId(disabledVal ? [] : functVal)
52
+ custom_id: overrideCustomIdVal ?? FunctCompiler.toCustomId(disabledVal ? [] : functVal)
36
53
  })),
37
54
 
38
55
  label: (text: string) => {
@@ -44,10 +61,14 @@ export function button() {
44
61
  return out
45
62
  },
46
63
  style: (style: 'primary' | 'secondary' | 'success' | 'danger') => {
47
- if (style === 'primary') styleVal = ButtonStyle.Primary
48
- else if (style === 'secondary') styleVal = ButtonStyle.Secondary
49
- else if (style === 'success') styleVal = ButtonStyle.Success
50
- else if (style === 'danger') styleVal = ButtonStyle.Danger
64
+ if (style === 'primary')
65
+ styleVal = ButtonStyle.Primary
66
+ else if (style === 'secondary')
67
+ styleVal = ButtonStyle.Secondary
68
+ else if (style === 'success')
69
+ styleVal = ButtonStyle.Success
70
+ else if (style === 'danger')
71
+ styleVal = ButtonStyle.Danger
51
72
  return out
52
73
  },
53
74
  disabled(disabled = true, opts?: { greyOut?: boolean }) {
@@ -57,9 +78,13 @@ export function button() {
57
78
  return out
58
79
  },
59
80
  onClick: (...funct: CordoFunctRun) => {
81
+ if (overrideCustomIdVal && !CordoMagic.getConfig()?.omitWarnings.includes('customIdOverride'))
82
+ console.warn('You are adding onClick handlers to a button that already has an overridden custom_id. These handlers will not be called.')
60
83
  functVal.push(...funct)
61
84
  return out
62
- }
85
+ },
86
+ /** This namespace contains advanced features you normally do not need */
87
+ advanced
63
88
  }
64
89
 
65
90
  return out
@@ -3,6 +3,7 @@ import { Hooks } from "../../core/hooks"
3
3
  import { value, type CordoFunct, type CordoFunctRun } from "../../functions"
4
4
  import { FunctCompiler } from "../../functions/compiler"
5
5
  import { MaxLengthConstants } from "../../lib/constants"
6
+ import { CordoMagic } from "../../core/magic"
6
7
 
7
8
 
8
9
  type CheckboxGroupOption<Value extends string = string> = ({
@@ -22,10 +23,14 @@ export function checkboxGroup<Values extends string = string>() {
22
23
  let requiredVal: boolean = false
23
24
  let ref: string | undefined = undefined
24
25
  const functVal: CordoFunct[] = []
26
+ let overrideCustomIdVal: string | undefined = undefined
25
27
 
26
28
  function getLabel() {
27
- if (!labelVal)
29
+ if (!labelVal) {
30
+ if (!CordoMagic.getConfig()?.omitWarnings.includes('placeholderTextAppearance'))
31
+ console.warn('A checkbox group was rendered without a label provided. Cordo will use a placeholder label.')
28
32
  return 'Pick one'
33
+ }
29
34
  return Hooks.callHook(
30
35
  'transformUserFacingText',
31
36
  labelVal,
@@ -50,18 +55,35 @@ export function checkboxGroup<Values extends string = string>() {
50
55
  description: o.description
51
56
  ? Hooks.callHook('transformUserFacingText', o.description, { component: 'CheckboxGroup', position: 'option.description' })?.slice(0, MaxLengthConstants.SELECT_OPTION_DESCRIPTION)
52
57
  : undefined,
53
- value: FunctCompiler.toCustomId([
54
- ...(o.onSelect
55
- ? Array.isArray(o.onSelect)
56
- ? o.onSelect
57
- : [ o.onSelect ]
58
- : []
59
- ),
60
- o.value ? value(o.value) : null
61
- ])
58
+ /** If the custom_id is overriden, use the override value (or an empty custom_id) - otherwise compile the custom_ids and values into the value field */
59
+ value: overrideCustomIdVal
60
+ ? (o.value ?? FunctCompiler.toCustomId([]))
61
+ : FunctCompiler.toCustomId([
62
+ ...(o.onSelect
63
+ ? Array.isArray(o.onSelect)
64
+ ? o.onSelect
65
+ : [ o.onSelect ]
66
+ : []
67
+ ),
68
+ o.value ? value(o.value) : null
69
+ ])
62
70
  }))
63
71
  }
64
72
 
73
+ const advanced = {
74
+ /** Will override cordo's custom_id generation. Not compatible with onClick handlers */
75
+ rawCustomIds(customId: string) {
76
+ if (!CordoMagic.getConfig()?.omitWarnings.includes('customIdOverride')) {
77
+ if (functVal.length > 0)
78
+ console.warn('You are overriding the custom_id of a checkbox group that has onSubmit handlers. This will prevent the onSubmit handlers from working.')
79
+ if (ref)
80
+ console.warn('You are overriding the custom_id of a checkbox group that has an as() id. Your as() id will be overridden.')
81
+ }
82
+ overrideCustomIdVal = customId
83
+ return out
84
+ }
85
+ }
86
+
65
87
  const out = {
66
88
  ...createComponent('CheckboxGroup', () => ({
67
89
  type: ComponentType.CheckboxGroup,
@@ -71,7 +93,7 @@ export function checkboxGroup<Values extends string = string>() {
71
93
  max_values: Math.min(maxValues ?? minValues ?? 1, optionsVal.length),
72
94
  required: requiredVal,
73
95
  options: getOptions(),
74
- custom_id: FunctCompiler.toCustomId([
96
+ custom_id: overrideCustomIdVal ?? FunctCompiler.toCustomId([
75
97
  ...functVal,
76
98
  ...(ref ? [ value(ref) ] : [])
77
99
  ]),
@@ -80,6 +102,8 @@ export function checkboxGroup<Values extends string = string>() {
80
102
  })),
81
103
 
82
104
  as: (id: string) => {
105
+ if (overrideCustomIdVal && !CordoMagic.getConfig()?.omitWarnings.includes('customIdOverride'))
106
+ console.warn('You are assigning an as() id to a checkbox group that already has an overridden custom_id. Your provided id will be ignored.')
83
107
  ref = id
84
108
  return out
85
109
  },
@@ -96,6 +120,8 @@ export function checkboxGroup<Values extends string = string>() {
96
120
  return out
97
121
  },
98
122
  onSubmit: (...funct: CordoFunctRun) => {
123
+ if (overrideCustomIdVal && !CordoMagic.getConfig()?.omitWarnings.includes('customIdOverride'))
124
+ console.warn('You are adding onSubmit handlers to a checkbox group that already has an overridden custom_id. These handlers will not be called.')
99
125
  functVal.push(...funct)
100
126
  return out
101
127
  },
@@ -115,6 +141,8 @@ export function checkboxGroup<Values extends string = string>() {
115
141
  descriptionVal = text
116
142
  return out
117
143
  },
144
+ /** This namespace contains advanced features you normally do not need */
145
+ advanced
118
146
  }
119
147
 
120
148
  return out
@@ -2,6 +2,7 @@ import { ComponentType, createComponent } from "../component"
2
2
  import { Hooks } from "../../core/hooks"
3
3
  import { value, type CordoFunct, type CordoFunctRun } from "../../functions"
4
4
  import { FunctCompiler } from "../../functions/compiler"
5
+ import { CordoMagic } from "../../core/magic"
5
6
 
6
7
 
7
8
  export function fileUpload() {
@@ -12,10 +13,14 @@ export function fileUpload() {
12
13
  let requiredVal: boolean = false
13
14
  let ref: string | undefined = undefined
14
15
  const functVal: CordoFunct[] = []
16
+ let overrideCustomIdVal: string | undefined = undefined
15
17
 
16
18
  function getLabel() {
17
- if (!labelVal)
18
- return 'Your Response'
19
+ if (!labelVal) {
20
+ if (!CordoMagic.getConfig()?.omitWarnings.includes('placeholderTextAppearance'))
21
+ console.warn('A file upload was rendered without a label provided. Cordo will use a placeholder label.')
22
+ return 'Your response'
23
+ }
19
24
  return Hooks.callHook(
20
25
  'transformUserFacingText',
21
26
  labelVal,
@@ -33,6 +38,20 @@ export function fileUpload() {
33
38
  )
34
39
  }
35
40
 
41
+ const advanced = {
42
+ /** Will override cordo's custom_id generation. Not compatible with onSubmit handlers */
43
+ overrideCustomId(customId: string) {
44
+ if (!CordoMagic.getConfig()?.omitWarnings.includes('customIdOverride')) {
45
+ if (functVal.length > 0)
46
+ console.warn('You are overriding the custom_id of a file upload that has onSubmit handlers. This will prevent the onSubmit handlers from working.')
47
+ if (ref)
48
+ console.warn('You are overriding the custom_id of a file upload that has an as() id. Your as() id will be overridden.')
49
+ }
50
+ overrideCustomIdVal = customId
51
+ return out
52
+ }
53
+ }
54
+
36
55
  const out = {
37
56
  ...createComponent('FileUpload', () => ({
38
57
  type: ComponentType.FileUpload,
@@ -41,7 +60,7 @@ export function fileUpload() {
41
60
  min_values: Math.max(minValues ?? 1, 0),
42
61
  max_values: Math.min(maxValues ?? minValues ?? 1, 10),
43
62
  required: requiredVal,
44
- custom_id: FunctCompiler.toCustomId([
63
+ custom_id: overrideCustomIdVal ?? FunctCompiler.toCustomId([
45
64
  ...functVal,
46
65
  ...(ref ? [ value(ref) ] : [])
47
66
  ]),
@@ -50,6 +69,8 @@ export function fileUpload() {
50
69
  })),
51
70
 
52
71
  as: (id: string) => {
72
+ if (overrideCustomIdVal && !CordoMagic.getConfig()?.omitWarnings.includes('customIdOverride'))
73
+ console.warn('You are assigning an as() id to a file upload that already has an overridden custom_id. Your provided id will be ignored.')
53
74
  ref = id
54
75
  return out
55
76
  },
@@ -66,6 +87,8 @@ export function fileUpload() {
66
87
  return out
67
88
  },
68
89
  onSubmit: (...funct: CordoFunctRun) => {
90
+ if (overrideCustomIdVal && !CordoMagic.getConfig()?.omitWarnings.includes('customIdOverride'))
91
+ console.warn('You are adding onSubmit handlers to a file upload that already has an overridden custom_id. These handlers will not be called.')
69
92
  functVal.push(...funct)
70
93
  return out
71
94
  },
@@ -77,6 +100,8 @@ export function fileUpload() {
77
100
  descriptionVal = text
78
101
  return out
79
102
  },
103
+ /** This namespace contains advanced features you normally do not need */
104
+ advanced
80
105
  }
81
106
 
82
107
  return out
@@ -1,4 +1,5 @@
1
1
  import { Hooks } from "../../core/hooks"
2
+ import { CordoMagic } from "../../core/magic"
2
3
  import type { CordoFunct, CordoFunctRun } from "../../functions"
3
4
  import { FunctCompiler } from "../../functions/compiler"
4
5
  import { ComponentType, createComponent, renderComponent, renderComponentList, type CordoComponent, type CordoComponentPayload, type StringComponentType } from "../component"
@@ -36,10 +37,14 @@ function labelize(component: CordoComponent<StringComponentType>, parsed: CordoC
36
37
  export function modal(...components: AllowedComponentArray) {
37
38
  let titleVal: string | undefined = undefined
38
39
  const functVal: CordoFunct[] = []
40
+ let overrideCustomIdVal: string | undefined = undefined
39
41
 
40
42
  function getTitle() {
41
- if (!titleVal)
43
+ if (!titleVal) {
44
+ if (!CordoMagic.getConfig()?.omitWarnings.includes('placeholderTextAppearance'))
45
+ console.warn('A modal was rendered without a title provided. Cordo will use a placeholder title.')
42
46
  return 'Modal'
47
+ }
43
48
 
44
49
  return Hooks.callHook(
45
50
  'transformUserFacingText',
@@ -48,12 +53,22 @@ export function modal(...components: AllowedComponentArray) {
48
53
  )
49
54
  }
50
55
 
56
+ const advanced = {
57
+ /** Will override cordo's custom_id generation. Not compatible with onSubmit handlers */
58
+ overrideCustomId(customId: string) {
59
+ if (functVal.length > 0 && !CordoMagic.getConfig()?.omitWarnings.includes('customIdOverride'))
60
+ console.warn('You are overriding the custom_id of a modal that has onSubmit handlers. This will prevent the onSubmit handlers from working.')
61
+ overrideCustomIdVal = customId
62
+ return out
63
+ }
64
+ }
65
+
51
66
  const out = {
52
67
  ...createComponent('Modal', ({ hirarchy, attributes }) => ({
53
68
  type: ComponentType.Modal,
54
69
  components: renderComponentList(components.flat(), 'Modal', hirarchy, attributes, labelize),
55
70
  title: getTitle(),
56
- custom_id: FunctCompiler.toCustomId(functVal)
71
+ custom_id: overrideCustomIdVal ?? FunctCompiler.toCustomId(functVal)
57
72
  })),
58
73
 
59
74
  title: (value: string) => {
@@ -61,6 +76,8 @@ export function modal(...components: AllowedComponentArray) {
61
76
  return out
62
77
  },
63
78
  onSubmit: (...funct: CordoFunctRun) => {
79
+ if (overrideCustomIdVal && !CordoMagic.getConfig()?.omitWarnings.includes('customIdOverride'))
80
+ console.warn('You are adding onSubmit handlers to a modal that already has an overridden custom_id. These handlers will not be called.')
64
81
  functVal.push(...funct)
65
82
  return out
66
83
  },
@@ -71,7 +88,9 @@ export function modal(...components: AllowedComponentArray) {
71
88
  else
72
89
  yield component
73
90
  }
74
- }
91
+ },
92
+ /** This namespace contains advanced features you normally do not need */
93
+ advanced
75
94
  }
76
95
 
77
96
  return out
@@ -3,6 +3,7 @@ import { Hooks } from "../../core/hooks"
3
3
  import { value, type CordoFunct, type CordoFunctRun } from "../../functions"
4
4
  import { FunctCompiler } from "../../functions/compiler"
5
5
  import { MaxLengthConstants } from "../../lib/constants"
6
+ import { CordoMagic } from "../../core/magic"
6
7
 
7
8
 
8
9
  type RadioGroupOption<Value extends string = string> = ({
@@ -20,10 +21,14 @@ export function radioGroup<Values extends string = string>() {
20
21
  let requiredVal: boolean = false
21
22
  let ref: string | undefined = undefined
22
23
  const functVal: CordoFunct[] = []
24
+ let overrideCustomIdVal: string | undefined = undefined
23
25
 
24
26
  function getLabel() {
25
- if (!labelVal)
27
+ if (!labelVal) {
28
+ if (!CordoMagic.getConfig()?.omitWarnings.includes('placeholderTextAppearance'))
29
+ console.warn('A radio group was rendered without a label provided. Cordo will use a placeholder label.')
26
30
  return 'Pick one'
31
+ }
27
32
  return Hooks.callHook(
28
33
  'transformUserFacingText',
29
34
  labelVal,
@@ -48,18 +53,35 @@ export function radioGroup<Values extends string = string>() {
48
53
  description: o.description
49
54
  ? Hooks.callHook('transformUserFacingText', o.description, { component: 'RadioGroup', position: 'option.description' })?.slice(0, MaxLengthConstants.SELECT_OPTION_DESCRIPTION)
50
55
  : undefined,
51
- value: FunctCompiler.toCustomId([
52
- ...(o.onSelect
53
- ? Array.isArray(o.onSelect)
54
- ? o.onSelect
55
- : [ o.onSelect ]
56
- : []
57
- ),
58
- o.value ? value(o.value) : null
59
- ])
56
+ /** If the custom_id is overriden, use the override value (or an empty custom_id) - otherwise compile the custom_ids and values into the value field */
57
+ value: overrideCustomIdVal
58
+ ? (o.value ?? FunctCompiler.toCustomId([]))
59
+ : FunctCompiler.toCustomId([
60
+ ...(o.onSelect
61
+ ? Array.isArray(o.onSelect)
62
+ ? o.onSelect
63
+ : [ o.onSelect ]
64
+ : []
65
+ ),
66
+ o.value ? value(o.value) : null
67
+ ])
60
68
  }))
61
69
  }
62
70
 
71
+ const advanced = {
72
+ /** Will override cordo's custom_id generation. Not compatible with onSubmit handlers */
73
+ overrideCustomId(customId: string) {
74
+ if (!CordoMagic.getConfig()?.omitWarnings.includes('customIdOverride')) {
75
+ if (functVal.length > 0)
76
+ console.warn('You are overriding the custom_id of a radio group that has onSubmit handlers. This will prevent the onSubmit handlers from working.')
77
+ if (ref)
78
+ console.warn('You are overriding the custom_id of a radio group that has an as() id. Your as() id will be overridden.')
79
+ }
80
+ overrideCustomIdVal = customId
81
+ return out
82
+ }
83
+ }
84
+
63
85
  const out = {
64
86
  ...createComponent('RadioGroup', () => ({
65
87
  type: ComponentType.RadioGroup,
@@ -67,7 +89,7 @@ export function radioGroup<Values extends string = string>() {
67
89
  description: getDescription(),
68
90
  required: requiredVal,
69
91
  options: getOptions(),
70
- custom_id: FunctCompiler.toCustomId([
92
+ custom_id: overrideCustomIdVal ?? FunctCompiler.toCustomId([
71
93
  ...functVal,
72
94
  ...(ref ? [ value(ref) ] : [])
73
95
  ]),
@@ -76,6 +98,8 @@ export function radioGroup<Values extends string = string>() {
76
98
  })),
77
99
 
78
100
  as: (id: string) => {
101
+ if (overrideCustomIdVal && !CordoMagic.getConfig()?.omitWarnings.includes('customIdOverride'))
102
+ console.warn('You are assigning an as() id to a radio group that already has an overridden custom_id. Your provided id will be ignored.')
79
103
  ref = id
80
104
  return out
81
105
  },
@@ -84,6 +108,8 @@ export function radioGroup<Values extends string = string>() {
84
108
  return out
85
109
  },
86
110
  onSubmit: (...funct: CordoFunctRun) => {
111
+ if (overrideCustomIdVal && !CordoMagic.getConfig()?.omitWarnings.includes('customIdOverride'))
112
+ console.warn('You are adding onSubmit handlers to a radio group that already has an overridden custom_id. These handlers will not be called.')
87
113
  functVal.push(...funct)
88
114
  return out
89
115
  },
@@ -103,6 +129,8 @@ export function radioGroup<Values extends string = string>() {
103
129
  descriptionVal = text
104
130
  return out
105
131
  },
132
+ /** This namespace contains advanced features you normally do not need */
133
+ advanced
106
134
  }
107
135
 
108
136
  return out
@@ -4,6 +4,7 @@ import { Hooks } from "../../core/hooks"
4
4
  import { value, type CordoFunct, type CordoFunctRun } from "../../functions"
5
5
  import { FunctCompiler } from "../../functions/compiler"
6
6
  import { MaxLengthConstants } from "../../lib/constants"
7
+ import { CordoMagic } from "../../core/magic"
7
8
 
8
9
 
9
10
  type SelectMenuOption<Value extends string = string> = Omit<APISelectMenuOption, 'value'> & ({
@@ -21,6 +22,7 @@ export function selectString<Values extends string = string>() {
21
22
  let disabledVal: boolean | undefined = undefined
22
23
  let ref: string | undefined = undefined
23
24
  const functVal: CordoFunct[] = []
25
+ let overrideCustomIdVal: string | undefined = undefined
24
26
 
25
27
  function getPlaceholder() {
26
28
  if (!placeholderVal)
@@ -33,8 +35,11 @@ export function selectString<Values extends string = string>() {
33
35
  }
34
36
 
35
37
  function getLabel() {
36
- if (!labelVal)
38
+ if (!labelVal) {
39
+ if (!CordoMagic.getConfig()?.omitWarnings.includes('placeholderTextAppearance'))
40
+ console.warn('A string select was rendered without a label provided. Cordo will use a placeholder label.')
37
41
  return 'Your Response'
42
+ }
38
43
  return Hooks.callHook(
39
44
  'transformUserFacingText',
40
45
  labelVal,
@@ -59,18 +64,35 @@ export function selectString<Values extends string = string>() {
59
64
  description: o.description
60
65
  ? Hooks.callHook('transformUserFacingText', o.description, { component: 'StringSelect', position: 'option.description' })?.slice(0, MaxLengthConstants.SELECT_OPTION_DESCRIPTION)
61
66
  : undefined,
62
- value: FunctCompiler.toCustomId([
63
- ...(o.onClick
64
- ? Array.isArray(o.onClick)
65
- ? o.onClick
66
- : [ o.onClick ]
67
- : []
68
- ),
69
- o.value ? value(o.value) : null
70
- ])
67
+ /** If the custom_id is overriden, use the override value (or an empty custom_id) - otherwise compile the custom_ids and values into the value field */
68
+ value: overrideCustomIdVal
69
+ ? (o.value ?? FunctCompiler.toCustomId([]))
70
+ : FunctCompiler.toCustomId([
71
+ ...(o.onClick
72
+ ? Array.isArray(o.onClick)
73
+ ? o.onClick
74
+ : [ o.onClick ]
75
+ : []
76
+ ),
77
+ o.value ? value(o.value) : null
78
+ ])
71
79
  }))
72
80
  }
73
81
 
82
+ const advanced = {
83
+ /** Will override cordo's custom_id generation. Not compatible with onSubmit handlers */
84
+ overrideCustomId(customId: string) {
85
+ if (!CordoMagic.getConfig()?.omitWarnings.includes('customIdOverride')) {
86
+ if (functVal.length > 0)
87
+ console.warn('You are overriding the custom_id of a string select that has onSubmit handlers. This will prevent the onSubmit handlers from working.')
88
+ if (ref)
89
+ console.warn('You are overriding the custom_id of a string select that has an as() id. Your as() id will be overridden.')
90
+ }
91
+ overrideCustomIdVal = customId
92
+ return out
93
+ }
94
+ }
95
+
74
96
  const out = {
75
97
  ...createComponent('StringSelect', () => ({
76
98
  type: ComponentType.StringSelect,
@@ -79,7 +101,7 @@ export function selectString<Values extends string = string>() {
79
101
  max_values: maxValues ? Math.min(optionsVal.length, maxValues) : undefined,
80
102
  disabled: disabledVal,
81
103
  options: getOptions(),
82
- custom_id: FunctCompiler.toCustomId([
104
+ custom_id: overrideCustomIdVal ?? FunctCompiler.toCustomId([
83
105
  ...(disabledVal ? [] : functVal),
84
106
  ...(ref ? [ value(ref) ] : [])
85
107
  ]),
@@ -88,6 +110,8 @@ export function selectString<Values extends string = string>() {
88
110
  })),
89
111
 
90
112
  as: (id: string) => {
113
+ if (overrideCustomIdVal && !CordoMagic.getConfig()?.omitWarnings.includes('customIdOverride'))
114
+ console.warn('You are assigning an as() id to a string select that already has an overridden custom_id. Your provided id will be ignored.')
91
115
  ref = id
92
116
  return out
93
117
  },
@@ -108,6 +132,8 @@ export function selectString<Values extends string = string>() {
108
132
  return out
109
133
  },
110
134
  onSubmit: (...funct: CordoFunctRun) => {
135
+ if (overrideCustomIdVal && !CordoMagic.getConfig()?.omitWarnings.includes('customIdOverride'))
136
+ console.warn('You are adding onSubmit handlers to a string select that already has an overridden custom_id. These handlers will not be called.')
111
137
  functVal.push(...funct)
112
138
  return out
113
139
  },
@@ -127,6 +153,8 @@ export function selectString<Values extends string = string>() {
127
153
  descriptionVal = text
128
154
  return out
129
155
  },
156
+ /** This namespace contains advanced features you normally do not need */
157
+ advanced,
130
158
  }
131
159
 
132
160
  return out
@@ -2,6 +2,7 @@ import { ComponentType, createComponent } from "../component"
2
2
  import { Hooks } from "../../core/hooks"
3
3
  import { FunctCompiler } from "../../functions/compiler"
4
4
  import { value } from "../../functions"
5
+ import { CordoMagic } from "../../core/magic"
5
6
 
6
7
 
7
8
  export function textInput() {
@@ -14,6 +15,7 @@ export function textInput() {
14
15
  let sizeVal: number | undefined = undefined
15
16
  let currentVal: string | undefined = undefined
16
17
  let ref: string | undefined = undefined
18
+ let overrideCustomIdVal: string | undefined = undefined
17
19
 
18
20
  function getPlaceholder() {
19
21
  if (!placeholderVal)
@@ -26,8 +28,11 @@ export function textInput() {
26
28
  }
27
29
 
28
30
  function getLabel() {
29
- if (!labelVal)
31
+ if (!labelVal) {
32
+ if (!CordoMagic.getConfig()?.omitWarnings.includes('placeholderTextAppearance'))
33
+ console.warn('A text input was rendered without a label provided. Cordo will use a placeholder label.')
30
34
  return 'Your Response'
35
+ }
31
36
  return Hooks.callHook(
32
37
  'transformUserFacingText',
33
38
  labelVal,
@@ -45,6 +50,16 @@ export function textInput() {
45
50
  )
46
51
  }
47
52
 
53
+ const advanced = {
54
+ /** Will override cordo's custom_id generation. Not compatible with as() ids */
55
+ overrideCustomId(customId: string) {
56
+ 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.')
58
+ overrideCustomIdVal = customId
59
+ return out
60
+ }
61
+ }
62
+
48
63
  const out = {
49
64
  ...createComponent('TextInput', () => ({
50
65
  type: ComponentType.TextInput,
@@ -54,12 +69,14 @@ export function textInput() {
54
69
  required: requiredVal,
55
70
  style: sizeVal ?? 1,
56
71
  value: currentVal,
57
- custom_id: FunctCompiler.toCustomId(ref ? [ value(ref) ] : []), // get a noop if no ref
72
+ custom_id: overrideCustomIdVal ?? FunctCompiler.toCustomId(ref ? [ value(ref) ] : []), // get a noop if no ref
58
73
  'modal:label': getLabel(),
59
74
  'modal:description': getDescription(),
60
75
  })),
61
76
 
62
77
  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.')
63
80
  ref = id
64
81
  return out
65
82
  },
@@ -102,7 +119,9 @@ export function textInput() {
102
119
  ? 2
103
120
  : undefined
104
121
  return out
105
- }
122
+ },
123
+ /** This namespace contains advanced features you normally do not need */
124
+ advanced
106
125
  }
107
126
 
108
127
  return out
@@ -3,6 +3,7 @@ import { ChannelType, ApplicationCommandOptionType, ApplicationCommandType, type
3
3
  import type { LocalizedString } from '../../lib/localization'
4
4
  import { CordoGateway } from '../gateway'
5
5
  import { RoutingResolve } from '../routing/resolve'
6
+ import { CordoMagic } from '../magic'
6
7
  import type { CordoInteraction } from '../interaction'
7
8
  import type { CordoRoute } from './route'
8
9
 
@@ -180,7 +181,7 @@ export namespace CommandInternals {
180
181
  } as any
181
182
  }
182
183
 
183
- export async function syncCommands(commands: Map<string, CordoCommand>, guild?: string, options?: { maxRetries?: number }) {
184
+ export async function syncCommands(commands: Map<string, CordoCommand> | undefined, guild?: string, options?: { maxRetries?: number }) {
184
185
  if (!commands || commands.size === 0) {
185
186
  console.warn('No commands to sync. Is cordo initialized and commands defined?')
186
187
  return
@@ -188,8 +189,16 @@ export namespace CommandInternals {
188
189
 
189
190
  const rootCommands = new Map<string, CommandTree>()
190
191
 
192
+ const config = CordoMagic.getConfig()
193
+ const prefix = (config?.defaults?.commandRoutePrefix ?? 'command') + '/'
194
+
191
195
  for (const [ route, command ] of commands.entries()) {
192
- const parts = route.split('/')
196
+ let cleanRoute = route
197
+ if (cleanRoute.startsWith(prefix))
198
+ cleanRoute = cleanRoute.slice(prefix.length)
199
+ cleanRoute = cleanRoute.replace(/\.\w+$/, '')
200
+
201
+ const parts = cleanRoute.split('/')
193
202
  let currentLevel = rootCommands
194
203
 
195
204
  for (let i = 0; i < parts.length; i++) {
@@ -16,6 +16,17 @@ 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
+ * Mounting cordo in headless mode will have the following effects:
21
+ * - Cordo will not read the filesystem for config, lockfile, or routes.
22
+ * - Cordo will not write to the lockfile or generate types.
23
+ * - Cordo will not generate custom_ids for components.
24
+ * - Cordo will not be able to route.
25
+ *
26
+ * Use headless mode if you want to use cordo exclusively to render components without using cordo as your framework.
27
+ */
28
+ headless: boolean
29
+
19
30
  paths: {
20
31
  root: string
21
32
  routes: string
@@ -25,14 +36,21 @@ export type CordoConfig = {
25
36
  defaults: {
26
37
  commandRoutePrefix?: string
27
38
  }
28
- upstream: {
29
- baseUrl: string
30
- /** if an interaction was not replied to within X millis, cordo will send the appropriate defer/ack response. Set to 0 to disable */
31
- autoDeferMs: number
32
- }
39
+ /** The Discord client you are operating as */
33
40
  client: {
41
+ /** The ID of the app */
34
42
  id: string
43
+ /** The app's public key. Only required if you are receiving interactions via HTTP */
35
44
  publicKey: string
45
+ /** The bot token. Only required for actions that call Discord proactively like syncing commands, not required for handling interactions. */
46
+ token?: string
47
+ }
48
+ /** Upstream describes the Discord API */
49
+ upstream: {
50
+ /** The Discord API base URL, e.g. https://discord.com/api/v10 */
51
+ baseUrl: string
52
+ /** If an interaction was not replied to within X millis, cordo will send the appropriate defer/ack response. Set to 0 to disable. */
53
+ autoDeferMs: number
36
54
  }
37
55
  /** 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. */
38
56
  hooks: {
@@ -61,6 +79,16 @@ export type CordoConfig = {
61
79
  run: Required<RunFlagOpts>
62
80
  goto: Required<GotoFlagOpts>
63
81
  }
82
+
83
+ /** 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
+ omitWarnings: Array<
85
+ /** A component was assigned functs while also having a custom id override. This means the functs won't trigger */
86
+ 'customIdOverride' |
87
+ /** 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
+ 'headlessCustomIdGeneration' |
89
+ /** 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'
91
+ >
64
92
  }
65
93
 
66
94
  export type ParsedCordoConfig = CordoConfig & {
@@ -80,6 +108,7 @@ export function defineCordoConfig(conf: PartialDeep<CordoConfig> = {}): PartialD
80
108
  export namespace ConfigInternals {
81
109
 
82
110
  const defaultConfig: CordoConfig = {
111
+ headless: false,
83
112
  paths: {
84
113
  root: '.',
85
114
  routes: './routes',
@@ -119,7 +148,8 @@ export namespace ConfigInternals {
119
148
  continueOnError: false,
120
149
  privateErrorMessage: false
121
150
  }
122
- }
151
+ },
152
+ omitWarnings: []
123
153
  }
124
154
 
125
155
  function locatePath() {
@@ -153,14 +183,16 @@ export namespace ConfigInternals {
153
183
  export async function readAndParseConfig(): Promise<ParsedCordoConfig> {
154
184
  const config = await readConfig()
155
185
 
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)
161
- : null
162
-
163
- config.paths.routes = resolveRelativePath(config.paths.routes, config.paths.root)
186
+ if (!config.headless) {
187
+ config.paths.root = resolveRelativePath(config.paths.root)
188
+
189
+ config.paths.lockfile = resolveRelativePath(config.paths.lockfile, config.paths.root)
190
+ config.paths.types = config.paths.types
191
+ ? resolveRelativePath(config.paths.types, config.paths.root)
192
+ : null
193
+
194
+ config.paths.routes = resolveRelativePath(config.paths.routes, config.paths.root)
195
+ }
164
196
 
165
197
  return {
166
198
  ...config,
@@ -64,6 +64,7 @@ export namespace CordoGateway {
64
64
  method,
65
65
  url,
66
66
  baseURL: config.upstream.baseUrl,
67
+ headers: config.client.token ? { Authorization: `Bot ${config.client.token}` } : undefined,
67
68
  data: body,
68
69
  validateStatus: null
69
70
  })
@@ -337,6 +338,8 @@ export namespace CordoGateway {
337
338
  const config = CordoMagic.getConfig()
338
339
  if (!config?.client.id)
339
340
  throw new MissingContextError('Could not upsert command, no client id found in config context.')
341
+ if (!config?.client.token)
342
+ throw new MissingContextError('Could not upsert command, no bot token found in config context (client.token).')
340
343
 
341
344
  const endpoint = guild ? `/applications/${config.client.id}/guilds/${guild}/commands` : `/applications/${config.client.id}/commands`
342
345
  return apiRequest('post', endpoint, command)
package/src/core/index.ts CHANGED
@@ -18,30 +18,35 @@ export { type CordoInteraction } from './interaction'
18
18
 
19
19
  //
20
20
 
21
- let lockfile: LockfileInternals.ParsedLockfile | null = null
22
- let config: ParsedCordoConfig | null = null
23
-
24
21
  async function mountCordo(configOverrides?: PartialDeep<CordoConfig>) {
25
22
  const fileConfig = await ConfigInternals.readAndParseConfig()
26
- config = configOverrides ? defu(configOverrides, fileConfig) as ParsedCordoConfig : fileConfig
27
-
28
- lockfile = await LockfileInternals.readOrCreateLockfile(config.paths.lockfile)
29
- await RoutingFilesystem.readFsTreeAndSyncLockfile(config.paths.routes, lockfile, config)
30
-
31
- LockfileInternals.writeLockfile(config.paths.lockfile, lockfile, config.paths.types)
23
+ CordoMagic.globalConfig = configOverrides
24
+ ? defu(configOverrides, fileConfig) as ParsedCordoConfig
25
+ : fileConfig
26
+
27
+ if (!CordoMagic.globalConfig.headless) {
28
+ CordoMagic.globalLockfile = await LockfileInternals.readOrCreateLockfile(CordoMagic.globalConfig!.paths.lockfile)
29
+ await RoutingFilesystem.readFsTreeAndSyncLockfile(CordoMagic.globalConfig.paths.routes, CordoMagic.globalLockfile, CordoMagic.globalConfig)
30
+
31
+ LockfileInternals.writeLockfile(CordoMagic.globalConfig.paths.lockfile, CordoMagic.globalLockfile, CordoMagic.globalConfig.paths.types)
32
+ }
32
33
  }
33
34
 
34
35
  function triggerInteraction(interaction: APIInteraction, opts: {
35
36
  httpCallback?: (payload: any) => any
36
37
  } = {}) {
37
- if (!lockfile || !config)
38
- throw new Error('Cordo is not mounted')
38
+ if (!CordoMagic.globalLockfile || !CordoMagic.globalConfig) {
39
+ if (CordoMagic.globalConfig?.headless)
40
+ throw new Error('[Cordo.triggerInteraction] Cordo is mounted in headless mode and cannot process interactions')
41
+ else
42
+ throw new Error('[Cordo.triggerInteraction] Cordo is not mounted')
43
+ }
39
44
 
40
45
  CordoGateway.triggerInteraction({
41
46
  interaction,
42
47
  httpCallback: opts.httpCallback,
43
- lockfile,
44
- config
48
+ lockfile: CordoMagic.globalLockfile,
49
+ config: CordoMagic.globalConfig
45
50
  })
46
51
  }
47
52
 
@@ -51,22 +56,26 @@ function triggerInteraction(interaction: APIInteraction, opts: {
51
56
  * you should not notice any difference but it will allow you to store more data on click or submit functions
52
57
  */
53
58
  function registerConstants(constants: readonly string[]) {
54
- if (!lockfile || !config)
55
- throw new Error('Cordo is not mounted')
59
+ if (!CordoMagic.globalLockfile || !CordoMagic.globalConfig) {
60
+ if (CordoMagic.globalConfig?.headless)
61
+ throw new Error('[Cordo.registerConstants] Cordo is mounted in headless mode and cannot register constants')
62
+ else
63
+ throw new Error('[Cordo.registerConstants] Cordo is not mounted')
64
+ }
56
65
 
57
66
  let changesMade = false
58
67
  for (const entry of constants) {
59
68
  if (entry.length <= LockfileInternals.Const.idLength) // too short to save any space
60
69
  continue
61
- if (lockfile!.lut.includes(entry))
70
+ if (CordoMagic.globalLockfile!.lut.includes(entry))
62
71
  continue
63
72
 
64
- lockfile.lut[lockfile.reg.lutCounter++] = entry
73
+ CordoMagic.globalLockfile.lut[CordoMagic.globalLockfile.reg.lutCounter++] = entry
65
74
  changesMade = true
66
75
  }
67
76
 
68
77
  if (changesMade)
69
- return LockfileInternals.writeLockfile(config!.paths.lockfile, lockfile!, config!.paths.types)
78
+ return LockfileInternals.writeLockfile(CordoMagic.globalConfig!.paths.lockfile, CordoMagic.globalLockfile!, CordoMagic.globalConfig!.paths.types)
70
79
  else
71
80
  return Promise.resolve()
72
81
  }
@@ -78,7 +87,8 @@ export const Cordo = {
78
87
  registerConstants,
79
88
  triggerInteraction,
80
89
  respondToRawInteraction: CordoGateway.respondTo,
81
- syncCommands: (opts?: { maxRetries?: number }) => CommandInternals.syncCommands(lockfile!.$runtime.registeredCommands, undefined, opts)
90
+ syncCommands: (opts?: { maxRetries?: number }) => CommandInternals.syncCommands(CordoMagic.globalLockfile?.$runtime?.registeredCommands, undefined, opts),
91
+ getConfig: () => CordoMagic.globalConfig,
82
92
  }
83
93
  Object.freeze(Cordo)
84
94
 
@@ -95,8 +105,8 @@ export namespace Extend {
95
105
  ) {
96
106
  CordoMagic.Internals.runWithCtx(fn, {
97
107
  invoker: ctx?.invoker ?? null,
98
- lockfile: ctx?.lockfile ?? lockfile,
99
- config: ctx?.config ?? config,
108
+ lockfile: ctx?.lockfile ?? null,
109
+ config: ctx?.config ?? null,
100
110
  cwd: '',
101
111
  idCounter: 0
102
112
  })
package/src/core/magic.ts CHANGED
@@ -15,6 +15,11 @@ type Context = {
15
15
 
16
16
  export namespace CordoMagic {
17
17
 
18
+ // eslint-disable-next-line import/no-mutable-exports, prefer-const
19
+ export let globalLockfile: LockfileInternals.ParsedLockfile | null = null
20
+ // eslint-disable-next-line import/no-mutable-exports, prefer-const
21
+ export let globalConfig: ParsedCordoConfig | null = null
22
+
18
23
  const als = new AsyncLocalStorage<Context>()
19
24
 
20
25
  export namespace Internals {
@@ -31,38 +36,52 @@ export namespace CordoMagic {
31
36
 
32
37
  //
33
38
 
39
+ /** check if the current code is running in a cordo context */
34
40
  export function inContext() {
35
41
  return !!als.getStore()
36
42
  }
37
43
 
44
+ /** get the current lockfile, if any */
38
45
  export function getLockfile() {
39
- return Internals.getCtx().lockfile
46
+ return Internals.getCtx()?.lockfile ?? globalLockfile
40
47
  }
41
48
 
49
+ /** get the current config, if any */
42
50
  export function getConfig() {
43
- return Internals.getCtx().config
51
+ return Internals.getCtx()?.config ?? globalConfig
44
52
  }
45
53
 
54
+ /** get the current evoker, if in a context */
46
55
  export function getInvoker() {
47
- return Internals.getCtx().invoker
56
+ return Internals.getCtx()?.invoker ?? null
48
57
  }
49
58
 
59
+ /** get the current working directory, if in a context */
50
60
  export function getCwd() {
51
- return Internals.getCtx().cwd
61
+ return Internals.getCtx()?.cwd ?? ''
52
62
  }
53
63
 
64
+ /** set the current working directory, if in a context */
54
65
  export function setCwd(path: string) {
55
- Internals.getCtx().cwd = path
66
+ if (Internals.getCtx())
67
+ Internals.getCtx().cwd = path
56
68
  return path
57
69
  }
58
70
 
71
+ /** reset the id counter, if in a context */
59
72
  export function resetIdCounter() {
60
- return Internals.getCtx().idCounter = 0
73
+ if (Internals.getCtx())
74
+ Internals.getCtx().idCounter = 0
61
75
  }
62
76
 
77
+ /** request a new id, if in a context */
63
78
  export function requestNewId<T extends boolean>(asString: T): T extends true ? string : number {
79
+ if (!Internals.getCtx())
80
+ throw new Error('Not in a Cordo context')
81
+
64
82
  const id = ++Internals.getCtx().idCounter
65
- if (!asString) return id as any
83
+ if (!asString)
84
+ return id as any
66
85
  return LibIds.stringify(id, 1) as any
67
86
  }
68
87
 
@@ -1,3 +1,4 @@
1
+ import { randomBytes } from "node:crypto"
1
2
  import { LockfileInternals } from "../core/files/lockfile"
2
3
  import { CordoMagic } from "../core/magic"
3
4
  import { RoutingResolve } from "../core/routing/resolve"
@@ -26,6 +27,12 @@ export namespace FunctCompiler {
26
27
  export function toCustomId(funct: CordoFunct | Array<CordoFunct | null>): string {
27
28
  const list = (Array.isArray(funct) ? funct : [ funct ]).filter(Boolean) as CordoFunct[]
28
29
 
30
+ if (CordoMagic.getConfig()?.headless) {
31
+ if (list.length > 0 && !CordoMagic.getConfig()?.omitWarnings.includes('headlessCustomIdGeneration'))
32
+ console.warn('You are rendering a component with functs assigned while in headless mode. Your functs will not register.')
33
+ return NoopIndicator + '_headless_' + randomBytes(6).toString('hex')
34
+ }
35
+
29
36
  const idc = CordoMagic.requestNewId(true)
30
37
  if (list.length === 0)
31
38
  return NoopIndicator + idc
@@ -68,7 +75,7 @@ export namespace FunctCompiler {
68
75
  if (!lut)
69
76
  console.warn('toCustomId called without a lockfile.')
70
77
  // throw new MissingContextError('toCustomId failed, no lockfile found in context.')
71
-
78
+
72
79
  let argusStr = ''
73
80
  let counter = -1
74
81
  for (const arg of LibUtils.iterate(argus, extraValues)) {
@@ -172,6 +179,9 @@ export namespace FunctCompiler {
172
179
  }
173
180
 
174
181
  const argRaw = argsRaw.shift()!
182
+ if (!argRaw)
183
+ return path.join('/')
184
+
175
185
  const parsed = parseArg(argRaw, parsedArguments)
176
186
  path.push(parsed)
177
187
  parsedArguments.push(parsed)
package/src/lib/ids.ts CHANGED
@@ -16,7 +16,8 @@ export namespace LibIds {
16
16
  const maxId = (1<<31 - 1) * 2 - 1
17
17
 
18
18
  export function stringify(id: number, length: number) {
19
- if (id > maxId) throw new Error(`Id ${id} is larger than 31 bits`)
19
+ if (id > maxId)
20
+ throw new Error(`Id ${id} is larger than 31 bits`)
20
21
  let out = ''
21
22
  for (let i = 0; i < length; i++)
22
23
  out += bitSet[(id >> (size*i)) & bitMap]