tsrun 0.1.23

A TypeScript interpreter designed for embedding in applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
//! A minimal TypeScript runtime for embedding in applications.
//!
//! This crate provides a TypeScript interpreter written in Rust, designed for
//! configuration files where users benefit from IDE autocompletion, type checking,
//! and error highlighting. TypeScript features like enums, interfaces, and generics
//! are fully parsed; types are stripped at runtime (not type-checked).
//!
//! # TypeScript Features
//!
//! The interpreter supports TypeScript-specific syntax for better editor experience:
//!
//! - **Enums** - Numeric and string enums with reverse mappings
//! - **Interfaces & Types** - Parsed for IDE support, stripped at runtime
//! - **Decorators** - Class, method, property, and parameter decorators
//! - **Namespaces** - TypeScript namespace declarations
//! - **Generics** - Generic functions and classes
//! - **Parameter Properties** - `constructor(public x: number)` syntax
//!
//! # Quick Start
//!
//! ```
//! use tsrun::{Interpreter, StepResult};
//!
//! let mut interp = Interpreter::new();
//! interp.prepare(r#"
//!     enum Status { Active = 1, Inactive = 0 }
//!     interface Config { status: Status; }
//!     const cfg: Config = { status: Status.Active };
//!     cfg.status
//! "#, None).unwrap();
//!
//! loop {
//!     match interp.step().unwrap() {
//!         StepResult::Continue => continue,
//!         StepResult::Complete(value) => {
//!             assert_eq!(value.as_number(), Some(1.0));
//!             break;
//!         }
//!         _ => panic!("Unexpected result"),
//!     }
//! }
//! ```
//!
//! # Execution Model
//!
//! The interpreter uses step-based execution, giving hosts full control:
//!
//! - [`Interpreter::prepare`] - Compiles code and prepares for execution
//! - [`Interpreter::step`] - Executes one instruction, returns [`StepResult`]
//! - [`StepResult::NeedImports`] - Execution paused, waiting for ES modules
//! - [`StepResult::Suspended`] - Execution paused, waiting for async operations
//!
//! # Working with Values
//!
//! Use the [`api`] module for creating and manipulating JavaScript values:
//!
//! ```
//! use tsrun::{Interpreter, api};
//!
//! let mut interp = Interpreter::new();
//! let guard = api::create_guard(&interp);
//!
//! // Create objects from JSON
//! let user = api::create_from_json(&mut interp, &guard, &serde_json::json!({
//!     "name": "Alice",
//!     "scores": [95, 87, 92]
//! })).unwrap();
//!
//! // Read properties
//! let name = api::get_property(&user, "name").unwrap();
//! assert_eq!(name.as_str(), Some("Alice"));
//!
//! // Call methods on arrays
//! let scores = api::get_property(&user, "scores").unwrap();
//! let joined = api::call_method(&mut interp, &guard, &scores, "join", &["-".into()]).unwrap();
//! assert_eq!(joined.as_str(), Some("95-87-92"));
//! ```
//!
//! # Module Loading
//!
//! ES modules are loaded on-demand. When execution needs an import:
//!
//! ```
//! use tsrun::{Interpreter, StepResult, ModulePath};
//!
//! let mut interp = Interpreter::new();
//! interp.prepare(r#"import { x } from "./config.ts"; x"#, Some("/main.ts".into())).unwrap();
//!
//! loop {
//!     match interp.step().unwrap() {
//!         StepResult::Continue => continue,
//!         StepResult::NeedImports(imports) => {
//!             for import in imports {
//!                 // Host provides module source code
//!                 let source = "export const x = 42;";
//!                 interp.provide_module(import.resolved_path, source).unwrap();
//!             }
//!         }
//!         StepResult::Complete(value) => {
//!             assert_eq!(value.as_number(), Some(42.0));
//!             break;
//!         }
//!         _ => break,
//!     }
//! }
//! ```
//!
//! # Internal Modules
//!
//! Register Rust functions as importable modules:
//!
//! ```
//! use tsrun::{Interpreter, InterpreterConfig, InternalModule, JsValue, Guarded, JsError};
//!
//! fn get_version(
//!     _interp: &mut Interpreter,
//!     _this: JsValue,
//!     _args: &[JsValue]
//! ) -> Result<Guarded, JsError> {
//!     Ok(Guarded::unguarded(JsValue::from("1.0.0")))
//! }
//!
//! let config = InterpreterConfig {
//!     internal_modules: vec![
//!         InternalModule::native("app:version")
//!             .with_function("getVersion", get_version, 0)
//!             .build(),
//!     ],
//!     ..Default::default()
//! };
//! let interp = Interpreter::with_config(config);
//! // Now code can: import { getVersion } from "app:version";
//! ```
//!
//! # GC Safety
//!
//! Objects are garbage-collected. Use [`Guard`] to keep them alive:
//!
//! ```
//! use tsrun::{Interpreter, api};
//!
//! let mut interp = Interpreter::new();
//! let guard = api::create_guard(&interp);
//!
//! // Objects allocated with guard stay alive until guard is dropped
//! let obj = api::create_object(&mut interp, &guard).unwrap();
//! api::set_property(&obj, "x", 42.into()).unwrap();
//!
//! // guard dropped here - obj may be collected
//! ```
//!
//! # Use Case Examples
//!
//! ## Kubernetes Deployment Configuration
//!
//! Generate type-safe Kubernetes manifests with IDE autocompletion:
//!
//! ```
//! use tsrun::{Interpreter, StepResult, js_value_to_json};
//!
//! let mut interp = Interpreter::new();
//! interp.prepare(r#"
//!     interface DeploymentConfig {
//!         name: string;
//!         image: string;
//!         replicas: number;
//!         port: number;
//!     }
//!
//!     function deployment(config: DeploymentConfig) {
//!         return {
//!             apiVersion: "apps/v1",
//!             kind: "Deployment",
//!             metadata: { name: config.name },
//!             spec: {
//!                 replicas: config.replicas,
//!                 selector: { matchLabels: { app: config.name } },
//!                 template: {
//!                     metadata: { labels: { app: config.name } },
//!                     spec: {
//!                         containers: [{
//!                             name: config.name,
//!                             image: config.image,
//!                             ports: [{ containerPort: config.port }]
//!                         }]
//!                     }
//!                 }
//!             }
//!         };
//!     }
//!
//!     deployment({ name: "api", image: "myapp:v1.2.0", replicas: 3, port: 8080 })
//! "#, None).unwrap();
//!
//! let result = loop {
//!     match interp.step().unwrap() {
//!         StepResult::Continue => continue,
//!         StepResult::Complete(value) => {
//!             break js_value_to_json(value.value()).unwrap();
//!         }
//!         _ => panic!("Unexpected result"),
//!     }
//! };
//!
//! assert_eq!(result["apiVersion"], "apps/v1");
//! assert_eq!(result["kind"], "Deployment");
//! assert_eq!(result["metadata"]["name"], "api");
//! assert_eq!(result["spec"]["replicas"], 3);
//! ```
//!
//! ## Game Item Configuration
//!
//! Define game items with enums and computed loot tables:
//!
//! ```
//! use tsrun::{Interpreter, StepResult, js_value_to_json};
//!
//! let mut interp = Interpreter::new();
//! interp.prepare(r#"
//!     enum Rarity { Common, Rare, Epic, Legendary }
//!
//!     interface Item {
//!         name: string;
//!         rarity: Rarity;
//!         basePrice: number;
//!         effects?: string[];
//!     }
//!
//!     function createLootTable(items: Item[]) {
//!         return items.map(item => ({
//!             ...item,
//!             dropWeight: item.rarity === Rarity.Legendary ? 1 :
//!                         item.rarity === Rarity.Epic ? 5 :
//!                         item.rarity === Rarity.Rare ? 15 : 50,
//!             sellPrice: Math.floor(item.basePrice * (1 + item.rarity * 0.5))
//!         }));
//!     }
//!
//!     createLootTable([
//!         { name: "Iron Sword", rarity: Rarity.Common, basePrice: 100 },
//!         { name: "Dragon Scale", rarity: Rarity.Legendary, basePrice: 5000,
//!           effects: ["Fire Resistance", "+50 Defense"] }
//!     ])
//! "#, None).unwrap();
//!
//! let result = loop {
//!     match interp.step().unwrap() {
//!         StepResult::Continue => continue,
//!         StepResult::Complete(value) => {
//!             break js_value_to_json(value.value()).unwrap();
//!         }
//!         _ => panic!("Unexpected result"),
//!     }
//! };
//!
//! // Common item: dropWeight=50, sellPrice=100*(1+0*0.5)=100
//! assert_eq!(result[0]["name"], "Iron Sword");
//! assert_eq!(result[0]["dropWeight"], 50);
//! assert_eq!(result[0]["sellPrice"], 100);
//!
//! // Legendary item: dropWeight=1, sellPrice=5000*(1+3*0.5)=12500
//! assert_eq!(result[1]["name"], "Dragon Scale");
//! assert_eq!(result[1]["dropWeight"], 1);
//! assert_eq!(result[1]["sellPrice"], 12500);
//! assert_eq!(result[1]["effects"][0], "Fire Resistance");
//! ```
//!
//! ## API Router Configuration
//!
//! Configure REST endpoints with typed middleware and rate limits:
//!
//! ```
//! use tsrun::{Interpreter, StepResult, js_value_to_json};
//!
//! let mut interp = Interpreter::new();
//! interp.prepare(r#"
//!     interface Route {
//!         method: "GET" | "POST" | "PUT" | "DELETE";
//!         path: string;
//!         handler: string;
//!         middleware?: string[];
//!         rateLimit?: { requests: number; window: string };
//!     }
//!
//!     const routes: Route[] = [
//!         {
//!             method: "GET",
//!             path: "/users/:id",
//!             handler: "users::get",
//!             middleware: ["auth", "cache"]
//!         },
//!         {
//!             method: "POST",
//!             path: "/users",
//!             handler: "users::create",
//!             middleware: ["auth", "validate"],
//!             rateLimit: { requests: 10, window: "1m" }
//!         },
//!         {
//!             method: "DELETE",
//!             path: "/users/:id",
//!             handler: "users::delete",
//!             middleware: ["auth", "admin"]
//!         }
//!     ];
//!
//!     routes
//! "#, None).unwrap();
//!
//! let result = loop {
//!     match interp.step().unwrap() {
//!         StepResult::Continue => continue,
//!         StepResult::Complete(value) => {
//!             break js_value_to_json(value.value()).unwrap();
//!         }
//!         _ => panic!("Unexpected result"),
//!     }
//! };
//!
//! assert_eq!(result.as_array().unwrap().len(), 3);
//! assert_eq!(result[0]["method"], "GET");
//! assert_eq!(result[0]["path"], "/users/:id");
//! assert_eq!(result[1]["rateLimit"]["requests"], 10);
//! assert_eq!(result[2]["middleware"][1], "admin");
//! ```
//!
//! ## Build Tool Configuration
//!
//! Create plugin-based build configurations like webpack or vite:
//!
//! ```
//! use tsrun::{Interpreter, StepResult, js_value_to_json};
//!
//! let mut interp = Interpreter::new();
//! interp.prepare(r#"
//!     interface Plugin {
//!         name: string;
//!         options?: Record<string, any>;
//!     }
//!
//!     interface BuildConfig {
//!         entry: string;
//!         output: { path: string; filename: string };
//!         plugins: Plugin[];
//!         minify: boolean;
//!     }
//!
//!     const config: BuildConfig = {
//!         entry: "./src/index.ts",
//!         output: {
//!             path: "./dist",
//!             filename: "[name].[hash].js"
//!         },
//!         plugins: [
//!             { name: "typescript", options: { target: "ES2022" } },
//!             { name: "minify", options: { dropConsole: true } },
//!             { name: "bundle-analyzer" }
//!         ],
//!         minify: true
//!     };
//!
//!     config
//! "#, None).unwrap();
//!
//! let result = loop {
//!     match interp.step().unwrap() {
//!         StepResult::Continue => continue,
//!         StepResult::Complete(value) => {
//!             break js_value_to_json(value.value()).unwrap();
//!         }
//!         _ => panic!("Unexpected result"),
//!     }
//! };
//!
//! assert_eq!(result["entry"], "./src/index.ts");
//! assert_eq!(result["output"]["path"], "./dist");
//! assert_eq!(result["plugins"].as_array().unwrap().len(), 3);
//! assert_eq!(result["plugins"][0]["name"], "typescript");
//! assert_eq!(result["plugins"][0]["options"]["target"], "ES2022");
//! assert_eq!(result["minify"], true);
//! ```
//!
//! ## Validation Schema
//!
//! Define form validation schemas with discriminated unions:
//!
//! ```
//! use tsrun::{Interpreter, StepResult, js_value_to_json};
//!
//! let mut interp = Interpreter::new();
//! interp.prepare(r#"
//!     type Rule =
//!         | { type: "required" }
//!         | { type: "minLength"; value: number }
//!         | { type: "maxLength"; value: number }
//!         | { type: "pattern"; regex: string; message: string }
//!         | { type: "email" };
//!
//!     interface FieldSchema {
//!         name: string;
//!         label: string;
//!         rules: Rule[];
//!     }
//!
//!     const userSchema: FieldSchema[] = [
//!         {
//!             name: "email",
//!             label: "Email Address",
//!             rules: [
//!                 { type: "required" },
//!                 { type: "email" }
//!             ]
//!         },
//!         {
//!             name: "password",
//!             label: "Password",
//!             rules: [
//!                 { type: "required" },
//!                 { type: "minLength", value: 8 },
//!                 { type: "pattern", regex: "[A-Z]", message: "Must contain uppercase" }
//!             ]
//!         }
//!     ];
//!
//!     userSchema
//! "#, None).unwrap();
//!
//! let result = loop {
//!     match interp.step().unwrap() {
//!         StepResult::Continue => continue,
//!         StepResult::Complete(value) => {
//!             break js_value_to_json(value.value()).unwrap();
//!         }
//!         _ => panic!("Unexpected result"),
//!     }
//! };
//!
//! assert_eq!(result.as_array().unwrap().len(), 2);
//! assert_eq!(result[0]["name"], "email");
//! assert_eq!(result[0]["label"], "Email Address");
//! assert_eq!(result[0]["rules"][0]["type"], "required");
//! assert_eq!(result[1]["rules"][1]["type"], "minLength");
//! assert_eq!(result[1]["rules"][1]["value"], 8);
//! assert_eq!(result[1]["rules"][2]["message"], "Must contain uppercase");
//! ```

