@overmvp/kumi 0.0.0-stage → 0.1.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 (205) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +14 -2
  3. package/animation/color-transition.ts +196 -0
  4. package/animation/cycle.ts +151 -0
  5. package/animation/ease.ts +29 -0
  6. package/animation/index.ts +13 -0
  7. package/animation/package.json +12 -0
  8. package/animation/presets.ts +376 -0
  9. package/animation/spec.ts +197 -0
  10. package/builder/Cargo.lock +192 -0
  11. package/builder/Cargo.toml +7 -0
  12. package/builder/css-v1.mjs +334 -0
  13. package/builder/css-v1.test.mjs +321 -0
  14. package/builder/generated-output.mjs +61 -0
  15. package/builder/generated-output.test.mjs +132 -0
  16. package/builder/jsx-form.mjs +93 -0
  17. package/builder/jsx-form.test.mjs +48 -0
  18. package/builder/jsx-lists.mjs +209 -0
  19. package/builder/link-addon-package.mjs +86 -0
  20. package/builder/lua-assets.mjs +74 -0
  21. package/builder/lua-builtin-values.mjs +57 -0
  22. package/builder/lua-builtin-values.test.mjs +155 -0
  23. package/builder/lua-loop-closures.mjs +183 -0
  24. package/builder/lua-loop-closures.test.mjs +89 -0
  25. package/builder/lua-truthiness.mjs +61 -0
  26. package/builder/lua-truthiness.test.mjs +113 -0
  27. package/builder/module-declarations.mjs +594 -0
  28. package/builder/module-declarations.test.mjs +444 -0
  29. package/builder/native-kernels.mjs +60 -0
  30. package/builder/native-lua.d.ts +57 -0
  31. package/builder/native-routes.mjs +51 -0
  32. package/builder/no-static-ref-read.mjs +93 -0
  33. package/builder/no-static-ref-read.test.mjs +181 -0
  34. package/builder/secure-snippet.mjs +317 -0
  35. package/builder/secure-snippet.test.mjs +101 -0
  36. package/builder/shared-lua-runtime.mjs +150 -0
  37. package/builder/src/addon-link.lua +29 -0
  38. package/builder/src/arrays.lua +260 -0
  39. package/builder/src/assets.rs +177 -0
  40. package/builder/src/classes.lua +75 -0
  41. package/builder/src/collections.lua +190 -0
  42. package/builder/src/compiler.rs +2164 -0
  43. package/builder/src/config.rs +42 -0
  44. package/builder/src/entries.rs +166 -0
  45. package/builder/src/errors.lua +15 -0
  46. package/builder/src/lua_data.rs +231 -0
  47. package/builder/src/main.rs +367 -0
  48. package/builder/src/native_ir.rs +65 -0
  49. package/builder/src/native_signal.rs +47 -0
  50. package/builder/src/numbers.lua +62 -0
  51. package/builder/src/project-front.mjs +3331 -0
  52. package/builder/src/records.lua +75 -0
  53. package/builder/src/routes.rs +127 -0
  54. package/builder/src/signal-kernel.fingerprint +1 -0
  55. package/builder/src/strings.lua +103 -0
  56. package/builder/src/ts-lower.mjs +68 -0
  57. package/builder/src/wow_client.rs +253 -0
  58. package/builder/src/wow_types.rs +564 -0
  59. package/builder/style-states.mjs +100 -0
  60. package/builder/style-states.test.mjs +103 -0
  61. package/builder/vite-assets.mjs +53 -0
  62. package/builder/vite-project.mjs +10 -0
  63. package/config.ts +17 -0
  64. package/form/index.ts +522 -0
  65. package/form/package.json +13 -0
  66. package/motion/index.ts +2 -0
  67. package/motion/package.json +10 -0
  68. package/package.json +22 -4
  69. package/router/index.ts +43 -0
  70. package/router/package.json +12 -0
  71. package/router/routes.ts +64 -0
  72. package/scripts/kumi-cli.mjs +70 -0
  73. package/scripts/link-addons.mjs +51 -0
  74. package/src/bindings.ts +35 -0
  75. package/src/context.ts +15 -0
  76. package/src/css-tokens.ts +234 -0
  77. package/src/css-v1.ts +58 -0
  78. package/src/cvars.ts +91 -0
  79. package/src/element-node.ts +32 -0
  80. package/src/elements.ts +479 -0
  81. package/src/feature-scope.ts +82 -0
  82. package/src/flex-layout.ts +807 -0
  83. package/src/frame-scheduler.ts +334 -0
  84. package/src/grid-tracks.ts +165 -0
  85. package/src/image-imports.d.ts +24 -0
  86. package/src/images.ts +79 -0
  87. package/src/index.ts +28 -0
  88. package/src/jsx-dev-runtime.ts +2 -0
  89. package/src/jsx-runtime.ts +22 -0
  90. package/src/jsx.d.ts +12 -0
  91. package/src/keyed-list.ts +363 -0
  92. package/src/media-query.ts +144 -0
  93. package/src/module.ts +277 -0
  94. package/src/node-selectors.ts +114 -0
  95. package/src/owned-collections.ts +44 -0
  96. package/src/providers.ts +235 -0
  97. package/src/reactive-scope.ts +34 -0
  98. package/src/reactivity.ts +254 -0
  99. package/src/result.ts +58 -0
  100. package/src/runtime.ts +52 -0
  101. package/src/scheduler.ts +185 -0
  102. package/src/signal-kernel.ts +30 -0
  103. package/src/style-classes.ts +51 -0
  104. package/src/style-states.ts +134 -0
  105. package/src/style-variables.ts +53 -0
  106. package/src/text-children.ts +42 -0
  107. package/src/theme.ts +50 -0
  108. package/src/transition.ts +18 -0
  109. package/state/index.ts +3 -0
  110. package/state/package.json +12 -0
  111. package/state/store-bindings.ts +25 -0
  112. package/state/store.ts +82 -0
  113. package/styles/_layers.scss +14 -0
  114. package/templates/addon/README.md +14 -0
  115. package/templates/addon/__ADDON_NAME__.toc +4 -0
  116. package/templates/addon/eslint.config.mjs +12 -0
  117. package/templates/addon/gitignore +8 -0
  118. package/templates/addon/package.json +21 -0
  119. package/templates/addon/scripts/build.mjs +25 -0
  120. package/templates/addon/src/app/main.tsx +13 -0
  121. package/templates/addon/tsconfig.json +24 -0
  122. package/translate/index.ts +14 -0
  123. package/translate/package.json +9 -0
  124. package/utils/colors.ts +76 -0
  125. package/utils/format.ts +37 -0
  126. package/utils/index.ts +4 -0
  127. package/utils/number.ts +17 -0
  128. package/utils/package.json +7 -0
  129. package/utils/text.ts +6 -0
  130. package/validate/index.ts +119 -0
  131. package/validate/package.json +9 -0
  132. package/wow/absolute-position.ts +142 -0
  133. package/wow/animation.ts +428 -0
  134. package/wow/aura-button.ts +76 -0
  135. package/wow/aura-container.ts +591 -0
  136. package/wow/aura-countdown.ts +201 -0
  137. package/wow/aura-slot.ts +153 -0
  138. package/wow/bar-shade.ts +93 -0
  139. package/wow/borrowed-slot.ts +216 -0
  140. package/wow/button-drag.ts +48 -0
  141. package/wow/cast-clock.ts +153 -0
  142. package/wow/cast-text.ts +83 -0
  143. package/wow/class-colors.ts +126 -0
  144. package/wow/clock.ts +7 -0
  145. package/wow/color-picker.ts +128 -0
  146. package/wow/commands.ts +17 -0
  147. package/wow/contained-frame.ts +128 -0
  148. package/wow/contract.ts +42 -0
  149. package/wow/css-box.ts +110 -0
  150. package/wow/css-color.ts +12 -0
  151. package/wow/css-style.ts +109 -0
  152. package/wow/css-surfaces.ts +398 -0
  153. package/wow/css-text.ts +399 -0
  154. package/wow/cvar-schema.ts +32 -0
  155. package/wow/cvars.ts +98 -0
  156. package/wow/dropdown-art.ts +39 -0
  157. package/wow/element-click.ts +20 -0
  158. package/wow/element-event-coordinator.ts +219 -0
  159. package/wow/element-events.ts +317 -0
  160. package/wow/event-dispatcher.ts +151 -0
  161. package/wow/events.ts +50 -0
  162. package/wow/font-cache.ts +92 -0
  163. package/wow/frame-access.ts +31 -0
  164. package/wow/frame-layer.ts +5 -0
  165. package/wow/frames.ts +236 -0
  166. package/wow/heal-prediction.ts +305 -0
  167. package/wow/image-layers.ts +55 -0
  168. package/wow/index.ts +97 -0
  169. package/wow/layout-view.ts +651 -0
  170. package/wow/lua-string.ts +18 -0
  171. package/wow/lua-table.ts +18 -0
  172. package/wow/macro-book.ts +84 -0
  173. package/wow/map-position.ts +27 -0
  174. package/wow/media-query.ts +65 -0
  175. package/wow/module-events.ts +11 -0
  176. package/wow/native-hooks.ts +168 -0
  177. package/wow/native-placement.ts +88 -0
  178. package/wow/native.ts +135 -0
  179. package/wow/number-format.ts +8 -0
  180. package/wow/number-input.ts +10 -0
  181. package/wow/protect.ts +24 -0
  182. package/wow/protected-layout.ts +133 -0
  183. package/wow/range-art.ts +74 -0
  184. package/wow/reparent-frame.ts +99 -0
  185. package/wow/rounded-texture.ts +156 -0
  186. package/wow/saved-variables.ts +60 -0
  187. package/wow/scroll-view.ts +64 -0
  188. package/wow/secret-ref.ts +14 -0
  189. package/wow/secure-bindings.ts +89 -0
  190. package/wow/secure-clicks.ts +432 -0
  191. package/wow/secure-snippet.ts +235 -0
  192. package/wow/secure-state.ts +130 -0
  193. package/wow/secure-target-visibility.ts +89 -0
  194. package/wow/secure-transaction.ts +331 -0
  195. package/wow/special-window.ts +269 -0
  196. package/wow/start-addon.ts +99 -0
  197. package/wow/state-paint.ts +256 -0
  198. package/wow/transition.ts +86 -0
  199. package/wow/unit-button.ts +39 -0
  200. package/wow/unit-cast.ts +92 -0
  201. package/wow/unit-health-text.ts +47 -0
  202. package/wow/view-nodes.ts +304 -0
  203. package/wow/view.ts +1746 -0
  204. package/wow/visible-frame-job.ts +34 -0
  205. package/wow/width-reserve.ts +108 -0
