Skip to main content

drawland_script/
lib.rs

1//! draw.land profiles in JavaScript.
2//!
3//! A profile is a script that calls our library (`library.js`, over the
4//! natives below); running it builds the operation graph the engine draws.
5//! The script never touches geometry: by the time anything is drawn, the
6//! interpreter is gone and only the graph is left.
7//!
8//! ```js
9//! const bldg = features.osm({ building: true })
10//! const foot = areas.polygons(bldg)
11//! draw({ id: "bldg_fill", from: fills.fill({ in: foot, pattern: "zigzag", spacing: "0.5mm", per: "feature" }) })
12//! ```
13//!
14//! Every node remembers the script line that made it, and every error (a
15//! syntax error, a wrong argument, a bad reference found by validation) comes
16//! back as `line N column M: …`, the form the web editor underlines.
17//!
18//! The sandbox is the bare language plus the library: no network, files,
19//! timers or console, no `Date` or `Math.random` (the same script always
20//! draws the same map), and loops and recursion are capped.
21
22use 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
32/// Where `view(spec, "name")` finds the script that draws in style `name`:
33/// the host's own (the command line reads `name.js` beside the profile, the
34/// web page its presets). `Err` says why there is none.
35pub type Styles = Rc<dyn Fn(&str) -> Result<String, String>>;
36
37/// What the host lends a run: a place over the one the script's `output`
38/// gives (`(lat, lng)`: the command line's `--lat`/`--lng` and `--address`;
39/// `world` answers for it), and the styles views can name.
40#[derive(Clone, Default)]
41pub struct Host {
42    pub place: Option<(f64, f64)>,
43    pub styles: Option<Styles>,
44}
45
46/// How deep views may nest (a view drawing a style that has views of its own).
47const VIEW_DEPTH: usize = 4;
48
49/// The name scripts run under; positions in other sources (the library) are
50/// not the user's.
51pub const SCRIPT_PATH: &str = "profile.js";
52const LIBRARY_PATH: &str = "drawland:library";
53
54/// The most loop iterations one loop may run, and the deepest recursion: a
55/// mistaken `while (true)` ends with an error instead of hanging the page.
56pub 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    /// The script asked `world` about a place its output names only by this
64    /// address: look it up and run the script again with `evaluate_at`.
65    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
79/// Run `source` and return the graph it built, validated. The place is the
80/// one its own `output` gives, and views can name no style.
81pub fn evaluate(source: &str) -> Result<Grammar, ScriptError> {
82    evaluate_in(source, &Host::default())
83}
84
85/// Run `source` with what `host` lends it.
86pub 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
98/// A draft of `source`'s graph, for a page following a drag: the same graph
99/// but with every `remap` warp left out, since sampling one runs the script's
100/// function hundreds of times. `true` with it when something was left out, so
101/// the page knows to run the script in full once the drag settles.
102pub 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
119/// The sandbox, the natives and the library.
120fn 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// ---------------------------------------------------------------------------
159// What the script has built so far
160// ---------------------------------------------------------------------------
161
162#[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    /// For a view: its id, corner, and the output keys that override what
176    /// the style itself asks (the place, the rectangle's size, no padding).
177    view: Option<ViewHead>,
178    /// The host's place, `(lat, lng)`, over the one the output asks.
179    place: Option<(f64, f64)>,
180    /// The frame `page` and `world` answer from, once worked out.
181    frame: Option<drawland_core::frame::Frame>,
182    /// An address `world` needed coordinates for (see `ScriptError::address`).
183    wanted_address: Option<String>,
184    /// The last error a native raised, with the user's line: a JS error
185    /// thrown from the library would otherwise point inside the library.
186    failure: Option<(String, Option<At>)>,
187}
188
189thread_local! {
190    /// Inside `evaluate_draft`: whether a `remap` has been left out yet.
191    static DRAFT: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
192    /// The host's styles, for the run in progress.
193    static STYLES: RefCell<Option<Styles>> = const { RefCell::new(None) };
194    /// The graph being built, innermost last: a view builds its own.
195    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            // A view whose style never called `output`: its own keys are all.
207            (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
242// ---------------------------------------------------------------------------
243// Natives
244// ---------------------------------------------------------------------------
245
246/// Where the user's script is in the call stack: the innermost call in the
247/// profile, skipping the library's own. Read from an `Error`'s `stack`, which
248/// records call sites (the frames' own positions lag inside functions).
249fn 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
277/// `dl.node(section, { op_key: … })` → the new def's reference.
278fn 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
308/// `dl.burin(callback)` → the atlas JSON the burin document built.
309///
310/// The callback is a real function in this engine, so a burin document written
311/// here has the same errors, positions and editor hints as anywhere else; the
312/// atlas it builds is burin's own, and the engine draws it later.
313fn 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
326/// `$lines.x`, `$fills.x` or `roads.outlines`.
327fn 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
419/// `dl.output(spec)` → the output as it will be: inside a view, the view's
420/// place and rectangle win over what the style asks, so a preset drawn in a
421/// view keeps its paper-independent look (pens, patterns) at the view's place.
422/// The paper's size comes back read, in mm, as `paper: { width, height }`.
423fn 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
448/// `dl.draft()` → whether this run is a draft (`evaluate_draft`), which
449/// leaves its `remap` warps out; asking in one marks the graph drafted.
450fn 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
461/// `dl.setWarp(list)` → the output's warps replaced, so `page` and `world`
462/// answer through them: how `output` samples a `remap` through the warps
463/// before it.
464fn 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
478/// The output `page` and `world` describe: the script's own, or inside a
479/// view whose style never called `output`, the view's keys.
480fn 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
493/// The frame `world` and the conversions answer from, worked out once per output.
494fn 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
519/// `dl.sheet(asked)` → what the output says without a place: the paper's
520/// `width` and `height` in mm, the `scale`, `bearing` and `projection` (the
521/// output's, or the view's).
522fn 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
535/// `dl.world(asked)` → the ground under the page: its centre, and its
536/// bounds round the page's edge.
537fn 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
549/// `dl.toPage(lat, lng)` → `[x, y]`, page mm.
550fn 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
557/// `dl.toWorld(x, y)` → `{ lat, lng }`.
558fn 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
567/// A view's id, corner, ink, and the output keys its spec sets.
568type ViewHead = (String, (f64, f64), serde_json::Map<String, Value>, Option<String>);
569
570/// The output keys a view's spec sets: `{ id, at: [x, y], size: [w, h] }` in
571/// page mm, and the place (`lat`, `lng`, `scale`, `bearing`, `tileZoom`,
572/// `projection`). The view's id and corner, and those keys.
573fn 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
604/// `dl.viewBegin(spec)`: the graph the next calls build is the view's.
605fn 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
618/// `dl.viewEnd(ok)`: the view's graph is done; it joins the page's views
619/// (`ok`), or is dropped (the style threw).
620fn 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
630/// `dl.viewStyle(spec, name)`: a view drawn in a style the host lends by
631/// name, run on its own (its top-level names never meet the page's).
632fn 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
654/// A finished view's graph, added to the page's views; its id back.
655fn 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
673// ---------------------------------------------------------------------------
674// Errors
675// ---------------------------------------------------------------------------
676
677/// `profile: …` and the like: the grammar's own prefixes mean nothing to a
678/// script author.
679fn strip_kind(message: &str) -> String {
680    message.strip_prefix("profile: ").unwrap_or(message).to_string()
681}
682
683/// The first `line N column M` in a message.
684fn 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
692/// The frame's old calls, and what replaced them: an older script that still
693/// calls one is told the new name instead of only "not a callable function".
694const 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    // `x is not defined` comes without a reliable position: the first use of
727    // the name.
728    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    // Runtime errors: `TypeError: … (profile.js:2:7)`.
734    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    // Syntax errors: `… at line 1, col 9`.
744    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
757/// Where `name` first appears as a whole word.
758fn 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
776/// Every function the library defines, as `areas.union` or `draw`, sorted
777/// (properties such as `page.width` are not calls, and not listed):
778/// what `drawland.d.ts` must declare.
779pub 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;