// ═══════════════════════════════════════════════════════════════════════════════
// no_std support
// ═══════════════════════════════════════════════════════════════════════════════

#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(not(feature = "std"))]
extern crate alloc;

mod prelude;
use prelude::ToString;

pub mod api;
pub mod ast;
pub mod compiler;
pub mod error;
pub mod gc;
pub(crate) mod interpreter;
pub mod parser;
pub mod platform;
pub mod string_dict;
pub mod value;

// C FFI module (only when c-api feature is enabled)
#[cfg(feature = "c-api")]
pub mod ffi;

// WASM module (only when wasm feature is enabled on wasm32 target)
// Exports C FFI-style functions for WASM runtimes (browser, wazero, wasmer, wasmtime)
#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
pub mod wasm;

use prelude::{Rc, String, Vec, format};

pub use error::JsError;
pub use gc::{Gc, GcStats, Guard, Heap, Reset};
pub use interpreter::Interpreter;
pub use string_dict::StringDict;
pub use value::CheapClone;
pub use value::EnvRef;
pub use value::Guarded;
pub use value::JsObject;
pub use value::JsString;
pub use value::JsValue;

// Re-export serde conversion functions for JsValue <-> serde_json::Value
pub use interpreter::builtins::json::{
    js_value_to_json, json_to_js_value_with_guard, json_to_js_value_with_interp,
};

