@devaloop/devalang 0.0.1-alpha.16-hotfix.3 → 0.0.1-alpha.18

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 (239) hide show
  1. package/.cargo/config.toml +2 -0
  2. package/.devalang +10 -10
  3. package/.github/workflows/ci.yml +0 -1
  4. package/Cargo.toml +18 -2
  5. package/README.md +82 -34
  6. package/docs/CHANGELOG.md +91 -0
  7. package/docs/ROADMAP.md +7 -4
  8. package/docs/TODO.md +1 -1
  9. package/examples/index.deva +55 -35
  10. package/examples/pattern.deva +5 -5
  11. package/out-tsc/bin/index.d.ts +2 -0
  12. package/out-tsc/core/functions/index.d.ts +37 -0
  13. package/out-tsc/core/functions/index.js +76 -0
  14. package/out-tsc/core/index.d.ts +6 -0
  15. package/out-tsc/core/index.js +22 -0
  16. package/out-tsc/core/types/index.d.ts +4 -0
  17. package/out-tsc/core/types/index.js +20 -0
  18. package/out-tsc/core/types/plugin.d.ts +18 -0
  19. package/out-tsc/core/types/plugin.js +2 -0
  20. package/out-tsc/core/types/result.d.ts +27 -0
  21. package/out-tsc/core/types/result.js +2 -0
  22. package/out-tsc/core/types/statement.d.ts +106 -0
  23. package/out-tsc/core/types/statement.js +2 -0
  24. package/out-tsc/core/types/value.d.ts +43 -0
  25. package/out-tsc/core/types/value.js +2 -0
  26. package/out-tsc/index.d.ts +7 -0
  27. package/out-tsc/index.js +41 -2
  28. package/out-tsc/pkg/devalang_core.d.ts +7 -0
  29. package/out-tsc/pkg/devalang_core_bg.wasm.d.ts +33 -0
  30. package/out-tsc/scripts/copy-wasm-dts.d.ts +1 -0
  31. package/out-tsc/scripts/copy-wasm-dts.js +73 -0
  32. package/out-tsc/scripts/postinstall.d.ts +1 -0
  33. package/out-tsc/scripts/postinstall.js +33 -23
  34. package/out-tsc/scripts/version/bump.d.ts +1 -0
  35. package/out-tsc/scripts/version/fetch.d.ts +1 -0
  36. package/out-tsc/scripts/version/index.d.ts +1 -0
  37. package/out-tsc/scripts/version/sync.d.ts +1 -0
  38. package/package.json +16 -4
  39. package/project-version.json +3 -3
  40. package/rust/cli/bank/api.rs +122 -0
  41. package/rust/cli/bank/commands.rs +275 -0
  42. package/rust/cli/bank/mod.rs +29 -0
  43. package/rust/cli/build/commands.rs +107 -0
  44. package/rust/cli/build/mod.rs +2 -0
  45. package/rust/cli/build/process.rs +146 -0
  46. package/rust/cli/{check.rs → check/mod.rs} +18 -31
  47. package/rust/cli/discover/commands.rs +253 -0
  48. package/rust/cli/discover/config.rs +111 -0
  49. package/rust/cli/discover/fs.rs +19 -0
  50. package/rust/cli/discover/install.rs +103 -0
  51. package/rust/cli/discover/metadata.rs +48 -0
  52. package/rust/cli/discover/mod.rs +5 -0
  53. package/rust/cli/{init.rs → init/commands.rs} +88 -87
  54. package/rust/cli/init/mod.rs +1 -0
  55. package/rust/cli/install/addon.rs +126 -0
  56. package/rust/cli/install/bank.rs +53 -0
  57. package/rust/cli/{install.rs → install/commands.rs} +9 -9
  58. package/rust/{installer → cli/install}/mod.rs +2 -3
  59. package/rust/cli/install/plugin.rs +61 -0
  60. package/rust/cli/{login.rs → login/commands.rs} +8 -11
  61. package/rust/cli/login/mod.rs +1 -0
  62. package/rust/cli/mod.rs +2 -2
  63. package/rust/cli/{driver.rs → parser.rs} +7 -2
  64. package/rust/cli/play/commands.rs +324 -0
  65. package/rust/cli/play/io.rs +17 -0
  66. package/rust/cli/play/mod.rs +5 -0
  67. package/rust/cli/play/process.rs +150 -0
  68. package/rust/cli/play/realtime.rs +91 -0
  69. package/rust/cli/play/utils.rs +23 -0
  70. package/rust/cli/{telemetry.rs → telemetry/commands.rs} +4 -4
  71. package/rust/cli/telemetry/event_creator.rs +80 -0
  72. package/rust/cli/telemetry/mod.rs +3 -0
  73. package/rust/cli/telemetry/send.rs +51 -0
  74. package/rust/cli/{template.rs → template/commands.rs} +1 -1
  75. package/rust/cli/template/mod.rs +1 -0
  76. package/rust/cli/{update.rs → update/commands.rs} +6 -6
  77. package/rust/cli/update/mod.rs +1 -0
  78. package/rust/config/driver.rs +57 -72
  79. package/rust/config/mod.rs +1 -2
  80. package/rust/config/ops.rs +26 -0
  81. package/rust/config/settings.rs +40 -42
  82. package/rust/core/audio/engine/helpers.rs +158 -0
  83. package/rust/core/audio/engine/mod.rs +7 -0
  84. package/rust/core/audio/engine/sample.rs +359 -0
  85. package/rust/core/audio/engine/synth.rs +325 -0
  86. package/rust/core/audio/evaluator.rs +68 -27
  87. package/rust/core/audio/interpreter/arrow_call.rs +113 -33
  88. package/rust/core/audio/interpreter/call.rs +232 -56
  89. package/rust/core/audio/interpreter/condition.rs +3 -2
  90. package/rust/core/audio/interpreter/driver.rs +206 -151
  91. package/rust/core/audio/interpreter/let_.rs +1 -1
  92. package/rust/core/audio/interpreter/load.rs +2 -1
  93. package/rust/core/audio/interpreter/loop_.rs +7 -6
  94. package/rust/core/audio/interpreter/sleep.rs +2 -1
  95. package/rust/core/audio/interpreter/spawn.rs +186 -54
  96. package/rust/core/audio/interpreter/tempo.rs +31 -10
  97. package/rust/core/audio/interpreter/trigger.rs +2 -2
  98. package/rust/core/audio/loader/trigger.rs +4 -7
  99. package/rust/core/audio/player.rs +6 -0
  100. package/rust/core/audio/renderer.rs +5 -7
  101. package/rust/core/audio/special/env.rs +3 -1
  102. package/rust/core/audio/special/math.rs +26 -6
  103. package/rust/core/audio/special/modulator.rs +2 -2
  104. package/rust/core/builder/mod.rs +9 -3
  105. package/rust/core/debugger/lexer.rs +1 -1
  106. package/rust/core/debugger/mod.rs +6 -0
  107. package/rust/core/debugger/module.rs +4 -4
  108. package/rust/core/debugger/preprocessor.rs +1 -1
  109. package/rust/core/debugger/store.rs +2 -2
  110. package/rust/core/error/mod.rs +189 -0
  111. package/rust/core/lexer/driver.rs +61 -0
  112. package/rust/core/lexer/handler/arrow.rs +1 -1
  113. package/rust/core/lexer/handler/at.rs +1 -1
  114. package/rust/core/lexer/handler/brace.rs +2 -2
  115. package/rust/core/lexer/handler/colon.rs +1 -1
  116. package/rust/core/lexer/handler/comment.rs +1 -1
  117. package/rust/core/lexer/handler/dot.rs +1 -1
  118. package/rust/core/lexer/handler/driver.rs +1 -1
  119. package/rust/core/lexer/handler/identifier.rs +4 -3
  120. package/rust/core/lexer/handler/mod.rs +1 -2
  121. package/rust/core/lexer/handler/number.rs +1 -1
  122. package/rust/core/lexer/handler/operator.rs +1 -1
  123. package/rust/core/lexer/handler/parenthesis.rs +2 -2
  124. package/rust/core/lexer/handler/slash.rs +1 -1
  125. package/rust/core/lexer/handler/string.rs +1 -1
  126. package/rust/core/lexer/mod.rs +1 -52
  127. package/rust/core/lexer/token.rs +91 -97
  128. package/rust/core/mod.rs +0 -1
  129. package/rust/core/parser/driver.rs +78 -22
  130. package/rust/core/parser/handler/arrow_call.rs +28 -8
  131. package/rust/core/parser/handler/at.rs +55 -21
  132. package/rust/core/parser/handler/bank.rs +14 -4
  133. package/rust/core/parser/handler/condition.rs +6 -3
  134. package/rust/core/parser/handler/dot.rs +5 -3
  135. package/rust/core/parser/handler/identifier/automate.rs +13 -16
  136. package/rust/core/parser/handler/identifier/call.rs +4 -4
  137. package/rust/core/parser/handler/identifier/emit.rs +9 -5
  138. package/rust/core/parser/handler/identifier/function.rs +20 -7
  139. package/rust/core/parser/handler/identifier/group.rs +11 -7
  140. package/rust/core/parser/handler/identifier/let_.rs +24 -9
  141. package/rust/core/parser/handler/identifier/mod.rs +6 -5
  142. package/rust/core/parser/handler/identifier/on.rs +16 -7
  143. package/rust/core/parser/handler/identifier/print.rs +6 -9
  144. package/rust/core/parser/handler/identifier/sleep.rs +12 -5
  145. package/rust/core/parser/handler/identifier/spawn.rs +4 -4
  146. package/rust/core/parser/handler/identifier/synth.rs +79 -9
  147. package/rust/core/parser/handler/loop_.rs +38 -13
  148. package/rust/core/parser/handler/mod.rs +1 -0
  149. package/rust/core/parser/handler/pattern.rs +74 -0
  150. package/rust/core/parser/handler/tempo.rs +9 -5
  151. package/rust/core/parser/mod.rs +0 -1
  152. package/rust/core/parser/statement.rs +6 -137
  153. package/rust/core/plugin/loader.rs +41 -27
  154. package/rust/core/plugin/runner.rs +68 -17
  155. package/rust/core/preprocessor/loader.rs +181 -99
  156. package/rust/core/preprocessor/processor.rs +9 -9
  157. package/rust/core/preprocessor/resolver/bank.rs +6 -8
  158. package/rust/core/preprocessor/resolver/call.rs +47 -23
  159. package/rust/core/preprocessor/resolver/condition.rs +6 -8
  160. package/rust/core/preprocessor/resolver/driver.rs +28 -28
  161. package/rust/core/preprocessor/resolver/function.rs +6 -6
  162. package/rust/core/preprocessor/resolver/group.rs +6 -8
  163. package/rust/core/preprocessor/resolver/loop_.rs +8 -10
  164. package/rust/core/preprocessor/resolver/mod.rs +1 -0
  165. package/rust/core/preprocessor/resolver/pattern.rs +75 -0
  166. package/rust/core/preprocessor/resolver/spawn.rs +45 -22
  167. package/rust/core/preprocessor/resolver/synth.rs +6 -8
  168. package/rust/core/preprocessor/resolver/tempo.rs +6 -8
  169. package/rust/core/preprocessor/resolver/trigger.rs +22 -19
  170. package/rust/core/preprocessor/resolver/value.rs +99 -4
  171. package/rust/core/store/export.rs +28 -28
  172. package/rust/core/store/function.rs +6 -0
  173. package/rust/core/store/global.rs +7 -1
  174. package/rust/core/store/import.rs +28 -28
  175. package/rust/core/store/variable.rs +16 -2
  176. package/rust/core/utils/mod.rs +0 -1
  177. package/rust/lib.rs +102 -9
  178. package/rust/main.rs +159 -45
  179. package/rust/types/Cargo.toml +11 -0
  180. package/rust/types/src/addons.rs +55 -0
  181. package/rust/types/src/ast.rs +202 -0
  182. package/rust/types/src/config.rs +74 -0
  183. package/rust/types/src/lib.rs +12 -0
  184. package/rust/types/src/telemetry.rs +85 -0
  185. package/rust/utils/Cargo.toml +26 -0
  186. package/rust/utils/{error.rs → src/error.rs} +186 -200
  187. package/rust/utils/src/file.rs +94 -0
  188. package/rust/utils/src/first_usage.rs +97 -0
  189. package/rust/utils/{mod.rs → src/lib.rs} +1 -1
  190. package/rust/utils/{logger.rs → src/logger.rs} +17 -12
  191. package/rust/utils/src/path.rs +88 -0
  192. package/rust/utils/src/signature.rs +41 -0
  193. package/rust/utils/{spinner.rs → src/spinner.rs} +3 -5
  194. package/rust/utils/src/version.rs +27 -0
  195. package/rust/utils/{watcher.rs → src/watcher.rs} +13 -1
  196. package/rust/web/cdn.rs +34 -0
  197. package/templates/minimal/README.md +98 -54
  198. package/templates/welcome/README.md +98 -54
  199. package/templates/welcome/src/index.deva +56 -8
  200. package/templates/welcome/src/variables.deva +2 -4
  201. package/tests/rust/TODO.md +0 -0
  202. package/tests/typescript/index.spec.ts +136 -0
  203. package/tests/typescript/playhead.spec.ts +36 -0
  204. package/tests/typescript/render_e2e.spec.ts +77 -0
  205. package/tsconfig.json +1 -1
  206. package/typescript/core/functions/index.ts +83 -0
  207. package/typescript/core/index.ts +6 -0
  208. package/typescript/core/types/index.ts +4 -0
  209. package/typescript/core/types/plugin.ts +19 -0
  210. package/typescript/core/types/result.ts +29 -0
  211. package/typescript/core/types/statement.ts +47 -0
  212. package/typescript/core/types/value.ts +29 -0
  213. package/typescript/index.ts +7 -2
  214. package/typescript/pkg/devalang_core.d.ts +4 -0
  215. package/typescript/scripts/copy-wasm-dts.ts +41 -0
  216. package/rust/cli/bank.rs +0 -462
  217. package/rust/cli/build.rs +0 -252
  218. package/rust/cli/play.rs +0 -1123
  219. package/rust/common/cdn.rs +0 -5
  220. package/rust/config/loader.rs +0 -165
  221. package/rust/config/stats.rs +0 -257
  222. package/rust/core/audio/engine.rs +0 -696
  223. package/rust/core/shared/bank.rs +0 -21
  224. package/rust/core/shared/duration.rs +0 -9
  225. package/rust/core/shared/mod.rs +0 -3
  226. package/rust/core/shared/value.rs +0 -35
  227. package/rust/core/utils/validation.rs +0 -35
  228. package/rust/installer/addon.rs +0 -84
  229. package/rust/installer/bank.rs +0 -62
  230. package/rust/installer/plugin.rs +0 -54
  231. package/rust/installer/utils.rs +0 -56
  232. package/rust/utils/file.rs +0 -38
  233. package/rust/utils/first_usage.rs +0 -83
  234. package/rust/utils/signature.rs +0 -19
  235. package/rust/utils/telemetry.rs +0 -292
  236. package/rust/utils/version.rs +0 -15
  237. /package/rust/{common → web}/api.rs +0 -0
  238. /package/rust/{common → web}/mod.rs +0 -0
  239. /package/rust/{common → web}/sso.rs +0 -0