@@ -0,0 +1,564 @@
1
+ use crate::lua_data::{self, Table};
2
+ use std::collections::{BTreeMap, BTreeSet};
3
+ use std::fmt::Write as _;
4
+ use std::fs;
5
+ use std::io;
6
+ use std::path::Path;
7
+
8
+ pub const DIRECTORY: &str = "blizzard_apidocumentationgenerated";
9
+ const TOC: &str = "blizzard_apidocumentationgenerated.toc";
10
+
11
+ fn invalid(message: impl Into<String>) -> io::Error {
12
+ io::Error::new(io::ErrorKind::InvalidData, message.into())
13
+ }
14
+
15
+ pub fn load(directory: &Path) -> io::Result<Vec<Table>> {
16
+ let mut files = BTreeMap::new();
17
+ for entry in fs::read_dir(directory)? {
18
+ let entry = entry?;
19
+ let name = entry.file_name().to_string_lossy().to_ascii_lowercase();
20
+ if entry.file_type()?.is_file() {
21
+ files.insert(name, entry.path());
22
+ }
23
+ }
24
+ let toc = files.get(TOC).ok_or_else(|| {
25
+ invalid(format!(
26
+ "Missing Blizzard API TOC in {}",
27
+ directory.display()
28
+ ))
29
+ })?;
30
+ let text = fs::read_to_string(toc)?;
31
+ let listed: Vec<_> = text
32
+ .lines()
33
+ .map(str::trim)
34
+ .filter(|line| !line.starts_with('#') && line.to_ascii_lowercase().ends_with(".lua"))
35
+ .collect();
36
+ let missing: Vec<_> = listed
37
+ .iter()
38
+ .filter(|line| !files.contains_key(&line.to_ascii_lowercase()))
39
+ .collect();
40
+ if !missing.is_empty() {
41
+ return Err(invalid(format!(
42
+ "Incomplete Blizzard API documentation ({} missing): {:?}",
43
+ missing.len(),
44
+ &missing[..missing.len().min(8)]
45
+ )));
46
+ }
47
+ if listed.is_empty() {
48
+ return Err(invalid("The Blizzard API TOC lists no Lua documentation"));
49
+ }
50
+ listed
51
+ .into_iter()
52
+ .map(|line| {
53
+ let path = &files[&line.to_ascii_lowercase()];
54
+ let data = fs::read_to_string(path)?;
55
+ lua_data::documentation(&data)
56
+ .map_err(|error| invalid(format!("{}: {error}", path.display())))
57
+ })
58
+ .collect()
59
+ }
60
+
61
+ fn identifier(name: &str) -> bool {
62
+ let mut chars = name.bytes();
63
+ chars
64
+ .next()
65
+ .is_some_and(|b| b.is_ascii_alphabetic() || b == b'_')
66
+ && chars.all(|b| b.is_ascii_alphanumeric() || b == b'_')
67
+ }
68
+
69
+ fn argument_name(field: &Table, used: &mut BTreeSet<String>, index: usize) -> String {
70
+ let name = field.text("Name").unwrap_or("value");
71
+ let name = if identifier(name) { name } else { "value" };
72
+ let mut result = if matches!(
73
+ name,
74
+ "this"
75
+ | "class"
76
+ | "default"
77
+ | "function"
78
+ | "new"
79
+ | "const"
80
+ | "var"
81
+ | "let"
82
+ | "import"
83
+ | "export"
84
+ | "return"
85
+ | "switch"
86
+ | "case"
87
+ | "in"
88
+ | "enum"
89
+ | "delete"
90
+ | "if"
91
+ | "else"
92
+ | "for"
93
+ | "while"
94
+ | "do"
95
+ | "try"
96
+ | "catch"
97
+ | "throw"
98
+ | "finally"
99
+ | "extends"
100
+ | "typeof"
101
+ | "yield"
102
+ | "await"
103
+ | "static"
104
+ | "with"
105
+ | "void"
106
+ | "break"
107
+ | "continue"
108
+ | "debugger"
109
+ | "null"
110
+ | "true"
111
+ | "false"
112
+ | "instanceof"
113
+ | "super"
114
+ | "private"
115
+ | "protected"
116
+ | "public"
117
+ | "package"
118
+ | "interface"
119
+ | "implements"
120
+ | "arguments"
121
+ | "eval"
122
+ ) {
123
+ format!("_{name}")
124
+ } else {
125
+ name.to_owned()
126
+ };
127
+ while !used.insert(result.clone()) {
128
+ let _ = write!(result, "{}", index + 1);
129
+ }
130
+ result
131
+ }
132
+
133
+ const WIDGETS: &[(&str, &[&str])] = &[
134
+ (
135
+ "SimpleObject",
136
+ &["SimpleObjectAPI", "SimpleFrameScriptObjectAPI"],
137
+ ),
138
+ ("SimpleRegion", &["SimpleRegionAPI", "SimpleObject"]),
139
+ (
140
+ "SimpleFrame",
141
+ &[
142
+ "SimpleFrameAPI",
143
+ "SimpleRegion",
144
+ "SimpleScriptRegionAPI",
145
+ "SimpleScriptRegionResizingAPI",
146
+ ],
147
+ ),
148
+ ("SimpleButton", &["SimpleButtonAPI", "SimpleFrame"]),
149
+ ("SimpleCheckbox", &["SimpleCheckboxAPI", "SimpleButton"]),
150
+ ("SimpleFontString", &["SimpleFontStringAPI", "SimpleRegion"]),
151
+ (
152
+ "SimpleTexture",
153
+ &["SimpleTextureAPI", "SimpleTextureBaseAPI", "SimpleRegion"],
154
+ ),
155
+ (
156
+ "SimpleMaskTexture",
157
+ &[
158
+ "SimpleMaskTextureAPI",
159
+ "SimpleTextureBaseAPI",
160
+ "SimpleRegion",
161
+ ],
162
+ ),
163
+ (
164
+ "SimpleLine",
165
+ &["SimpleLineAPI", "SimpleTextureBaseAPI", "SimpleRegion"],
166
+ ),
167
+ ("SimpleFont", &["SimpleFontAPI", "SimpleObject"]),
168
+ ("SimpleEditBox", &["SimpleEditBoxAPI", "SimpleFrame"]),
169
+ ("SimpleSlider", &["SimpleSliderAPI", "SimpleFrame"]),
170
+ ("SimpleStatusBar", &["SimpleStatusBarAPI", "SimpleFrame"]),
171
+ (
172
+ "SimpleScrollFrame",
173
+ &["SimpleScrollFrameAPI", "SimpleFrame"],
174
+ ),
175
+ (
176
+ "SimpleMessageFrame",
177
+ &["SimpleMessageFrameAPI", "SimpleFrame"],
178
+ ),
179
+ ("SimpleModel", &["SimpleModelAPI", "SimpleFrame"]),
180
+ ("SimpleHTML", &["SimpleHTMLAPI", "SimpleFrame"]),
181
+ ("Cooldown", &["FrameAPICooldown", "SimpleFrame"]),
182
+ ("GameTooltip", &["FrameAPITooltip", "SimpleFrame"]),
183
+ ];
184
+
185
+ struct Types<'a> {
186
+ named: BTreeMap<&'a str, &'a Table>,
187
+ methods: BTreeMap<&'a str, &'a Table>,
188
+ unknown: BTreeSet<String>,
189
+ }
190
+
191
+ impl Types<'_> {
192
+ fn value(&mut self, name: &str, field: &Table) -> String {
193
+ match name {
194
+ "number" | "luaIndex" | "uiUnit" | "fileID" | "textureFileID" | "time_t" | "Seconds"
195
+ | "Milliseconds" | "ClubId" | "BigUInteger" | "FrameAlpha" | "UnitCastBarID" => "number".into(),
196
+ "bool" | "boolean" => "boolean".into(),
197
+ "string" | "cstring" | "stringView" | "WOWGUID" | "UnitToken" | "UnitTokenVariant"
198
+ | "textureKit" | "textureAtlas" | "SimpleButtonStateToken" => "string".into(),
199
+ "SpellIdentifier" => "number | string".into(),
200
+ "DrawLayer" => r#""BACKGROUND" | "BORDER" | "ARTWORK" | "OVERLAY" | "HIGHLIGHT""#.into(),
201
+ "FramePoint" => r#""TOP" | "BOTTOM" | "LEFT" | "RIGHT" | "CENTER" | "TOPLEFT" | "TOPRIGHT" | "BOTTOMLEFT" | "BOTTOMRIGHT""#.into(),
202
+ "table" | "LuaValueVariant" if field.text("InnerType").is_some() => {
203
+ format!("({})[]", self.value(field.text("InnerType").unwrap(), &Table::default()))
204
+ }
205
+ "table" => "Record<string | number, unknown>".into(),
206
+ "function" | "LuaFunction" => "(this: void, ...args: never[]) => unknown".into(),
207
+ "LuaValueVariant" | "LuaValue" | "any" | "userdata" => "unknown".into(),
208
+ "void" | "nil" => "undefined".into(),
209
+ _ if WIDGETS.iter().any(|(widget, _)| *widget == name) => name.into(),
210
+ _ if self.methods.contains_key(name) => name.into(),
211
+ _ if self.methods.contains_key(format!("{name}API").as_str()) => format!("{name}API"),
212
+ _ if self.named.contains_key(name) => format!("Data_{name}"),
213
+ _ => {
214
+ self.unknown.insert(name.to_owned());
215
+ "unknown".into()
216
+ }
217
+ }
218
+ }
219
+
220
+ fn field(&mut self, field: &Table, secret: bool, nilable: bool) -> String {
221
+ let value = self.value(field.text("Type").unwrap_or("any"), field);
222
+ if value == "unknown" {
223
+ return value;
224
+ }
225
+ let secret = (secret || field.flag("ConditionalSecret") || field.flag("SecretValue"))
226
+ && !field.flag("NeverSecret");
227
+ let value = if secret {
228
+ format!("{value} | SecretValue<{value}>")
229
+ } else {
230
+ value
231
+ };
232
+ if nilable {
233
+ format!("{value} | undefined")
234
+ } else {
235
+ value
236
+ }
237
+ }
238
+
239
+ fn tuple(&mut self, fields: &[&Table], secret: bool, may_return_nothing: bool) -> String {
240
+ let last_required = fields
241
+ .iter()
242
+ .rposition(|field| !field.flag("Nilable") && !field.has("Default"));
243
+ let mut used = BTreeSet::new();
244
+ fields
245
+ .iter()
246
+ .enumerate()
247
+ .map(|(index, field)| {
248
+ let name = argument_name(field, &mut used, index);
249
+ let value = self.field(field, secret, may_return_nothing || field.flag("Nilable"));
250
+ let optional = last_required.is_none_or(|last| index > last) && !may_return_nothing;
251
+ if field.has("StrideIndex") {
252
+ // A homogeneous Lua variadic return is represented as a rest tuple.
253
+ format!("...{name}: ({value})[]")
254
+ } else {
255
+ format!("{name}{}: {value}", if optional { "?" } else { "" })
256
+ }
257
+ })
258
+ .collect::<Vec<_>>()
259
+ .join(", ")
260
+ }
261
+
262
+ fn method(&mut self, item: &Table, owner: &str) -> String {
263
+ let args: Vec<_> = item.list("Arguments").collect();
264
+ let returns: Vec<_> = item.list("Returns").collect();
265
+ let conditional = secret_rule(item);
266
+ let may_return_nothing = item.flag("MayReturnNothing");
267
+ let mut arguments = self.tuple(&args, false, false);
268
+ arguments.insert_str(
269
+ 0,
270
+ &format!(
271
+ "this: {owner}{}",
272
+ if arguments.is_empty() { "" } else { ", " }
273
+ ),
274
+ );
275
+ let returns = match returns.as_slice() {
276
+ [] => "void".to_owned(),
277
+ [only] if !only.has("StrideIndex") => self.field(
278
+ only,
279
+ conditional,
280
+ may_return_nothing || only.flag("Nilable"),
281
+ ),
282
+ _ => {
283
+ let stride_count = returns
284
+ .iter()
285
+ .filter(|field| field.has("StrideIndex"))
286
+ .count();
287
+ let fixed = returns
288
+ .iter()
289
+ .copied()
290
+ .take_while(|field| !field.has("StrideIndex"))
291
+ .collect::<Vec<_>>();
292
+ let tuple = if stride_count > 1 {
293
+ let prefix = self.tuple(&fixed, conditional, may_return_nothing);
294
+ format!(
295
+ "{prefix}{}...rest: unknown[]",
296
+ if prefix.is_empty() { "" } else { ", " }
297
+ )
298
+ } else {
299
+ self.tuple(&returns, conditional, may_return_nothing)
300
+ };
301
+ format!("LuaMultiReturn<[{tuple}]>")
302
+ }
303
+ };
304
+ let mut result = String::new();
305
+ let mut notes = Vec::new();
306
+ if item.flag("IsProtectedFunction") || item.flag("HasRestrictions") {
307
+ notes.push("Restricted by the WoW client.");
308
+ }
309
+ if conditional {
310
+ notes.push("Can return secret values.");
311
+ }
312
+ if !notes.is_empty() {
313
+ let _ = writeln!(result, " /** {} */", notes.join(" "));
314
+ }
315
+ let _ = writeln!(
316
+ result,
317
+ " {:?}({arguments}): {returns};",
318
+ item.text("Name").unwrap()
319
+ );
320
+ result
321
+ }
322
+ }
323
+
324
+ fn secret_rule(item: &Table) -> bool {
325
+ !item.flag("ReturnsNeverSecret")
326
+ && (item.has_prefix("SecretWhen")
327
+ || item.has_prefix("SecretIn")
328
+ || item.has_prefix("SecretReturns")
329
+ || item.flag("SecretPayloads"))
330
+ }
331
+
332
+ pub fn generate(systems: &[Table], origin: &str) -> (String, usize, usize) {
333
+ let mut types = Types {
334
+ named: BTreeMap::new(),
335
+ methods: BTreeMap::new(),
336
+ unknown: BTreeSet::new(),
337
+ };
338
+ let mut functions: BTreeMap<&str, BTreeMap<&str, &Table>> = BTreeMap::new();
339
+ let mut events: BTreeMap<&str, Vec<&Table>> = BTreeMap::new();
340
+ for system in systems {
341
+ for item in system.list("Tables") {
342
+ if let Some(name) = item.text("Name").filter(|name| identifier(name)) {
343
+ types.named.entry(name).or_insert(item);
344
+ }
345
+ }
346
+ if system.text("Environment") == Some("Glue") {
347
+ continue;
348
+ }
349
+ for event in system.list("Events") {
350
+ if let Some(name) = event.text("LiteralName") {
351
+ events.entry(name).or_default().push(event);
352
+ }
353
+ }
354
+ if system.text("Type") == Some("ScriptObject") {
355
+ if let Some(name) = system.text("Name").filter(|name| identifier(name)) {
356
+ types.methods.insert(name, system);
357
+ }
358
+ } else if system.text("Type") == Some("System") {
359
+ for item in system.list("Functions") {
360
+ if let Some(name) = item.text("Name") {
361
+ let namespace = item
362
+ .text("Namespace")
363
+ .or_else(|| system.text("Namespace"))
364
+ .unwrap_or("");
365
+ functions
366
+ .entry(namespace)
367
+ .or_default()
368
+ .entry(name)
369
+ .or_insert(item);
370
+ }
371
+ }
372
+ }
373
+ }
374
+ let mut out = format!("// Generated by kumi-pack from {origin}.\n// This file is a compile-time description of Lua, with no JS runtime.\n\n");
375
+ out.push_str("export type LuaMultiReturn<T extends unknown[]> = T & { readonly __tstlMultiReturn: never };\n");
376
+ out.push_str("declare const secret: unique symbol;\nexport type SecretValue<T = unknown> = { readonly [secret]: T };\n\n");
377
+ for (name, item) in types.named.clone() {
378
+ match item.text("Type") {
379
+ Some("Structure") => {
380
+ let _ = writeln!(out, "export interface Data_{name} {{");
381
+ for field in item.list("Fields") {
382
+ if let Some(key) = field.text("Name") {
383
+ let optional = if field.flag("Nilable") { "?" } else { "" };
384
+ let value = types.field(field, false, false);
385
+ let _ = writeln!(out, " {key:?}{optional}: {value};");
386
+ }
387
+ }
388
+ out.push_str("}\n");
389
+ }
390
+ Some("Enumeration") => {
391
+ let _ = writeln!(out, "export type Data_{name} = number;");
392
+ }
393
+ Some("CallbackType") => {
394
+ let args: Vec<_> = item.list("Arguments").collect();
395
+ let args = types.tuple(&args, false, false);
396
+ let _ = writeln!(
397
+ out,
398
+ "export type Data_{name} = (this: void{}{}) => void;",
399
+ if args.is_empty() { "" } else { ", " },
400
+ args
401
+ );
402
+ }
403
+ _ => {
404
+ let _ = writeln!(out, "export type Data_{name} = unknown;");
405
+ }
406
+ }
407
+ }
408
+ for (name, system) in types.methods.clone() {
409
+ let _ = writeln!(out, "export interface {name} {{");
410
+ for item in system
411
+ .list("Functions")
412
+ .filter(|item| item.text("Name").is_some())
413
+ {
414
+ out.push_str(&types.method(item, "object"));
415
+ }
416
+ out.push_str("}\n");
417
+ }
418
+ let widget_names: BTreeSet<_> = WIDGETS.iter().map(|(name, _)| *name).collect();
419
+ for (name, members) in WIDGETS {
420
+ let available: Vec<_> = members
421
+ .iter()
422
+ .copied()
423
+ .filter(|member| widget_names.contains(member) || types.methods.contains_key(member))
424
+ .collect();
425
+ let _ = writeln!(
426
+ out,
427
+ "export type {name} = {};",
428
+ if available.is_empty() {
429
+ "object".into()
430
+ } else {
431
+ available.join(" & ")
432
+ }
433
+ );
434
+ }
435
+ out.push_str("\nexport interface WoWGlobals {\n");
436
+ for (kind, table) in [("Enumeration", "Enum"), ("Constants", "Constants")] {
437
+ let _ = writeln!(out, " readonly {table:?}: {{");
438
+ for (name, item) in types.named.clone() {
439
+ if item.text("Type") != Some(kind) {
440
+ continue;
441
+ }
442
+ let _ = writeln!(out, " readonly {name:?}: {{");
443
+ let mut seen = BTreeSet::new();
444
+ for field in item.list("Fields") {
445
+ if let Some(key) = field.text("Name").filter(|key| seen.insert(*key)) {
446
+ let value = if kind == "Enumeration" {
447
+ "number".to_owned()
448
+ } else {
449
+ types.field(field, false, false)
450
+ };
451
+ let _ = writeln!(out, " readonly {key:?}: {value};");
452
+ }
453
+ }
454
+ out.push_str(" };\n");
455
+ }
456
+ out.push_str(" };\n");
457
+ }
458
+ let mut count = 0;
459
+ for (scope, items) in functions {
460
+ if !scope.is_empty() {
461
+ let _ = writeln!(out, " readonly {scope:?}: {{");
462
+ }
463
+ for item in items.into_values() {
464
+ out.push_str(&types.method(item, "void"));
465
+ count += 1;
466
+ }
467
+ if !scope.is_empty() {
468
+ out.push_str(" };\n");
469
+ }
470
+ }
471
+ out.push_str("}\n\nexport interface WoWEventMap {\n");
472
+ for (name, versions) in &events {
473
+ let payload: BTreeSet<_> = versions
474
+ .iter()
475
+ .map(|event| {
476
+ let fields: Vec<_> = event.list("Payload").collect();
477
+ format!("[{}]", types.tuple(&fields, secret_rule(event), false))
478
+ })
479
+ .collect();
480
+ let _ = writeln!(
481
+ out,
482
+ " {name:?}: {};",
483
+ payload.into_iter().collect::<Vec<_>>().join(" | ")
484
+ );
485
+ }
486
+ out.push_str("}\n");
487
+ if !types.unknown.is_empty() {
488
+ let _ = writeln!(
489
+ out,
490
+ "// Native types without a known TypeScript representation: {}.",
491
+ types.unknown.into_iter().collect::<Vec<_>>().join(", ")
492
+ );
493
+ }
494
+ (out, count, events.len())
495
+ }
496
+
497
+ fn signatures(source: &str) -> BTreeMap<String, String> {
498
+ let mut signatures = BTreeMap::new();
499
+ let mut sections = Vec::new();
500
+ let mut note = "";
501
+ for line in source.lines() {
502
+ let line = line.trim();
503
+ if let Some(name) = line
504
+ .strip_prefix("export interface ")
505
+ .and_then(|line| line.strip_suffix(" {"))
506
+ {
507
+ sections.push(name);
508
+ signatures.insert(name.to_owned(), line.to_owned());
509
+ } else if let Some((name, _)) = line
510
+ .strip_prefix("export type ")
511
+ .and_then(|line| line.split_once(" = "))
512
+ {
513
+ signatures.insert(name.to_owned(), line.to_owned());
514
+ } else if line == "};" || line == "}" {
515
+ sections.pop();
516
+ } else if line.starts_with("/**") {
517
+ note = line;
518
+ } else if let Some((name, _)) = line
519
+ .strip_prefix("readonly ")
520
+ .unwrap_or(line)
521
+ .strip_prefix('"')
522
+ .and_then(|line| line.split_once('"'))
523
+ {
524
+ signatures.insert(
525
+ format!("{}.{name}", sections.join(".")),
526
+ format!("{note}{line}"),
527
+ );
528
+ if line.ends_with(": {") {
529
+ sections.push(name);
530
+ }
531
+ note = "";
532
+ }
533
+ }
534
+ signatures
535
+ }
536
+
537
+ pub fn report_changes(before: &str, after: &str) {
538
+ let old = signatures(before);
539
+ let new = signatures(after);
540
+ let mut added = 0;
541
+ let mut removed = 0;
542
+ let mut changed = 0;
543
+ for name in old
544
+ .keys()
545
+ .chain(new.keys().filter(|name| !old.contains_key(*name)))
546
+ {
547
+ match (old.get(name), new.get(name)) {
548
+ (Some(_), None) => {
549
+ println!("- {name}");
550
+ removed += 1;
551
+ }
552
+ (None, Some(_)) => {
553
+ println!("+ {name}");
554
+ added += 1;
555
+ }
556
+ (Some(old), Some(new)) if old != new => {
557
+ println!("~ {name}");
558
+ changed += 1;
559
+ }
560
+ _ => {}
561
+ }
562
+ }
563
+ println!("WoW API diff: {added} added, {removed} removed, {changed} changed");
564
+ }
@@ -0,0 +1,100 @@
1
+ const localClass = /^\.([a-z][a-zA-Z0-9]*)$/;
2
+ const styleStates = new Set(["hover", "active", "focus", "disabled", "checked"]);
3
+ const hexColor = /^#[0-9a-f]{6}(?:[0-9a-f]{2})?$/i;
4
+ const rgbaColor = /^rgba\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d*\.?\d+)\s*\)$/i;
5
+ const opacity = /^(?:0(?:\.\d+)?|1(?:\.0+)?)$/;
6
+ const tokenReference = /^var\((--[a-z][\w-]*)\)$/;
7
+ const textureUrl = /^url\(\s*(["'])([^"']+)\1\s*\)$/;
8
+ const textureAtlas = /^atlas\(\s*(?:([\w-]+)|(["'])([\w-]+)\2)\s*\)$/;
9
+ const pathSegment = /^[\w-](?:[\w. -]*[\w-])?$/;
10
+
11
+ export function parseLocalStyleSelector(selector) {
12
+ const [base, ...when] = selector.split(":");
13
+ const match = localClass.exec(base);
14
+ if (!match) throw new Error("Expected a single local class in camelCase");
15
+
16
+ const seen = new Set();
17
+ for (const state of when) {
18
+ if (!styleStates.has(state)) throw new Error(`Unsupported style state :${state}`);
19
+ if (seen.has(state)) throw new Error(`Duplicate style state :${state}`);
20
+ seen.add(state);
21
+ }
22
+ return { name: match[1], when };
23
+ }
24
+
25
+ function parseBackgroundImage(value) {
26
+ const atlas = textureAtlas.exec(value);
27
+ if (atlas) return { atlas: atlas[1] ?? atlas[3] };
28
+
29
+ const path = textureUrl.exec(value)?.[2];
30
+ if (path === undefined) return;
31
+ const relative = path.startsWith("./") ? path.slice(2) : path;
32
+ if (relative.split("/").every(segment => pathSegment.test(segment))) return { path };
33
+ }
34
+
35
+ export function parseStyleColor(value) {
36
+ if (hexColor.test(value)) return value;
37
+ const rgba = rgbaColor.exec(value);
38
+ if (!rgba) return;
39
+ const [red, green, blue, alpha] = rgba.slice(1).map(Number);
40
+ if (red > 255 || green > 255 || blue > 255 || alpha > 1) return;
41
+ const bytes = alpha === 1 ? [red, green, blue] : [red, green, blue, alpha * 255];
42
+ return "#" + bytes.map(channel => Math.round(channel).toString(16).padStart(2, "0")).join("");
43
+ }
44
+
45
+ function stateOpacity(value) {
46
+ if (opacity.test(value)) return Number(value);
47
+ }
48
+
49
+ const stateProperties = {
50
+ color: ["color", parseStyleColor],
51
+ "background-color": ["backgroundColor", parseStyleColor],
52
+ "border-color": ["borderColor", parseStyleColor],
53
+ opacity: ["opacity", stateOpacity],
54
+ "background-image": ["backgroundImage", parseBackgroundImage],
55
+ };
56
+
57
+ export function supportsStateProperty(property) {
58
+ return Object.hasOwn(stateProperties, property);
59
+ }
60
+
61
+ export function parseStateDeclaration(property, input, tokens) {
62
+ if (!supportsStateProperty(property)) {
63
+ throw new Error(`Unsupported property ${property} in a style state`);
64
+ }
65
+ const [key, parse] = stateProperties[property];
66
+ const token = tokenReference.exec(input)?.[1];
67
+ if (token && !tokens?.has(token)) throw new Error(`Unknown token ${token}`);
68
+
69
+ const value = parse(token ? tokens.get(token) : input);
70
+ if (value === undefined) throw new Error(`Invalid value for ${property}: ${input}`);
71
+ return [key, token && parse === parseStyleColor ? `var(${token}, ${value})` : value];
72
+ }
73
+
74
+ // A stable sort preserves declaration order when specificity and disabled match.
75
+ export function compareStyleStates(left, right) {
76
+ return left.when.length - right.when.length
77
+ || Number(left.when.includes("disabled")) - Number(right.when.includes("disabled"));
78
+ }
79
+
80
+ export function parseMediaQuery(condition, breakpoints) {
81
+ if (/^\(\s*prefers-reduced-motion\s*:\s*reduce\s*\)$/.test(condition)) return { reducedMotion: true };
82
+ const width = /^\(\s*(min|max)-width\s*:\s*(\d+)px\s*\)$/.exec(condition);
83
+ if (width === null) throw new Error(`Unsupported media query ${condition}`);
84
+ const breakpoint = breakpoints.get(Number(width[2]));
85
+ if (breakpoint === undefined) throw new Error(`Undefined media breakpoint ${width[2]}px`);
86
+ return width[1] === "min" ? { minWidth: breakpoint } : { maxWidth: breakpoint };
87
+ }
88
+
89
+ const mediaProperties = new Set([
90
+ "color", "background-color", "opacity", "display", "width", "height", "min-width", "min-height", "max-width", "max-height",
91
+ "top", "right", "bottom", "left", "padding", "margin", "gap", "row-gap", "column-gap", "flex-grow", "flex-shrink",
92
+ "flex-basis", "flex-direction", "justify-content", "align-items", "align-self", "justify-items", "grid-template-columns",
93
+ "grid-template-rows", "grid-column",
94
+ ]);
95
+
96
+ export function assertMediaProperties(declarations) {
97
+ for (const declaration of declarations) {
98
+ if (!mediaProperties.has(declaration.prop)) throw declaration.error(`Unsupported property ${declaration.prop} in a media query`);
99
+ }
100
+ }