// Re-export internal module builder for the order system
pub use interpreter::builtins::internal::create_eval_internal_module;

// Re-export order system types
// Note: Order, OrderId, OrderResponse, ModulePath, ImportRequest, StepResult are defined in this module

// ═══════════════════════════════════════════════════════════════════════════════
// Order System Types
// ═══════════════════════════════════════════════════════════════════════════════

/// Unique identifier for an order
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct OrderId(pub u64);

/// An order is a request for an external effect.
/// The payload is a RuntimeValue that the host interprets to perform side effects.
/// The RuntimeValue keeps the payload alive until the order is fulfilled or dropped.
#[derive(Debug)]
pub struct Order {
    /// Unique identifier for this order
    pub id: OrderId,
    /// The JS value describing what operation to perform.
    /// Wrapped in RuntimeValue to keep it alive until the order is processed.
    pub payload: RuntimeValue,
}

/// Response to fulfill an order from the host
pub struct OrderResponse {
    /// The order ID this response is for
    pub id: OrderId,
    /// The result of the operation (success or error).
    /// Use `RuntimeValue::unguarded()` for primitives or
    /// `api::create_response_object()` for objects.
    pub result: Result<RuntimeValue, JsError>,
}

// ═══════════════════════════════════════════════════════════════════════════════
// Runtime Value
// ═══════════════════════════════════════════════════════════════════════════════

