1use boa_engine::{js_string, Context, JsError, JsNativeError, JsResult, JsValue, NativeFunction, Source};
23use drawland_core::grammar::{self, At, Clip, Compose, Def, Draw, Grammar, Id, Mask, Name, Section, Target};
24use drawland_core::profile::{OutputSpec, StrokeSpec};
25use serde_json::Value;
26use std::cell::RefCell;
27use std::rc::Rc;
28use std::fmt;
29
30const LIBRARY: &str = include_str!("library.js");
31
32pub type Styles = Rc<dyn Fn(&str) -> Result<String, String>>;
36
37#[derive(Clone, Default)]
41pub struct Host {
42 pub place: Option<(f64, f64)>,
43 pub styles: Option<Styles>,
44}
45
46const VIEW_DEPTH: usize = 4;
48
49pub const SCRIPT_PATH: &str = "profile.js";
52const LIBRARY_PATH: &str = "drawland:library";
53
54pub const LOOP_LIMIT: u64 = 1_000_000;
57pub const RECURSION_LIMIT: usize = 256;
58
59#[derive(Debug, Clone, PartialEq)]
60pub struct ScriptError {
61 pub message: String,
62 pub at: Option<At>,
63 pub address: Option<String>,
66}
67
68impl fmt::Display for ScriptError {
69 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
70 match self.at {
71 Some(at) => write!(f, "{at}: {}", self.message),
72 None => f.write_str(&self.message),
73 }
74 }
75}
76
77impl std::error::Error for ScriptError {}
78
79pub fn evaluate(source: &str) -> Result<Grammar, ScriptError> {
82 evaluate_in(source, &Host::default())
83}
84
85pub fn evaluate_in(source: &str, host: &Host) -> Result<Grammar, ScriptError> {
87 STYLES.with(|s| *s.borrow_mut() = host.styles.clone());
88 BUILDER.with(|b| b.borrow_mut().clear());
89 BUILDER.with(|b| b.borrow_mut().push(Builder { place: host.place, ..Builder::default() }));
90 let result = run(source);
91 let builder = BUILDER.with(|b| b.borrow_mut().pop()).unwrap_or_default();
92 BUILDER.with(|b| b.borrow_mut().clear());
93 STYLES.with(|s| s.borrow_mut().take());
94 result.map_err(|e| ScriptError { address: builder.wanted_address.clone(), ..e })?;
95 builder.finish()
96}
97
98pub fn evaluate_draft(source: &str, host: &Host) -> Result<(Grammar, bool), ScriptError> {
103 DRAFT.with(|d| d.set(Some(false)));
104 let result = evaluate_in(source, host);
105 let drafted = DRAFT.with(|d| d.take()).unwrap_or(false);
106 result.map(|g| (g, drafted))
107}
108
109fn run(source: &str) -> Result<(), ScriptError> {
110 let mut ctx = Context::default();
111 let limits = ctx.runtime_limits_mut();
112 limits.set_loop_iteration_limit(LOOP_LIMIT);
113 limits.set_recursion_limit(RECURSION_LIMIT);
114 install(&mut ctx).map_err(|e| ScriptError { message: format!("library: {e}"), at: None, address: None })?;
115 let script = Source::from_bytes(source).with_path(std::path::Path::new(SCRIPT_PATH));
116 ctx.eval(script).map(|_| ()).map_err(|e| script_error(e, source, &mut ctx))
117}
118
119fn install(ctx: &mut Context) -> JsResult<()> {
121 ctx.eval(Source::from_bytes(
122 "delete globalThis.Date; delete Math.random; delete globalThis.WeakRef; delete globalThis.FinalizationRegistry;",
123 ))?;
124 let natives: [(&str, usize, fn(&JsValue, &[JsValue], &mut Context) -> JsResult<JsValue>); 19] = [
125 ("node", 2, native_node),
126 ("draw", 1, native_draw),
127 ("order", 1, native_order),
128 ("mask", 1, native_mask),
129 ("clip", 1, native_clip),
130 ("optimize", 1, native_optimize),
131 ("output", 1, native_output),
132 ("setWarp", 1, native_set_warp),
133 ("draft", 0, native_draft),
134 ("sheet", 1, native_sheet),
135 ("world", 1, native_world),
136 ("toPage", 2, native_to_page),
137 ("toWorld", 2, native_to_world),
138 ("title", 1, native_title),
139 ("fail", 1, native_fail),
140 ("burin", 1, native_burin),
141 ("viewBegin", 1, native_view_begin),
142 ("viewEnd", 1, native_view_end),
143 ("viewStyle", 2, native_view_style),
144 ];
145 let dl = boa_engine::object::ObjectInitializer::new(ctx).build();
146 for (name, arity, f) in natives {
147 let function = boa_engine::object::FunctionObjectBuilder::new(ctx.realm(), NativeFunction::from_fn_ptr(f))
148 .name(js_string!(name))
149 .length(arity)
150 .build();
151 dl.set(js_string!(name), function, false, ctx)?;
152 }
153 ctx.register_global_property(js_string!("__drawland"), dl, boa_engine::property::Attribute::all())?;
154 ctx.eval(Source::from_bytes(LIBRARY).with_path(std::path::Path::new(LIBRARY_PATH)))?;
155 Ok(())
156}
157
158#[derive(Default)]
163struct Builder {
164 title: Option<String>,
165 output: Option<OutputSpec>,
166 defs: Vec<Def>,
167 count: usize,
168 draw: Vec<Draw>,
169 order: Vec<Id>,
170 order_at: Option<At>,
171 masks: Vec<(String, Mask)>,
172 clip: Option<Clip>,
173 optimize: Vec<drawland_core::optimize::OptimizeStep>,
174 views: Vec<grammar::View>,
175 view: Option<ViewHead>,
178 place: Option<(f64, f64)>,
180 frame: Option<drawland_core::frame::Frame>,
182 wanted_address: Option<String>,
184 failure: Option<(String, Option<At>)>,
187}
188
189thread_local! {
190 static DRAFT: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
192 static STYLES: RefCell<Option<Styles>> = const { RefCell::new(None) };
194 static BUILDER: RefCell<Vec<Builder>> = const { RefCell::new(Vec::new()) };
196}
197
198fn with<T>(f: impl FnOnce(&mut Builder) -> T) -> T {
199 BUILDER.with(|b| f(b.borrow_mut().last_mut().expect("natives run inside evaluate")))
200}
201
202impl Builder {
203 fn finish(self) -> Result<Grammar, ScriptError> {
204 let output = match (self.output, &self.view) {
205 (Some(o), _) => o,
206 (None, Some((_, _, keys, _))) => serde_json::from_value(Value::Object(keys.clone()))
208 .map_err(|e| ScriptError { message: format!("view: {e}"), at: None, address: None })?,
209 (None, None) => serde_json::from_value(Value::Object(Default::default())).expect("an empty output is valid"),
210 };
211 let mut sections: Vec<(Section, Vec<Def>)> = Vec::new();
212 for section in Section::ALL {
213 let defs: Vec<Def> = self.defs.iter().filter(|d| d.op.section() == section).cloned().collect();
214 if !defs.is_empty() {
215 sections.push((section, defs));
216 }
217 }
218 let groups: Vec<String> = self.draw.iter().map(Draw::group).collect();
219 if let Some(missing) = self.order.iter().find(|id| !groups.contains(&id.0)) {
220 return Err(ScriptError {
221 message: format!("compose.order names {:?}, which no draw writes", missing.0),
222 at: self.order_at,
223 address: None,
224 });
225 }
226 let compose = Compose {
227 order: self.order,
228 masks: self.masks,
229 clip: Default::default(),
230 clip_default: self.clip.unwrap_or(Clip::Auto),
231 optimize: self.optimize,
232 };
233 let graph = Grammar { title: self.title, output, sections, draw: self.draw, compose, views: self.views };
234 grammar::validate(&graph).map_err(|e| {
235 let message = e.to_string();
236 ScriptError { at: find_at(&message), message, address: None }
237 })?;
238 Ok(graph)
239 }
240}
241
242fn user_at(ctx: &mut Context) -> Option<At> {
250 let error = ctx.intrinsics().constructors().error().constructor();
251 let error = error.construct(&[], None, ctx).ok()?;
252 let stack = error.get(js_string!("stack"), ctx).ok()?.to_string(ctx).ok()?.to_std_string_escaped();
253 let marker = format!("({SCRIPT_PATH}:");
254 stack.lines().find_map(|line| {
255 let spot = &line[line.find(&marker)? + marker.len()..];
256 let (l, c) = spot.trim_end_matches(')').split_once(':')?;
257 Some(At(l.parse().ok()?, c.parse().ok()?))
258 })
259}
260
261fn fail(ctx: &mut Context, message: impl Into<String>) -> JsError {
262 let message = message.into();
263 let at = user_at(ctx);
264 with(|b| b.failure = Some((message.clone(), at)));
265 JsNativeError::typ().with_message(message).into()
266}
267
268fn json_arg(args: &[JsValue], i: usize, ctx: &mut Context) -> JsResult<Value> {
269 let value = args.get(i).cloned().unwrap_or_default();
270 Ok(value.to_json(ctx)?.unwrap_or(Value::Null))
271}
272
273fn string_arg(args: &[JsValue], i: usize, ctx: &mut Context) -> JsResult<String> {
274 Ok(args.get(i).cloned().unwrap_or_default().to_string(ctx)?.to_std_string_escaped())
275}
276
277fn native_node(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
279 let section = string_arg(args, 0, ctx)?;
280 let op = json_arg(args, 1, ctx)?;
281 let at = user_at(ctx);
282 let section = Section::ALL.into_iter().find(|s| s.key() == section).ok_or_else(|| fail(ctx, "unknown section"))?;
283 let key = op.as_object().and_then(|o| o.keys().next().cloned()).unwrap_or_default();
284 let parsed = grammar::op_from_json(section, op).map_err(|e| fail(ctx, strip_kind(&e.to_string())))?;
285 let short = key
286 .strip_prefix("tools_")
287 .or_else(|| key.strip_prefix("engine_"))
288 .or_else(|| key.strip_suffix("_select"))
289 .unwrap_or(&key);
290 let name = match key.strip_prefix("module_") {
291 Some(module) => {
292 if with(|b| b.defs.iter().any(|d| d.name == module)) {
293 return Err(fail(ctx, format!("modules.{module} is called twice; call it once and reuse its outputs")));
294 }
295 module.to_string()
296 }
297 None => with(|b| {
298 b.count += 1;
299 format!("{short}_{}", b.count)
300 }),
301 };
302 let def = Def { name, op: parsed, at };
303 let reference = def.reference().to_string();
304 with(|b| b.defs.push(def));
305 Ok(JsValue::from(js_string!(reference)))
306}
307
308fn native_burin(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
314 let callback = args.first().cloned().unwrap_or_default();
315 match burin_map_script::run_builder(ctx, &callback, SCRIPT_PATH) {
316 Ok(atlas) => Ok(JsValue::from(js_string!(atlas.to_string()))),
317 Err(e) => {
318 let message = e.message;
319 let at = e.at.map(|a| At(a.0, a.1));
320 with(|b| b.failure = Some((message.clone(), at)));
321 Err(JsNativeError::typ().with_message(message).into())
322 }
323 }
324}
325
326fn target(text: &str) -> Result<Target, String> {
328 if text.starts_with('$') {
329 return Name::parse(text).map(|name| Target { module: None, name });
330 }
331 match text.split_once('.') {
332 Some((module, output)) => Ok(Target {
333 module: Some(module.to_string()),
334 name: Name { section: Section::Lines, name: output.to_string() },
335 }),
336 None => Err(format!("{text:?} is not a reference")),
337 }
338}
339
340fn native_draw(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
341 let spec = json_arg(args, 0, ctx)?;
342 let at = user_at(ctx);
343 let from = target(spec["from"].as_str().unwrap_or_default()).map_err(|e| fail(ctx, format!("draw: {e}")))?;
344 let stroke = match spec.get("stroke") {
345 None => None,
346 Some(s) => Some(
347 serde_json::from_value::<StrokeSpec>(s.clone())
348 .map_err(|e| fail(ctx, format!("draw: stroke {s}: {e}; write solid, dash, dotted, none or {{ style, dash, gap, mark, color, width, cap, join }}")))?,
349 ),
350 };
351 let id = spec.get("id").and_then(Value::as_str).map(str::to_string);
352 let draw = Draw { id, from, stroke, at };
353 let group = draw.group();
354 if with(|b| b.draw.iter().any(|d| d.group() == group)) {
355 return Err(fail(ctx, format!("draw: the id {group:?} is already drawn")));
356 }
357 with(|b| b.draw.push(draw));
358 Ok(JsValue::from(js_string!(group)))
359}
360
361fn native_order(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
362 let ids: Vec<String> = serde_json::from_value(json_arg(args, 0, ctx)?).unwrap_or_default();
363 let at = user_at(ctx);
364 with(|b| {
365 b.order = ids.into_iter().map(Id).collect();
366 b.order_at = at;
367 });
368 Ok(JsValue::undefined())
369}
370
371fn native_mask(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
372 let spec = json_arg(args, 0, ctx)?;
373 let at = user_at(ctx);
374 let from = target(spec["from"].as_str().unwrap_or_default()).map_err(|e| fail(ctx, format!("compose.mask: {e}")))?;
375 let occludes: Vec<String> = serde_json::from_value(spec["occludes"].clone()).unwrap_or_default();
376 let name = with(|b| match spec["name"].as_str() {
377 Some(n) => n.to_string(),
378 None => format!("mask_{}", b.masks.len() + 1),
379 });
380 if with(|b| b.masks.iter().any(|(n, _)| *n == name)) {
381 return Err(fail(ctx, format!("compose.mask: the name {name:?} is already used")));
382 }
383 with(|b| b.masks.push((name, Mask { from, occludes: occludes.into_iter().map(Id).collect(), at })));
384 Ok(JsValue::undefined())
385}
386
387fn native_clip(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
388 let clip = match json_arg(args, 0, ctx)? {
389 Value::String(s) if s == "auto" => Clip::Auto,
390 Value::String(s) if s == "none" => Clip::None,
391 Value::Array(items) => Clip::Areas(
392 items
393 .iter()
394 .map(|v| Name::parse(v.as_str().unwrap_or_default()))
395 .collect::<Result<_, _>>()
396 .map_err(|e| fail(ctx, format!("compose.clip: {e}")))?,
397 ),
398 other => return Err(fail(ctx, format!("compose.clip: {other} is not auto, none or a list of areas"))),
399 };
400 with(|b| b.clip = Some(clip));
401 Ok(JsValue::undefined())
402}
403
404fn native_optimize(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
405 let spec = json_arg(args, 0, ctx)?;
406 let at = user_at(ctx);
407 let raw: grammar::RawOptimizeStep = serde_json::from_value(spec)
408 .map_err(|e| fail(ctx, format!("compose: {}", strip_kind(&e.to_string()))))?;
409 let step = drawland_core::optimize::OptimizeStep {
410 layers: raw.layers.into_iter().map(Id).collect(),
411 except: raw.except.into_iter().map(Id).collect(),
412 op: raw.op,
413 at,
414 };
415 with(|b| b.optimize.push(step));
416 Ok(JsValue::undefined())
417}
418
419fn native_output(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
424 let mut spec = json_arg(args, 0, ctx)?;
425 if let (Some(obj), Some(keys)) = (spec.as_object_mut(), with(|b| b.view.as_ref().map(|v| v.2.clone()))) {
426 for k in ["address", "slices"] {
427 obj.remove(k);
428 }
429 obj.extend(keys);
430 }
431 if let (Some(obj), Some((lat, lng))) = (spec.as_object_mut(), with(|b| b.place)) {
432 obj.remove("address");
433 obj.insert("lat".into(), Value::from(lat));
434 obj.insert("lng".into(), Value::from(lng));
435 }
436 with(|b| b.frame = None);
437 let output: OutputSpec = serde_json::from_value(spec.clone()).map_err(|e| fail(ctx, format!("output: {e}")))?;
438 let paper = serde_json::json!({ "width": output.width.0, "height": output.height.0 });
439 if with(|b| b.output.replace(output).is_some()) {
440 return Err(fail(ctx, "output is set twice"));
441 }
442 if let Some(obj) = spec.as_object_mut() {
443 obj.insert("paper".into(), paper);
444 }
445 JsValue::from_json(&spec, ctx)
446}
447
448fn native_draft(_: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult<JsValue> {
451 let draft = DRAFT.with(|d| match d.get() {
452 Some(_) => {
453 d.set(Some(true));
454 true
455 }
456 None => false,
457 });
458 Ok(JsValue::from(draft))
459}
460
461fn native_set_warp(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
465 let spec = json_arg(args, 0, ctx)?;
466 let warps: drawland_core::warp::Warps =
467 serde_json::from_value(spec).map_err(|e| fail(ctx, format!("output.warp: {e}")))?;
468 let set = with(|b| {
469 b.frame = None;
470 b.output.as_mut().map(|o| o.warp = warps).is_some()
471 });
472 if !set {
473 return Err(fail(ctx, "output.warp: call output({ … }) first"));
474 }
475 Ok(JsValue::undefined())
476}
477
478fn current_output(ctx: &mut Context, asked: &str) -> JsResult<OutputSpec> {
481 let found = with(|b| match (&b.output, &b.view) {
482 (Some(o), _) => Some(Ok(o.clone())),
483 (None, Some((_, _, keys, _))) => Some(serde_json::from_value(Value::Object(keys.clone())).map_err(|e| e.to_string())),
484 (None, None) => None,
485 });
486 match found {
487 Some(Ok(o)) => Ok(o),
488 Some(Err(e)) => Err(fail(ctx, format!("{asked}: {e}"))),
489 None => Err(fail(ctx, format!("{asked}: call output({{ … }}) first"))),
490 }
491}
492
493fn current_frame(ctx: &mut Context, asked: &str) -> JsResult<drawland_core::frame::Frame> {
495 if let Some(f) = with(|b| b.frame.clone()) {
496 return Ok(f);
497 }
498 let spec = current_output(ctx, asked)?;
499 let (lat, lng) = match (spec.lat, spec.lng, &spec.address) {
500 (Some(lat), Some(lng), _) => (lat, lng),
501 (_, _, Some(address)) => {
502 with(|b| b.wanted_address = Some(address.clone()));
503 return Err(fail(
504 ctx,
505 format!("{asked}: the output's place is the address {address:?}; a script can't look it up, so give the output a lat and lng"),
506 ));
507 }
508 _ => return Err(fail(ctx, format!("{asked}: the output has no place; give it a lat and lng"))),
509 };
510 let frame = drawland_core::frame::Frame::new(&spec, (lng, lat));
511 with(|b| b.frame = Some(frame.clone()));
512 Ok(frame)
513}
514
515fn number_arg(args: &[JsValue], i: usize, ctx: &mut Context) -> JsResult<f64> {
516 args.get(i).cloned().unwrap_or_default().to_number(ctx)
517}
518
519fn native_sheet(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
523 let asked = string_arg(args, 0, ctx)?;
524 let o = current_output(ctx, &asked)?;
525 let json = serde_json::json!({
526 "width": o.width.0,
527 "height": o.height.0,
528 "scale": o.scale.0,
529 "bearing": o.bearing,
530 "projection": o.projection,
531 });
532 JsValue::from_json(&json, ctx)
533}
534
535fn native_world(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
538 let asked = string_arg(args, 0, ctx)?;
539 let f = current_frame(ctx, &asked)?;
540 let b = f.bounds();
541 let json = serde_json::json!({
542 "lat": f.output.center.1,
543 "lng": f.output.center.0,
544 "bounds": { "north": b.north, "south": b.south, "east": b.east, "west": b.west },
545 });
546 JsValue::from_json(&json, ctx)
547}
548
549fn native_to_page(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
551 let (lat, lng) = (number_arg(args, 0, ctx)?, number_arg(args, 1, ctx)?);
552 let f = current_frame(ctx, "world.toPage")?;
553 let (x, y) = f.to_page(lng, lat);
554 JsValue::from_json(&serde_json::json!([x, y]), ctx)
555}
556
557fn native_to_world(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
559 let (x, y) = (number_arg(args, 0, ctx)?, number_arg(args, 1, ctx)?);
560 let f = current_frame(ctx, "page.toWorld")?;
561 match f.to_world(x, y) {
562 Some((lng, lat)) => JsValue::from_json(&serde_json::json!({ "lat": lat, "lng": lng }), ctx),
563 None => Err(fail(ctx, format!("page.toWorld: [{x}, {y}] is off the edge of the projection's world"))),
564 }
565}
566
567type ViewHead = (String, (f64, f64), serde_json::Map<String, Value>, Option<String>);
569
570fn view_keys(spec: &Value) -> Result<ViewHead, String> {
574 let o = spec.as_object().ok_or("view takes { at, size, lat, lng, scale, … }")?;
575 let pair = |k: &str| -> Result<(f64, f64), String> {
576 match o.get(k).and_then(Value::as_array).map(|a| a.iter().map(Value::as_f64).collect::<Vec<_>>()) {
577 Some(v) if v.len() == 2 && v.iter().all(Option::is_some) => Ok((v[0].unwrap(), v[1].unwrap())),
578 _ => Err(format!("view.{k} is [x, y] in millimetres")),
579 }
580 };
581 let at = pair("at")?;
582 let (w, h) = pair("size")?;
583 if w <= 0.0 || h <= 0.0 {
584 return Err("view.size must be positive".into());
585 }
586 let id = o.get("id").and_then(Value::as_str).ok_or("view.id names the view, as compose.mask occludes it")?.to_string();
587 let mut keys = serde_json::Map::new();
588 keys.insert("width".into(), Value::String(format!("{w}mm")));
589 keys.insert("height".into(), Value::String(format!("{h}mm")));
590 keys.insert("padding".into(), Value::from(0));
591 for k in ["lat", "lng", "scale", "bearing", "tileZoom", "projection"] {
592 if let Some(v) = o.get(k) {
593 keys.insert(k.into(), v.clone());
594 }
595 }
596 let ink = match o.get("ink") {
597 None | Some(Value::Null) => None,
598 Some(Value::String(c)) if !c.trim().is_empty() => Some(c.trim().to_string()),
599 Some(v) => return Err(format!("view.ink is a colour like \"#e4572e\", got {v}")),
600 };
601 Ok((id, at, keys, ink))
602}
603
604fn native_view_begin(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
606 let spec = json_arg(args, 0, ctx)?;
607 let view = view_keys(&spec).map_err(|e| fail(ctx, e))?;
608 if BUILDER.with(|b| b.borrow().len()) > VIEW_DEPTH {
609 return Err(fail(ctx, "views nest too deep"));
610 }
611 if with(|b| b.views.iter().any(|v| v.id == view.0)) {
612 return Err(fail(ctx, format!("two views are called {:?}", view.0)));
613 }
614 BUILDER.with(|b| b.borrow_mut().push(Builder { view: Some(view), ..Builder::default() }));
615 Ok(JsValue::undefined())
616}
617
618fn native_view_end(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
621 let ok = args.first().is_some_and(JsValue::to_boolean);
622 let inner = BUILDER.with(|b| if b.borrow().len() > 1 { b.borrow_mut().pop() } else { None });
623 let Some(inner) = inner else { return Err(fail(ctx, "viewEnd without viewBegin")) };
624 if !ok {
625 return Ok(JsValue::undefined());
626 }
627 attach(inner, ctx)
628}
629
630fn native_view_style(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
633 let spec = json_arg(args, 0, ctx)?;
634 let id = string_arg(args, 1, ctx)?;
635 let view = view_keys(&spec).map_err(|e| fail(ctx, e))?;
636 let source = match STYLES.with(|s| s.borrow().clone()) {
637 Some(styles) => styles(&id),
638 None => Err("this host lends no styles by name; pass a function that draws".to_string()),
639 };
640 let source = source.map_err(|e| fail(ctx, format!("no style {id:?}: {e}")))?;
641 if BUILDER.with(|b| b.borrow().len()) > VIEW_DEPTH {
642 return Err(fail(ctx, "views nest too deep"));
643 }
644 let view_id = view.0.clone();
645 BUILDER.with(|b| b.borrow_mut().push(Builder { view: Some(view), ..Builder::default() }));
646 let result = run(&source);
647 let inner = BUILDER.with(|b| b.borrow_mut().pop()).expect("pushed above");
648 if let Err(e) = result {
649 return Err(fail(ctx, format!("view {view_id} ({id}): {e}")));
650 }
651 attach(inner, ctx)
652}
653
654fn attach(inner: Builder, ctx: &mut Context) -> JsResult<JsValue> {
656 let (id, at, _, ink) = inner.view.clone().expect("a view builder");
657 let grammar = inner.finish().map_err(|e| fail(ctx, format!("view {id}: {}", e.message)))?;
658 with(|b| b.views.push(grammar::View { id: id.clone(), at, grammar: Box::new(grammar), ink }));
659 Ok(JsValue::from(js_string!(id)))
660}
661
662fn native_title(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
663 let text = string_arg(args, 0, ctx)?;
664 with(|b| b.title = Some(text));
665 Ok(JsValue::undefined())
666}
667
668fn native_fail(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
669 let message = string_arg(args, 0, ctx)?;
670 Err(fail(ctx, message))
671}
672
673fn strip_kind(message: &str) -> String {
680 message.strip_prefix("profile: ").unwrap_or(message).to_string()
681}
682
683fn find_at(message: &str) -> Option<At> {
685 let start = message.find("line ")?;
686 let rest = &message[start + 5..];
687 let (line, rest) = rest.split_once(" column ")?;
688 let column: String = rest.chars().take_while(char::is_ascii_digit).collect();
689 Some(At(line.parse().ok()?, column.parse().ok()?))
690}
691
692const RENAMED: [(&str, &str); 3] = [
695 ("engine.frame(", "engine.frame() is now page.frame (a property: no parentheses)"),
696 ("engine.scale(", "engine.scale() is now world.scale (a property: no parentheses)"),
697 ("engine.paper(", "engine.paper() is now page: page.width and page.height"),
698];
699
700fn script_error(err: JsError, source: &str, ctx: &mut Context) -> ScriptError {
701 let mut e = raw_script_error(err, source, ctx);
702 if e.message.contains("not a callable function") {
703 let line = e.at.and_then(|At(l, _)| source.lines().nth(l.saturating_sub(1) as usize)).unwrap_or_default();
704 if let Some((_, hint)) = RENAMED.iter().find(|(old, _)| line.contains(old)) {
705 e.message = format!("{}: {hint}", e.message);
706 }
707 }
708 e
709}
710
711fn raw_script_error(err: JsError, source: &str, ctx: &mut Context) -> ScriptError {
712 let native = err.try_native(ctx).ok();
713 let message = native.as_ref().map(|n| n.message().to_string());
714 if let (Some(message), Some((failed, at))) = (&message, with(|b| b.failure.take())) {
715 if *message == failed {
716 return ScriptError { message: failed, at, address: None };
717 }
718 }
719 let text = err.to_string();
720 let first = text.lines().next().unwrap_or_default();
721 let kind = native.as_ref().map(|n| format!("{}", n.kind())).unwrap_or_default();
722 let message = match (&message, kind.is_empty()) {
723 (Some(m), false) => format!("{kind}: {m}"),
724 _ => first.split(" (").next().unwrap_or(first).to_string(),
725 };
726 if let Some(name) = message.strip_prefix("ReferenceError: ").and_then(|m| m.strip_suffix(" is not defined")) {
729 if let Some(at) = first_use(source, name) {
730 return ScriptError { at: Some(at), message, address: None };
731 }
732 }
733 let marker = format!("({SCRIPT_PATH}:");
735 if let Some(i) = first.rfind(&marker) {
736 let spot = &first[i + marker.len()..first.len().saturating_sub(1)];
737 if let Some((line, column)) = spot.split_once(':') {
738 if let (Ok(line), Ok(column)) = (line.parse(), column.parse()) {
739 return ScriptError { message, at: Some(At(line, column)), address: None };
740 }
741 }
742 }
743 if let Some(i) = first.rfind(" at line ") {
745 let spot = &first[i + 9..];
746 if let Some((line, column)) = spot.split_once(", col ") {
747 let column: String = column.chars().take_while(char::is_ascii_digit).collect();
748 if let (Ok(line), Ok(column)) = (line.trim().parse(), column.parse()) {
749 let message = format!("SyntaxError: {}", first[..i].trim_start_matches("SyntaxError: "));
750 return ScriptError { message, at: Some(At(line, column)), address: None };
751 }
752 }
753 }
754 ScriptError { message, at: None, address: None }
755}
756
757fn first_use(source: &str, name: &str) -> Option<At> {
759 let word = |c: char| c.is_alphanumeric() || c == '_' || c == '$';
760 for (i, line) in source.lines().enumerate() {
761 let mut from = 0;
762 while let Some(j) = line[from..].find(name) {
763 let start = from + j;
764 let end = start + name.len();
765 let before = line[..start].chars().next_back();
766 let after = line[end..].chars().next();
767 if !before.is_some_and(|c| word(c) || c == '.') && !after.is_some_and(word) {
768 return Some(At(i as u32 + 1, line[..start].chars().count() as u32 + 1));
769 }
770 from = end;
771 }
772 }
773 None
774}
775
776pub fn library_names() -> Result<Vec<String>, ScriptError> {
780 BUILDER.with(|b| b.borrow_mut().push(Builder::default()));
781 let mut ctx = Context::default();
782 install(&mut ctx).map_err(|e| ScriptError { message: format!("library: {e}"), at: None, address: None })?;
783 let listing = ctx
784 .eval(Source::from_bytes(
785 "JSON.stringify(['features','areas','engine','page','world','lines','fills','burin','ink','modules','draw','compose','output','title','view'].flatMap((n) => typeof globalThis[n] === 'function' ? [n] : [n, ...Object.keys(globalThis[n]).filter((k) => typeof Object.getOwnPropertyDescriptor(globalThis[n], k).value === 'function').map((k) => n + '.' + k)]))",
786 ))
787 .and_then(|v| v.to_string(&mut ctx))
788 .map_err(|e| ScriptError { message: e.to_string(), at: None, address: None })?
789 .to_std_string_escaped();
790 BUILDER.with(|b| b.borrow_mut().pop());
791 let mut names: Vec<String> = serde_json::from_str(&listing).unwrap_or_default();
792 names.sort();
793 Ok(names)
794}
795
796#[cfg(test)]
797mod catalog_dts;
798#[cfg(test)]
799mod tests;