@@ -0,0 +1,324 @@
1
+ use crate::config::driver::ProjectConfig;
2
+ use devalang_utils::logger::{LogLevel, Logger};
3
+ use std::{sync::mpsc::channel, thread};
4
+
5
+ pub use crate::cli::play::io::wav_duration_seconds;
6
+ pub use crate::cli::play::realtime::{
7
+ RtContext, join_realtime_runner, start_realtime_runner, stop_realtime_runner,
8
+ };
9
+
10
+ use super::process::process_play;
11
+ use super::utils::{files_changed, snapshot_files};
12
+
13
+ use crate::core::audio::player::AudioPlayer;
14
+
15
+ #[cfg(feature = "cli")]
16
+ pub fn handle_play_command(
17
+ config: Option<ProjectConfig>,
18
+ entry: Option<String>,
19
+ output: Option<String>,
20
+ watch: bool,
21
+ repeat: bool,
22
+ debug: bool,
23
+ ) -> Result<(), String> {
24
+ let logger = Logger::new();
25
+
26
+ let entry_path = entry
27
+ .or_else(|| config.as_ref().and_then(|c| c.defaults.entry.clone()))
28
+ .unwrap_or_default();
29
+
30
+ let output_path = output
31
+ .or_else(|| config.as_ref().and_then(|c| c.defaults.output.clone()))
32
+ .unwrap_or_default();
33
+
34
+ let fetched_repeat = if repeat {
35
+ true
36
+ } else {
37
+ config
38
+ .as_ref()
39
+ .and_then(|c| c.defaults.repeat)
40
+ .unwrap_or(false)
41
+ };
42
+
43
+ if entry_path.is_empty() || output_path.is_empty() {
44
+ logger.log_message(LogLevel::Error, "Entry or output path not specified.");
45
+ return Err("missing entry or output".to_string());
46
+ }
47
+
48
+ let entry_file = match crate::core::utils::path::find_entry_file(&entry_path) {
49
+ Some(p) => p,
50
+ None => {
51
+ logger.log_message(LogLevel::Error, "index.deva not found");
52
+ return Err("index.deva not found".to_string());
53
+ }
54
+ };
55
+
56
+ let audio_file = format!(
57
+ "{}/audio/index.wav",
58
+ crate::core::utils::path::normalize_path(&output_path)
59
+ );
60
+ let mut audio_player = AudioPlayer::new();
61
+
62
+ if watch && fetched_repeat {
63
+ logger.log_message(
64
+ LogLevel::Error,
65
+ "Watch and repeat cannot be used together. Use repeat instead.",
66
+ );
67
+ return Err("invalid options: watch and repeat cannot be combined".to_string());
68
+ }
69
+
70
+ if watch {
71
+ let (tx, rx) = channel::<()>();
72
+
73
+ // Thread 1 : Watcher sending changes
74
+ let entry_clone = entry_path.clone();
75
+ thread::spawn(move || {
76
+ let _ = devalang_utils::watcher::watch_directory(entry_clone, move || {
77
+ let _ = tx.send(()); // signal a change
78
+ });
79
+ });
80
+
81
+ // Main thread: build + play in a loop
82
+ let (bpm, entry_stmts, variables, functions, global_store) =
83
+ process_play(&config, &entry_file, &output_path, debug)?;
84
+ audio_player.play_file_once(&audio_file);
85
+ // Estimate duration: base on statement count plus extra for loop iterations (1 beat per iter)
86
+ let loop_iters: usize = entry_stmts
87
+ .iter()
88
+ .map(|s| match &s.kind {
89
+ crate::core::parser::statement::StatementKind::Loop => {
90
+ use devalang_types::Value;
91
+ if let Value::Map(m) = &s.value {
92
+ if let Some(Value::Array(items)) = m.get("array") {
93
+ items.len()
94
+ } else if let Some(Value::Number(n)) = m.get("iterator") {
95
+ (*n).max(0.0) as usize
96
+ } else {
97
+ 0
98
+ }
99
+ } else {
100
+ 0
101
+ }
102
+ }
103
+ _ => 0,
104
+ })
105
+ .sum();
106
+ let est_beats = (entry_stmts.len() as f32) + (loop_iters as f32);
107
+ let est_by_len = ((60.0 / bpm).max(0.01) * est_beats).max(1.0);
108
+ let total_secs = wav_duration_seconds(&audio_file)
109
+ .unwrap_or(0.0)
110
+ .max(est_by_len);
111
+ let mut rt_runner = Some(start_realtime_runner(
112
+ RtContext {
113
+ bpm,
114
+ entry_stmts,
115
+ variables,
116
+ functions,
117
+ global_store,
118
+ },
119
+ total_secs,
120
+ ));
121
+
122
+ logger.log_message(
123
+ LogLevel::Watcher,
124
+ "Watching for changes... Press Ctrl+C to exit.",
125
+ );
126
+
127
+ while rx.recv().is_ok() {
128
+ logger.log_message(LogLevel::Watcher, "Change detected, rebuilding...");
129
+
130
+ // Stop previous real-time runner before restarting playback
131
+ stop_realtime_runner(&mut rt_runner);
132
+
133
+ let (bpm, entry_stmts, variables, functions, global_store) =
134
+ match process_play(&config, &entry_file, &output_path, debug) {
135
+ Ok(v) => v,
136
+ Err(e) => {
137
+ logger.log_message(LogLevel::Error, &format!("Rebuild failed: {}", e));
138
+ continue;
139
+ }
140
+ };
141
+
142
+ logger.log_message(LogLevel::Info, "🎵 Playback started (once mode)...");
143
+
144
+ audio_player.play_file_once(&audio_file);
145
+ let loop_iters: usize = entry_stmts
146
+ .iter()
147
+ .map(|s| match &s.kind {
148
+ crate::core::parser::statement::StatementKind::Loop => {
149
+ use devalang_types::Value;
150
+ if let Value::Map(m) = &s.value {
151
+ if let Some(Value::Array(items)) = m.get("array") {
152
+ items.len()
153
+ } else if let Some(Value::Number(n)) = m.get("iterator") {
154
+ (*n).max(0.0) as usize
155
+ } else {
156
+ 0
157
+ }
158
+ } else {
159
+ 0
160
+ }
161
+ }
162
+ _ => 0,
163
+ })
164
+ .sum();
165
+ let est_beats = (entry_stmts.len() as f32) + (loop_iters as f32);
166
+ let est_by_len = ((60.0 / bpm).max(0.01) * est_beats).max(1.0);
167
+ let total_secs = wav_duration_seconds(&audio_file)
168
+ .unwrap_or(0.0)
169
+ .max(est_by_len);
170
+ rt_runner = Some(start_realtime_runner(
171
+ RtContext {
172
+ bpm,
173
+ entry_stmts: entry_stmts.clone(),
174
+ variables: variables.clone(),
175
+ functions: functions.clone(),
176
+ global_store: global_store.clone(),
177
+ },
178
+ total_secs,
179
+ ));
180
+ }
181
+ } else if fetched_repeat {
182
+ // Initial build to start from a clean slate
183
+ let (bpm, entry_stmts, variables, functions, global_store) =
184
+ process_play(&config, &entry_file, &output_path, debug)?;
185
+
186
+ logger.log_message(LogLevel::Info, "🎵 Playback started (repeat mode)...");
187
+
188
+ let mut last_snapshot = snapshot_files(&entry_path);
189
+ let mut audio_player = AudioPlayer::new();
190
+ audio_player.play_file_once(&audio_file);
191
+
192
+ let loop_iters: usize = entry_stmts
193
+ .iter()
194
+ .map(|s| match &s.kind {
195
+ crate::core::parser::statement::StatementKind::Loop => {
196
+ use devalang_types::Value;
197
+
198
+ if let Value::Map(m) = &s.value {
199
+ if let Some(Value::Array(items)) = m.get("array") {
200
+ items.len()
201
+ } else if let Some(Value::Number(n)) = m.get("iterator") {
202
+ (*n).max(0.0) as usize
203
+ } else {
204
+ 0
205
+ }
206
+ } else {
207
+ 0
208
+ }
209
+ }
210
+ _ => 0,
211
+ })
212
+ .sum();
213
+ let est_beats = (entry_stmts.len() as f32) + (loop_iters as f32);
214
+ let est_by_len = ((60.0 / bpm).max(0.01) * est_beats).max(1.0);
215
+ let total_secs = wav_duration_seconds(&audio_file)
216
+ .unwrap_or(0.0)
217
+ .max(est_by_len);
218
+ let mut rt_runner = Some(start_realtime_runner(
219
+ RtContext {
220
+ bpm,
221
+ entry_stmts: entry_stmts.clone(),
222
+ variables: variables.clone(),
223
+ functions: functions.clone(),
224
+ global_store: global_store.clone(),
225
+ },
226
+ total_secs,
227
+ ));
228
+
229
+ loop {
230
+ let current_snapshot = snapshot_files(&entry_path);
231
+ let has_changed = files_changed(&last_snapshot, &current_snapshot);
232
+
233
+ if has_changed {
234
+ logger.log_message(
235
+ LogLevel::Info,
236
+ "Change detected, rebuilding in background...",
237
+ );
238
+ let entry_file = entry_file.clone();
239
+ let output_path = output_path.clone();
240
+ let config_clone = config.clone();
241
+
242
+ // Rebuild in a separate thread
243
+ std::thread::spawn(move || {
244
+ if let Err(e) = process_play(&config_clone, &entry_file, &output_path, debug) {
245
+ eprintln!("Rebuild failed in background: {}", e);
246
+ }
247
+ });
248
+
249
+ last_snapshot = current_snapshot;
250
+ }
251
+
252
+ // Wait for the audio to finish
253
+ audio_player.wait_until_end();
254
+ // Stop the current real-time runner
255
+ stop_realtime_runner(&mut rt_runner);
256
+
257
+ // Then replay the audio (rebuilt or not)
258
+ audio_player.play_file_once(&audio_file);
259
+ let loop_iters: usize = entry_stmts
260
+ .iter()
261
+ .map(|s| match &s.kind {
262
+ crate::core::parser::statement::StatementKind::Loop => {
263
+ use devalang_types::Value;
264
+ if let Value::Map(m) = &s.value {
265
+ if let Some(Value::Array(items)) = m.get("array") {
266
+ items.len()
267
+ } else if let Some(Value::Number(n)) = m.get("iterator") {
268
+ (*n).max(0.0) as usize
269
+ } else {
270
+ 0
271
+ }
272
+ } else {
273
+ 0
274
+ }
275
+ }
276
+ _ => 0,
277
+ })
278
+ .sum();
279
+ let est_beats = (entry_stmts.len() as f32) + (loop_iters as f32);
280
+ let est_by_len = ((60.0 / bpm).max(0.01) * est_beats).max(1.0);
281
+ let total_secs = wav_duration_seconds(&audio_file)
282
+ .unwrap_or(0.0)
283
+ .max(est_by_len);
284
+ rt_runner = Some(start_realtime_runner(
285
+ RtContext {
286
+ bpm,
287
+ entry_stmts: entry_stmts.clone(),
288
+ variables: variables.clone(),
289
+ functions: functions.clone(),
290
+ global_store: global_store.clone(),
291
+ },
292
+ total_secs,
293
+ ));
294
+ }
295
+ } else {
296
+ // Single execution
297
+ let (bpm, entry_stmts, variables, functions, global_store) =
298
+ process_play(&config, &entry_file, &output_path, debug)?;
299
+
300
+ logger.log_message(LogLevel::Info, "🎵 Playback started (once mode)...");
301
+
302
+ audio_player.play_file_once(&audio_file);
303
+
304
+ let est_by_len = ((60.0 / bpm).max(0.01) * (entry_stmts.len() as f32)).max(1.0);
305
+ let total_secs = wav_duration_seconds(&audio_file)
306
+ .unwrap_or(0.0)
307
+ .max(est_by_len);
308
+ let mut rt_runner = Some(start_realtime_runner(
309
+ RtContext {
310
+ bpm,
311
+ entry_stmts,
312
+ variables,
313
+ functions,
314
+ global_store,
315
+ },
316
+ total_secs,
317
+ ));
318
+
319
+ audio_player.wait_until_end();
320
+ // Let the runner finish naturally to execute all remaining statements (e.g., loop prints)
321
+ join_realtime_runner(&mut rt_runner);
322
+ }
323
+ Ok(())
324
+ }
@@ -0,0 +1,17 @@
1
+ use hound;
2
+
3
+ pub fn wav_duration_seconds(path: &str) -> Option<f32> {
4
+ if let Ok(reader) = hound::WavReader::open(path) {
5
+ let spec = reader.spec();
6
+ let len = reader.len();
7
+ if spec.sample_rate == 0 {
8
+ return None;
9
+ }
10
+ let channels = spec.channels.max(1) as u32;
11
+ let frames = len / channels;
12
+ let dur = (frames as f32) / (spec.sample_rate as f32);
13
+ Some(dur)
14
+ } else {
15
+ None
16
+ }
17
+ }
@@ -0,0 +1,5 @@
1
+ pub mod commands;
2
+ pub mod io;
3
+ pub mod process;
4
+ pub mod realtime;
5
+ pub mod utils;
@@ -0,0 +1,150 @@
1
+ use crate::{
2
+ config::driver::ProjectConfig,
3
+ core::{
4
+ builder::Builder,
5
+ debugger::{
6
+ lexer::write_lexer_log_file,
7
+ module::{write_module_function_log_file, write_module_variable_log_file},
8
+ preprocessor::write_preprocessor_log_file,
9
+ store::{write_function_log_file, write_variables_log_file},
10
+ },
11
+ preprocessor::loader::ModuleLoader,
12
+ store::global::GlobalStore,
13
+ utils::path::normalize_path,
14
+ },
15
+ };
16
+ use devalang_utils::{
17
+ logger::{LogLevel, Logger},
18
+ spinner::start_spinner,
19
+ };
20
+
21
+ pub fn process_play(
22
+ _config: &Option<ProjectConfig>,
23
+ entry_file: &str,
24
+ output: &str,
25
+ debug: bool,
26
+ ) -> Result<
27
+ (
28
+ f32,
29
+ Vec<crate::core::parser::statement::Statement>,
30
+ crate::core::store::variable::VariableTable,
31
+ crate::core::store::function::FunctionTable,
32
+ crate::core::store::global::GlobalStore,
33
+ ),
34
+ String,
35
+ > {
36
+ let spinner = start_spinner("Building...");
37
+
38
+ let normalized_entry = normalize_path(entry_file);
39
+ let normalized_output_dir = normalize_path(output);
40
+
41
+ let duration = std::time::Instant::now();
42
+ let mut global_store = GlobalStore::new();
43
+ let loader = ModuleLoader::new(&normalized_entry, &normalized_output_dir);
44
+ let (modules_tokens, modules_statements) = loader.load_all_modules(&mut global_store);
45
+
46
+ // Try to detect initial BPM from statements (fallback to 120.0)
47
+ let mut detected_bpm: f32 = 120.0;
48
+ let mut entry_statements: Vec<crate::core::parser::statement::Statement> = Vec::new();
49
+ // Prefer the entry module if present
50
+ if let Some(entry_stmts) = modules_statements.get(&normalized_entry) {
51
+ entry_statements = entry_stmts.clone();
52
+ for stmt in entry_stmts {
53
+ if let crate::core::parser::statement::StatementKind::Tempo = &stmt.kind {
54
+ use devalang_types::Value;
55
+ if let Value::Number(n) = &stmt.value {
56
+ detected_bpm = *n;
57
+ break;
58
+ }
59
+ }
60
+ }
61
+ }
62
+ // If still default, scan other modules for a tempo directive
63
+ if (detected_bpm - 120.0).abs() < f32::EPSILON {
64
+ 'outer: for (_name, stmts) in modules_statements.iter() {
65
+ for stmt in stmts {
66
+ if let crate::core::parser::statement::StatementKind::Tempo = &stmt.kind {
67
+ use devalang_types::Value;
68
+ if let Value::Number(n) = &stmt.value {
69
+ detected_bpm = *n;
70
+ break 'outer;
71
+ }
72
+ }
73
+ }
74
+ }
75
+ }
76
+
77
+ // SECTION Write logs
78
+ if debug {
79
+ for (module_path, module) in global_store.modules.clone() {
80
+ write_module_variable_log_file(
81
+ &normalized_output_dir,
82
+ &module_path,
83
+ &module.variable_table,
84
+ );
85
+ write_module_function_log_file(
86
+ &normalized_output_dir,
87
+ &module_path,
88
+ &module.function_table,
89
+ );
90
+ }
91
+
92
+ write_lexer_log_file(
93
+ &normalized_output_dir,
94
+ "lexer_tokens.log",
95
+ modules_tokens.clone(),
96
+ );
97
+ write_preprocessor_log_file(
98
+ &normalized_output_dir,
99
+ "resolved_statements.log",
100
+ modules_statements.clone(),
101
+ );
102
+ write_variables_log_file(
103
+ &normalized_output_dir,
104
+ "global_variables.log",
105
+ global_store.variables.clone(),
106
+ );
107
+ write_function_log_file(
108
+ &normalized_output_dir,
109
+ "global_functions.log",
110
+ global_store.functions.clone(),
111
+ );
112
+ }
113
+
114
+ // SECTION Detect errors before building (like build.rs)
115
+ let all_errors = crate::core::error::collect_all_errors_with_modules(&modules_statements);
116
+ let (warnings, criticals) = crate::core::error::partition_errors(all_errors);
117
+ crate::core::error::log_errors_with_stack("Play", &warnings, &criticals);
118
+ if !criticals.is_empty() {
119
+ spinner.finish_and_clear();
120
+ return Err(format!(
121
+ "play failed with {} critical error(s): {}",
122
+ criticals.len(),
123
+ criticals[0].message
124
+ ));
125
+ }
126
+
127
+ // SECTION Building AST and Audio
128
+ let builder = Builder::new();
129
+ builder.build_ast(&modules_statements, output, false);
130
+ builder.build_audio(&modules_statements, output, &mut global_store);
131
+
132
+ // SECTION Logging
133
+ let logger = Logger::new();
134
+ let success_message = format!(
135
+ "Build completed successfully in {:.2?}. Output files written to: '{}'",
136
+ duration.elapsed(),
137
+ normalized_output_dir
138
+ );
139
+
140
+ spinner.finish_and_clear();
141
+ logger.log_message(LogLevel::Success, &success_message);
142
+
143
+ Ok((
144
+ detected_bpm,
145
+ entry_statements,
146
+ global_store.variables.clone(),
147
+ global_store.functions.clone(),
148
+ global_store,
149
+ ))
150
+ }
@@ -0,0 +1,91 @@
1
+ use std::sync::Arc;
2
+ use std::sync::atomic::{AtomicBool, Ordering};
3
+ use std::time::Duration;
4
+
5
+ use devalang_types::Value;
6
+
7
+ pub struct RtRunner {
8
+ pub stop: Arc<AtomicBool>,
9
+ pub handle: std::thread::JoinHandle<()>,
10
+ }
11
+
12
+ pub struct RtContext {
13
+ pub bpm: f32,
14
+ pub entry_stmts: Vec<crate::core::parser::statement::Statement>,
15
+ pub variables: crate::core::store::variable::VariableTable,
16
+ pub functions: crate::core::store::function::FunctionTable,
17
+ pub global_store: crate::core::store::global::GlobalStore,
18
+ }
19
+
20
+ pub fn start_realtime_runner(ctx: RtContext, total_secs: f32) -> RtRunner {
21
+ use crate::core::audio::engine::AudioEngine;
22
+ use crate::core::audio::interpreter::driver::execute_audio_block;
23
+ use crate::core::parser::statement::StatementKind;
24
+ use devalang_utils::logger::Logger;
25
+
26
+ let stop = Arc::new(AtomicBool::new(false));
27
+ let stop_clone = stop.clone();
28
+
29
+ let handle = std::thread::spawn(move || {
30
+ let _logger = Logger::new();
31
+ let bpm = if ctx.bpm > 0.0 { ctx.bpm } else { 120.0 };
32
+ let beat_secs = 60.0f32 / bpm;
33
+ let mut elapsed = 0.0f32;
34
+
35
+ let mut variables = ctx.variables.clone();
36
+ variables.set("__rt".to_string(), Value::Boolean(true));
37
+ let functions = ctx.functions.clone();
38
+ let _global_store = ctx.global_store.clone();
39
+ let mut audio_engine = AudioEngine::new("rt".to_string());
40
+
41
+ let i: usize = 0;
42
+ let mut _current_loop: Option<()> = None; // simplified state
43
+ let mut _beat_index: u64 = 0;
44
+ while elapsed + 1e-3 < total_secs && i < ctx.entry_stmts.len() {
45
+ if stop_clone.load(Ordering::Relaxed) {
46
+ break;
47
+ }
48
+
49
+ std::thread::sleep(Duration::from_secs_f32(beat_secs));
50
+ elapsed += beat_secs;
51
+ _beat_index += 1;
52
+ if stop_clone.load(Ordering::Relaxed) {
53
+ break;
54
+ }
55
+
56
+ // Only fire periodic handlers when not in a loop - simplified
57
+ if let Some(handlers) = ctx.global_store.get_event_handlers("beat") {
58
+ for h in handlers {
59
+ if let StatementKind::On { body, .. } = &h.kind {
60
+ let _ = execute_audio_block(
61
+ &mut audio_engine,
62
+ &ctx.global_store,
63
+ variables.clone(),
64
+ functions.clone(),
65
+ body,
66
+ bpm,
67
+ 60.0 / bpm,
68
+ 0.0,
69
+ 0.0,
70
+ );
71
+ }
72
+ }
73
+ }
74
+ }
75
+ });
76
+
77
+ RtRunner { stop, handle }
78
+ }
79
+
80
+ pub fn stop_realtime_runner(runner_opt: &mut Option<RtRunner>) {
81
+ if let Some(r) = runner_opt.take() {
82
+ r.stop.store(true, Ordering::Relaxed);
83
+ let _ = r.handle.join();
84
+ }
85
+ }
86
+
87
+ pub fn join_realtime_runner(runner_opt: &mut Option<RtRunner>) {
88
+ if let Some(r) = runner_opt.take() {
89
+ let _ = r.handle.join();
90
+ }
91
+ }
@@ -0,0 +1,23 @@
1
+ use std::collections::HashMap;
2
+ use std::fs;
3
+ use std::path::Path;
4
+
5
+ pub fn snapshot_files<P: AsRef<Path>>(dir: P) -> HashMap<String, u64> {
6
+ let mut map = HashMap::new();
7
+ if let Ok(entries) = fs::read_dir(dir) {
8
+ for entry in entries.flatten() {
9
+ if let Ok(meta) = entry.metadata() {
10
+ if let Ok(mtime) = meta.modified() {
11
+ if let Ok(duration) = mtime.duration_since(std::time::UNIX_EPOCH) {
12
+ map.insert(entry.path().display().to_string(), duration.as_secs());
13
+ }
14
+ }
15
+ }
16
+ }
17
+ }
18
+ map
19
+ }
20
+
21
+ pub fn files_changed(old: &HashMap<String, u64>, new: &HashMap<String, u64>) -> bool {
22
+ old != new
23
+ }
@@ -1,9 +1,9 @@
1
- use crate::config::settings::set_user_config_bool;
2
- use crate::utils::logger::{LogLevel, Logger};
1
+ use crate::config::settings::set_user_config_value;
2
+ use devalang_utils::logger::{LogLevel, Logger};
3
3
 
4
4
  #[cfg(feature = "cli")]
5
5
  pub async fn handle_telemetry_enable_command() -> Result<(), String> {
6
- set_user_config_bool("telemetry", true);
6
+ set_user_config_value("telemetry", serde_json::Value::Bool(true));
7
7
 
8
8
  let logger = Logger::new();
9
9
  logger.log_message(LogLevel::Info, "Telemetry has been enabled.");
@@ -13,7 +13,7 @@ pub async fn handle_telemetry_enable_command() -> Result<(), String> {
13
13
 
14
14
  #[cfg(feature = "cli")]
15
15
  pub async fn handle_telemetry_disable_command() -> Result<(), String> {
16
- set_user_config_bool("telemetry", false);
16
+ set_user_config_value("telemetry", serde_json::Value::Bool(false));
17
17
 
18
18
  let logger = Logger::new();
19
19
  logger.log_message(LogLevel::Info, "Telemetry has been disabled.");