/// A JS value with an attached guard that keeps it alive until dropped.
///
/// This struct ensures that GC-managed objects remain valid for as long as
/// the `RuntimeValue` exists. The guard is private to prevent accidental
/// extraction of the value without the guard.
///
/// # Creating RuntimeValues
///
/// For primitives (no GC needed):
/// ```
/// use tsrun::{RuntimeValue, JsValue};
///
/// let num = RuntimeValue::unguarded(JsValue::from(42.0));
/// assert_eq!(num.as_number(), Some(42.0));
///
/// let text = RuntimeValue::unguarded(JsValue::from("hello"));
/// assert_eq!(text.as_str(), Some("hello"));
/// ```
///
/// For objects returned from execution:
/// ```
/// use tsrun::{Interpreter, StepResult};
///
/// let mut interp = Interpreter::new();
/// interp.prepare("({ x: 1, y: 2 })", None).unwrap();
///
/// loop {
///     match interp.step().unwrap() {
///         StepResult::Continue => continue,
///         StepResult::Complete(value) => {
///             // value is a RuntimeValue keeping the object alive
///             assert!(value.is_object());
///             break;
///         }
///         _ => break,
///     }
/// }
/// ```
pub struct RuntimeValue {
    value: JsValue,
    _guard: Option<Guard<JsObject>>,
}

impl RuntimeValue {
    /// Create a RuntimeValue from an internal Guarded value
    pub(crate) fn from_guarded(guarded: Guarded) -> Self {
        Self {
            value: guarded.value,
            _guard: guarded.guard,
        }
    }

    /// Create a RuntimeValue with an explicit guard
    pub(crate) fn with_guard(value: JsValue, guard: Guard<JsObject>) -> Self {
        Self {
            value,
            _guard: Some(guard),
        }
    }

    /// Create an unguarded RuntimeValue (for primitives).
    /// Use this for values that don't need GC protection (strings, numbers, booleans, null, undefined).
    pub fn unguarded(value: JsValue) -> Self {
        Self {
            value,
            _guard: None,
        }
    }

    /// Get a reference to the value
    pub fn value(&self) -> &JsValue {
        &self.value
    }

    // NOTE: Do NOT add `into_value(self) -> JsValue` or similar methods that
    // extract the value without the guard. The guard must stay alive as long
    // as the value is in use. If you need to pass the value somewhere, pass
    // the entire RuntimeValue and let the receiver access it via .value().

    // ═══════════════════════════════════════════════════════════════════════════════
    // Type Check Delegation Methods
    // ═══════════════════════════════════════════════════════════════════════════════

    /// Check if this is undefined
    pub fn is_undefined(&self) -> bool {
        self.value.is_undefined()
    }

    /// Check if this is null
    pub fn is_null(&self) -> bool {
        self.value.is_null()
    }

    /// Check if this is null or undefined
    pub fn is_nullish(&self) -> bool {
        self.value.is_nullish()
    }

    /// Check if this is a boolean
    pub fn is_boolean(&self) -> bool {
        self.value.is_boolean()
    }

    /// Check if this is a number
    pub fn is_number(&self) -> bool {
        self.value.is_number()
    }

    /// Check if this is a string
    pub fn is_string(&self) -> bool {
        self.value.is_string()
    }

    /// Check if this is an object
    pub fn is_object(&self) -> bool {
        self.value.is_object()
    }

    // ═══════════════════════════════════════════════════════════════════════════════
    // Value Extraction Delegation Methods
    // ═══════════════════════════════════════════════════════════════════════════════

    /// Returns the boolean value if this is a Boolean, otherwise None
    pub fn as_bool(&self) -> Option<bool> {
        self.value.as_bool()
    }

    /// Returns the numeric value if this is a Number, otherwise None
    pub fn as_number(&self) -> Option<f64> {
        self.value.as_number()
    }

    /// Returns the string slice if this is a String, otherwise None
    pub fn as_str(&self) -> Option<&str> {
        self.value.as_str()
    }

    /// Returns a string describing the type of this value
    pub fn type_name(&self) -> &'static str {
        self.value.type_name()
    }

    // ═══════════════════════════════════════════════════════════════════════════════
    // Array Inspection Methods (primitives only - complex values go through Runtime)
    // ═══════════════════════════════════════════════════════════════════════════════

    /// Get the length of an array.
    ///
    /// Returns `None` if this is not an array.
    ///
    /// # Example
    /// ```ignore
    /// let arr = runtime.create_from_json(&json!([1, 2, 3, 4, 5]))?;
    /// assert_eq!(arr.len(), Some(5));
    /// ```
    pub fn len(&self) -> Option<usize> {
        let obj = self.value.as_object()?;
        let borrowed = obj.borrow();
        borrowed.array_length().map(|l| l as usize)
    }

    /// Check if the array is empty.
    ///
    /// Returns `None` if this is not an array.
    pub fn is_empty(&self) -> Option<bool> {
        self.len().map(|l| l == 0)
    }

    /// Check if this value is an array.
    ///
    /// # Example
    /// ```ignore
    /// let arr = runtime.create_from_json(&json!([1, 2, 3]))?;
    /// let obj = runtime.create_from_json(&json!({"x": 1}))?;
    /// assert!(arr.is_array());
    /// assert!(!obj.is_array());
    /// ```
    pub fn is_array(&self) -> bool {
        if let Some(obj) = self.value.as_object() {
            let borrowed = obj.borrow();
            borrowed.array_length().is_some()
        } else {
            false
        }
    }

    /// Get all property keys of an object.
    ///
    /// Returns an empty vector if this is not an object.
    ///
    /// # Example
    /// ```ignore
    /// let obj = runtime.create_from_json(&json!({"a": 1, "b": 2}))?;
    /// let keys = obj.keys();
    /// assert!(keys.contains(&"a".to_string()));
    /// assert!(keys.contains(&"b".to_string()));
    /// ```
    pub fn keys(&self) -> Vec<String> {
        if let Some(obj) = self.value.as_object() {
            let borrowed = obj.borrow();
            borrowed
                .properties
                .keys()
                .filter_map(|k| match k {
                    value::PropertyKey::String(s) => Some(s.to_string()),
                    value::PropertyKey::Index(i) => Some(i.to_string()),
                    value::PropertyKey::Symbol(_) => None,
                })
                .collect()
        } else {
            Vec::new()
        }
    }
}

impl core::ops::Deref for RuntimeValue {
    type Target = JsValue;

    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl core::fmt::Debug for RuntimeValue {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("RuntimeValue")
            .field("value", &self.value)
            .field("guarded", &self._guard.is_some())
            .finish()
    }
}

impl core::fmt::Display for RuntimeValue {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::Display::fmt(&self.value, f)
    }
}

impl PartialEq<JsValue> for RuntimeValue {
    fn eq(&self, other: &JsValue) -> bool {
        &self.value == other
    }
}

impl PartialEq<RuntimeValue> for JsValue {
    fn eq(&self, other: &RuntimeValue) -> bool {
        self == &other.value
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Module Path System
// ═══════════════════════════════════════════════════════════════════════════════

/// A normalized, absolute module path.
///
/// Module paths are always stored in normalized form:
/// - No `.` or `..` segments
/// - Forward slashes only
/// - No trailing slashes
/// - Absolute (starts with `/` or is a bare specifier like `lodash`)
///
/// # Resolution Examples
///
/// ```
/// use tsrun::ModulePath;
///
/// // Relative paths resolve against a base
/// let base = ModulePath::new("/src/app/main.ts");
/// let resolved = ModulePath::resolve("./utils.ts", Some(&base));
/// assert_eq!(resolved.as_str(), "/src/app/utils.ts");
///
/// // Parent directory traversal
/// let resolved = ModulePath::resolve("../lib/helper.ts", Some(&base));
/// assert_eq!(resolved.as_str(), "/src/lib/helper.ts");
///
/// // Bare specifiers pass through for host resolution
/// let resolved = ModulePath::resolve("lodash", Some(&base));
/// assert_eq!(resolved.as_str(), "lodash");
///
/// // Absolute paths are just normalized
/// let resolved = ModulePath::resolve("/lib/../src/index.ts", None);
/// assert_eq!(resolved.as_str(), "/src/index.ts");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ModulePath(String);

impl ModulePath {
    /// Create a ModulePath from an already-normalized absolute path.
    /// Use `resolve` for relative paths.
    pub fn new(path: impl Into<String>) -> Self {
        ModulePath(path.into())
    }

    /// Get the path as a string slice
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Get the directory portion of this path (everything before the last `/`)
    pub fn parent(&self) -> Option<&str> {
        self.0.rfind('/').and_then(|idx| self.0.get(..idx))
    }

    /// Check if this is a relative specifier (starts with `.` or `..`)
    pub fn is_relative(specifier: &str) -> bool {
        specifier.starts_with("./") || specifier.starts_with("../")
    }

    /// Check if this is a bare specifier (not relative, not absolute)
    /// e.g., "lodash", "react", "tsrun:host"
    pub fn is_bare(specifier: &str) -> bool {
        !specifier.starts_with('/') && !Self::is_relative(specifier)
    }

    /// Resolve a specifier relative to a base path.
    ///
    /// - Relative specifiers (`./foo`, `../bar`) are resolved against the base's directory
    /// - Absolute specifiers (`/foo/bar`) are normalized and returned as-is
    /// - Bare specifiers (`lodash`) are returned as-is (for the host to resolve)
    pub fn resolve(specifier: &str, base: Option<&ModulePath>) -> ModulePath {
        if Self::is_bare(specifier) {
            // Bare specifier - return as-is for host resolution
            return ModulePath(specifier.to_string());
        }

        if specifier.starts_with('/') {
            // Absolute path - just normalize
            return ModulePath(Self::normalize_path(specifier));
        }

        // Relative path - resolve against base
        let base_dir = base.and_then(|b| b.parent()).unwrap_or("");

        let combined = if base_dir.is_empty() {
            specifier.to_string()
        } else {
            format!("{}/{}", base_dir, specifier)
        };

        ModulePath(Self::normalize_path(&combined))
    }

    /// Normalize a path by resolving `.` and `..` segments
    fn normalize_path(path: &str) -> String {
        let mut segments: Vec<&str> = Vec::new();

        for segment in path.split('/') {
            match segment {
                "" | "." => {
                    // Skip empty segments and current directory markers
                }
                ".." => {
                    // Go up one directory
                    segments.pop();
                }
                s => {
                    segments.push(s);
                }
            }
        }

        // Reconstruct path
        if path.starts_with('/') {
            format!("/{}", segments.join("/"))
        } else {
            segments.join("/")
        }
    }
}

impl core::fmt::Display for ModulePath {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<&str> for ModulePath {
    fn from(s: &str) -> Self {
        ModulePath::new(s)
    }
}

impl From<String> for ModulePath {
    fn from(s: String) -> Self {
        ModulePath::new(s)
    }
}

/// A pending import request with context about where it was requested from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImportRequest {
    /// The original specifier as written in the source code
    pub specifier: String,
    /// The resolved absolute path (for deduplication)
    pub resolved_path: ModulePath,
    /// The module that requested this import (None for main module)
    pub importer: Option<ModulePath>,
}

// ═══════════════════════════════════════════════════════════════════════════════
// Step Result
// ═══════════════════════════════════════════════════════════════════════════════

/// Result of executing a single step.
///
/// Step-based execution gives the host full control over when execution should stop.
/// The host calls `step()` repeatedly until it receives a terminal result
/// (`Complete`, `NeedImports`, `Suspended`), or decides to stop early.
///
/// # Execution Loop
///
/// ```
/// use tsrun::{Interpreter, StepResult};
///
/// fn run_to_completion(interp: &mut Interpreter) -> Option<f64> {
///     loop {
///         match interp.step().ok()? {
///             StepResult::Continue => continue,
///             StepResult::Complete(val) => return val.as_number(),
///             StepResult::NeedImports(_) => return None, // would need module loading
///             StepResult::Suspended { .. } => return None, // would need async handling
///             StepResult::Done => return None,
///         }
///     }
/// }
///
/// let mut interp = Interpreter::new();
/// interp.prepare("2 ** 10", None).unwrap();
/// assert_eq!(run_to_completion(&mut interp), Some(1024.0));
/// ```
#[derive(Debug)]
pub enum StepResult {
    /// Executed one instruction, more to execute.
    /// Call `step()` again to continue.
    Continue,

    /// Execution completed with a final value.
    Complete(RuntimeValue),

    /// Need these modules before execution can continue.
    /// Call `provide_module()` for each import, then call `step()` again.
    NeedImports(Vec<ImportRequest>),

    /// Execution suspended waiting for orders to be fulfilled.
    /// Call `fulfill_orders()` with responses, then call `step()` again.
    Suspended {
        /// Orders waiting for fulfillment
        pending: Vec<Order>,
        /// Orders that were cancelled (e.g., Promise.race loser)
        cancelled: Vec<OrderId>,
    },

    /// No active execution to step.
    /// Call `prepare()` first to start execution.
    Done,
}

// ═══════════════════════════════════════════════════════════════════════════════
// Internal Module System
// ═══════════════════════════════════════════════════════════════════════════════

/// A native function that can be exported from an internal module
pub type InternalFn = fn(&mut Interpreter, JsValue, &[JsValue]) -> Result<Guarded, JsError>;

/// Definition of an export from an internal module
#[derive(Clone)]
pub enum InternalExport {
    /// A native function
    Function {
        name: String,
        func: InternalFn,
        arity: usize,
    },
    /// A constant value
    Value(JsValue),
}

/// How an internal module is defined
#[derive(Clone)]
pub enum InternalModuleKind {
    /// Native module with Rust functions
    Native(Vec<(String, InternalExport)>),
    /// Source module (TypeScript code that may import from other internal modules)
    Source(String),
}

/// Definition of an internal module that can be imported from JavaScript.
///
/// Internal modules allow you to expose Rust functions to JavaScript code.
/// They're imported using the specifier you define (e.g., `import { x } from "mymodule"`).
///
/// # Native Module (Rust functions)
///
/// ```
/// use tsrun::{InternalModule, JsValue, Guarded, JsError, Interpreter};
///
/// fn add(_: &mut Interpreter, _: JsValue, args: &[JsValue]) -> Result<Guarded, JsError> {
///     let a = args.first().and_then(|v| v.as_number()).unwrap_or(0.0);
///     let b = args.get(1).and_then(|v| v.as_number()).unwrap_or(0.0);
///     Ok(Guarded::unguarded(JsValue::from(a + b)))
/// }
///
/// let module = InternalModule::native("math:utils")
///     .with_function("add", add, 2)
///     .with_value("PI", JsValue::from(3.14159))
///     .build();
///
/// assert_eq!(module.specifier, "math:utils");
/// ```
///
/// # Source Module (TypeScript code)
///
/// ```
/// use tsrun::InternalModule;
///
/// let module = InternalModule::source("config:defaults", r#"
///     export const timeout = 5000;
///     export const retries = 3;
/// "#);
/// ```
pub struct InternalModule {
    /// The import specifier (e.g., "tsrun:host", "eval:fs")
    pub specifier: String,
    /// How the module is implemented
    pub kind: InternalModuleKind,
}

impl InternalModule {
    /// Create a native module builder
    pub fn native(specifier: impl Into<String>) -> NativeModuleBuilder {
        NativeModuleBuilder {
            specifier: specifier.into(),
            exports: Vec::new(),
        }
    }

    /// Create a source module
    pub fn source(specifier: impl Into<String>, source: impl Into<String>) -> Self {
        Self {
            specifier: specifier.into(),
            kind: InternalModuleKind::Source(source.into()),
        }
    }
}

/// Builder for creating native internal modules
pub struct NativeModuleBuilder {
    specifier: String,
    exports: Vec<(String, InternalExport)>,
}

impl NativeModuleBuilder {
    /// Add a function export
    pub fn with_function(
        mut self,
        name: impl Into<String>,
        func: InternalFn,
        arity: usize,
    ) -> Self {
        let name = name.into();
        self.exports
            .push((name.clone(), InternalExport::Function { name, func, arity }));
        self
    }

    /// Add a value export
    pub fn with_value(mut self, name: impl Into<String>, value: JsValue) -> Self {
        self.exports
            .push((name.into(), InternalExport::Value(value)));
        self
    }

    /// Build the internal module
    pub fn build(self) -> InternalModule {
        InternalModule {
            specifier: self.specifier,
            kind: InternalModuleKind::Native(self.exports),
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Interpreter Configuration
// ═══════════════════════════════════════════════════════════════════════════════

/// Configuration for creating an Interpreter
#[derive(Default)]
pub struct InterpreterConfig {
    /// Internal modules available for import
    pub internal_modules: Vec<InternalModule>,

    /// Custom RegExp provider.
    ///
    /// If `None`, uses the default provider:
    /// - `FancyRegexProvider` when `regex` feature is enabled
    /// - `NoOpRegExpProvider` otherwise
    pub regexp_provider: Option<Rc<dyn platform::RegExpProvider>>,
}