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::fmt;
28
29const LIBRARY: &str = include_str!("library.js");
30
31include!(concat!(env!("OUT_DIR"), "/presets.rs"));
32
33/// How deep views may nest (a view drawing a preset that has views of its own).
34const VIEW_DEPTH: usize = 4;
35
36/// The name scripts run under; positions in other sources (the library) are
37/// not the user's.
38pub const SCRIPT_PATH: &str = "profile.js";
39const LIBRARY_PATH: &str = "drawland:library";
40
41/// The most loop iterations one loop may run, and the deepest recursion: a
42/// mistaken `while (true)` ends with an error instead of hanging the page.
43pub const LOOP_LIMIT: u64 = 1_000_000;
44pub const RECURSION_LIMIT: usize = 256;
45
46#[derive(Debug, Clone, PartialEq)]
47pub struct ScriptError {
48    pub message: String,
49    pub at: Option<At>,
50}
51
52impl fmt::Display for ScriptError {
53    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
54        match self.at {
55            Some(at) => write!(f, "{at}: {}", self.message),
56            None => f.write_str(&self.message),
57        }
58    }
59}
60
61impl std::error::Error for ScriptError {}
62
63/// Run `source` and return the graph it built, validated.
64pub fn evaluate(source: &str) -> Result<Grammar, ScriptError> {
65    BUILDER.with(|b| b.borrow_mut().clear());
66    BUILDER.with(|b| b.borrow_mut().push(Builder::default()));
67    let result = run(source);
68    let builder = BUILDER.with(|b| b.borrow_mut().pop()).unwrap_or_default();
69    BUILDER.with(|b| b.borrow_mut().clear());
70    result?;
71    builder.finish()
72}
73
74fn run(source: &str) -> Result<(), ScriptError> {
75    let mut ctx = Context::default();
76    let limits = ctx.runtime_limits_mut();
77    limits.set_loop_iteration_limit(LOOP_LIMIT);
78    limits.set_recursion_limit(RECURSION_LIMIT);
79    install(&mut ctx).map_err(|e| ScriptError { message: format!("library: {e}"), at: None })?;
80    let script = Source::from_bytes(source).with_path(std::path::Path::new(SCRIPT_PATH));
81    ctx.eval(script).map(|_| ()).map_err(|e| script_error(e, source, &mut ctx))
82}
83
84/// The sandbox, the natives and the library.
85fn install(ctx: &mut Context) -> JsResult<()> {
86    ctx.eval(Source::from_bytes(
87        "delete globalThis.Date; delete Math.random; delete globalThis.WeakRef; delete globalThis.FinalizationRegistry;",
88    ))?;
89    let natives: [(&str, usize, fn(&JsValue, &[JsValue], &mut Context) -> JsResult<JsValue>); 13] = [
90        ("node", 2, native_node),
91        ("draw", 1, native_draw),
92        ("order", 1, native_order),
93        ("mask", 1, native_mask),
94        ("clip", 1, native_clip),
95        ("optimize", 1, native_optimize),
96        ("output", 1, native_output),
97        ("title", 1, native_title),
98        ("fail", 1, native_fail),
99        ("burin", 1, native_burin),
100        ("viewBegin", 1, native_view_begin),
101        ("viewEnd", 1, native_view_end),
102        ("viewPreset", 2, native_view_preset),
103    ];
104    let dl = boa_engine::object::ObjectInitializer::new(ctx).build();
105    for (name, arity, f) in natives {
106        let function = boa_engine::object::FunctionObjectBuilder::new(ctx.realm(), NativeFunction::from_fn_ptr(f))
107            .name(js_string!(name))
108            .length(arity)
109            .build();
110        dl.set(js_string!(name), function, false, ctx)?;
111    }
112    ctx.register_global_property(js_string!("__drawland"), dl, boa_engine::property::Attribute::all())?;
113    ctx.eval(Source::from_bytes(LIBRARY).with_path(std::path::Path::new(LIBRARY_PATH)))?;
114    Ok(())
115}
116
117// ---------------------------------------------------------------------------
118// What the script has built so far
119// ---------------------------------------------------------------------------
120
121#[derive(Default)]
122struct Builder {
123    title: Option<String>,
124    output: Option<OutputSpec>,
125    defs: Vec<Def>,
126    count: usize,
127    draw: Vec<Draw>,
128    order: Vec<Id>,
129    order_at: Option<At>,
130    masks: Vec<(String, Mask)>,
131    clip: Option<Clip>,
132    optimize: Vec<drawland_core::optimize::OptimizeStep>,
133    views: Vec<grammar::View>,
134    /// For a view: its id, corner, and the output keys that override what
135    /// the style itself asks (the place, the rectangle's size, no padding).
136    view: Option<ViewHead>,
137    /// The last error a native raised, with the user's line: a JS error
138    /// thrown from the library would otherwise point inside the library.
139    failure: Option<(String, Option<At>)>,
140}
141
142thread_local! {
143    /// The graph being built, innermost last: a view builds its own.
144    static BUILDER: RefCell<Vec<Builder>> = const { RefCell::new(Vec::new()) };
145}
146
147fn with<T>(f: impl FnOnce(&mut Builder) -> T) -> T {
148    BUILDER.with(|b| f(b.borrow_mut().last_mut().expect("natives run inside evaluate")))
149}
150
151impl Builder {
152    fn finish(self) -> Result<Grammar, ScriptError> {
153        let output = match (self.output, &self.view) {
154            (Some(o), _) => o,
155            // A view whose style never called `output`: its own keys are all.
156            (None, Some((_, _, keys, _))) => serde_json::from_value(Value::Object(keys.clone()))
157                .map_err(|e| ScriptError { message: format!("view: {e}"), at: None })?,
158            (None, None) => serde_json::from_value(Value::Object(Default::default())).expect("an empty output is valid"),
159        };
160        let mut sections: Vec<(Section, Vec<Def>)> = Vec::new();
161        for section in Section::ALL {
162            let defs: Vec<Def> = self.defs.iter().filter(|d| d.op.section() == section).cloned().collect();
163            if !defs.is_empty() {
164                sections.push((section, defs));
165            }
166        }
167        let groups: Vec<String> = self.draw.iter().map(Draw::group).collect();
168        if let Some(missing) = self.order.iter().find(|id| !groups.contains(&id.0)) {
169            return Err(ScriptError {
170                message: format!("compose.order names {:?}, which no draw writes", missing.0),
171                at: self.order_at,
172            });
173        }
174        let compose = Compose {
175            order: self.order,
176            masks: self.masks,
177            clip: Default::default(),
178            clip_default: self.clip.unwrap_or(Clip::Auto),
179            optimize: self.optimize,
180        };
181        let graph = Grammar { title: self.title, output, sections, draw: self.draw, compose, views: self.views };
182        grammar::validate(&graph).map_err(|e| {
183            let message = e.to_string();
184            ScriptError { at: find_at(&message), message }
185        })?;
186        Ok(graph)
187    }
188}
189
190// ---------------------------------------------------------------------------
191// Natives
192// ---------------------------------------------------------------------------
193
194/// Where the user's script is in the call stack: the innermost call in the
195/// profile, skipping the library's own. Read from an `Error`'s `stack`, which
196/// records call sites (the frames' own positions lag inside functions).
197fn user_at(ctx: &mut Context) -> Option<At> {
198    let error = ctx.intrinsics().constructors().error().constructor();
199    let error = error.construct(&[], None, ctx).ok()?;
200    let stack = error.get(js_string!("stack"), ctx).ok()?.to_string(ctx).ok()?.to_std_string_escaped();
201    let marker = format!("({SCRIPT_PATH}:");
202    stack.lines().find_map(|line| {
203        let spot = &line[line.find(&marker)? + marker.len()..];
204        let (l, c) = spot.trim_end_matches(')').split_once(':')?;
205        Some(At(l.parse().ok()?, c.parse().ok()?))
206    })
207}
208
209fn fail(ctx: &mut Context, message: impl Into<String>) -> JsError {
210    let message = message.into();
211    let at = user_at(ctx);
212    with(|b| b.failure = Some((message.clone(), at)));
213    JsNativeError::typ().with_message(message).into()
214}
215
216fn json_arg(args: &[JsValue], i: usize, ctx: &mut Context) -> JsResult<Value> {
217    let value = args.get(i).cloned().unwrap_or_default();
218    Ok(value.to_json(ctx)?.unwrap_or(Value::Null))
219}
220
221fn string_arg(args: &[JsValue], i: usize, ctx: &mut Context) -> JsResult<String> {
222    Ok(args.get(i).cloned().unwrap_or_default().to_string(ctx)?.to_std_string_escaped())
223}
224
225/// `dl.node(section, { op_key: … })` → the new def's reference.
226fn native_node(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
227    let section = string_arg(args, 0, ctx)?;
228    let op = json_arg(args, 1, ctx)?;
229    let at = user_at(ctx);
230    let section = Section::ALL.into_iter().find(|s| s.key() == section).ok_or_else(|| fail(ctx, "unknown section"))?;
231    let key = op.as_object().and_then(|o| o.keys().next().cloned()).unwrap_or_default();
232    let parsed = grammar::op_from_json(section, op).map_err(|e| fail(ctx, strip_kind(&e.to_string())))?;
233    let short = key
234        .strip_prefix("tools_")
235        .or_else(|| key.strip_prefix("engine_"))
236        .or_else(|| key.strip_suffix("_select"))
237        .unwrap_or(&key);
238    let name = match key.strip_prefix("module_") {
239        Some(module) => {
240            if with(|b| b.defs.iter().any(|d| d.name == module)) {
241                return Err(fail(ctx, format!("modules.{module} is called twice; call it once and reuse its outputs")));
242            }
243            module.to_string()
244        }
245        None => with(|b| {
246            b.count += 1;
247            format!("{short}_{}", b.count)
248        }),
249    };
250    let def = Def { name, op: parsed, at };
251    let reference = def.reference().to_string();
252    with(|b| b.defs.push(def));
253    Ok(JsValue::from(js_string!(reference)))
254}
255
256/// `dl.burin(callback)` → the atlas JSON the burin document built.
257///
258/// The callback is a real function in this engine, so a burin document written
259/// here has the same errors, positions and editor hints as anywhere else; the
260/// atlas it builds is burin's own, and the engine draws it later.
261fn native_burin(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
262    let callback = args.first().cloned().unwrap_or_default();
263    match burin_map_script::run_builder(ctx, &callback, SCRIPT_PATH) {
264        Ok(atlas) => Ok(JsValue::from(js_string!(atlas.to_string()))),
265        Err(e) => {
266            let message = e.message;
267            let at = e.at.map(|a| At(a.0, a.1));
268            with(|b| b.failure = Some((message.clone(), at)));
269            Err(JsNativeError::typ().with_message(message).into())
270        }
271    }
272}
273
274/// `$lines.x`, `$fills.x` or `roads.outlines`.
275fn target(text: &str) -> Result<Target, String> {
276    if text.starts_with('$') {
277        return Name::parse(text).map(|name| Target { module: None, name });
278    }
279    match text.split_once('.') {
280        Some((module, output)) => Ok(Target {
281            module: Some(module.to_string()),
282            name: Name { section: Section::Lines, name: output.to_string() },
283        }),
284        None => Err(format!("{text:?} is not a reference")),
285    }
286}
287
288fn native_draw(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
289    let spec = json_arg(args, 0, ctx)?;
290    let at = user_at(ctx);
291    let from = target(spec["from"].as_str().unwrap_or_default()).map_err(|e| fail(ctx, format!("draw: {e}")))?;
292    let stroke = match spec.get("stroke") {
293        None => None,
294        Some(s) => Some(
295            serde_json::from_value::<StrokeSpec>(s.clone())
296                .map_err(|e| fail(ctx, format!("draw: stroke {s}: {e}; write solid, dash, dotted, none or {{ style, dash, gap, mark, color, width, cap, join }}")))?,
297        ),
298    };
299    let id = spec.get("id").and_then(Value::as_str).map(str::to_string);
300    let draw = Draw { id, from, stroke, at };
301    let group = draw.group();
302    if with(|b| b.draw.iter().any(|d| d.group() == group)) {
303        return Err(fail(ctx, format!("draw: the id {group:?} is already drawn")));
304    }
305    with(|b| b.draw.push(draw));
306    Ok(JsValue::from(js_string!(group)))
307}
308
309fn native_order(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
310    let ids: Vec<String> = serde_json::from_value(json_arg(args, 0, ctx)?).unwrap_or_default();
311    let at = user_at(ctx);
312    with(|b| {
313        b.order = ids.into_iter().map(Id).collect();
314        b.order_at = at;
315    });
316    Ok(JsValue::undefined())
317}
318
319fn native_mask(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
320    let spec = json_arg(args, 0, ctx)?;
321    let at = user_at(ctx);
322    let from = target(spec["from"].as_str().unwrap_or_default()).map_err(|e| fail(ctx, format!("compose.mask: {e}")))?;
323    let occludes: Vec<String> = serde_json::from_value(spec["occludes"].clone()).unwrap_or_default();
324    let name = with(|b| match spec["name"].as_str() {
325        Some(n) => n.to_string(),
326        None => format!("mask_{}", b.masks.len() + 1),
327    });
328    if with(|b| b.masks.iter().any(|(n, _)| *n == name)) {
329        return Err(fail(ctx, format!("compose.mask: the name {name:?} is already used")));
330    }
331    with(|b| b.masks.push((name, Mask { from, occludes: occludes.into_iter().map(Id).collect(), at })));
332    Ok(JsValue::undefined())
333}
334
335fn native_clip(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
336    let clip = match json_arg(args, 0, ctx)? {
337        Value::String(s) if s == "auto" => Clip::Auto,
338        Value::String(s) if s == "none" => Clip::None,
339        Value::Array(items) => Clip::Areas(
340            items
341                .iter()
342                .map(|v| Name::parse(v.as_str().unwrap_or_default()))
343                .collect::<Result<_, _>>()
344                .map_err(|e| fail(ctx, format!("compose.clip: {e}")))?,
345        ),
346        other => return Err(fail(ctx, format!("compose.clip: {other} is not auto, none or a list of areas"))),
347    };
348    with(|b| b.clip = Some(clip));
349    Ok(JsValue::undefined())
350}
351
352fn native_optimize(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
353    let spec = json_arg(args, 0, ctx)?;
354    let at = user_at(ctx);
355    let raw: grammar::RawOptimizeStep = serde_json::from_value(spec)
356        .map_err(|e| fail(ctx, format!("compose: {}", strip_kind(&e.to_string()))))?;
357    let step = drawland_core::optimize::OptimizeStep {
358        layers: raw.layers.into_iter().map(Id).collect(),
359        except: raw.except.into_iter().map(Id).collect(),
360        op: raw.op,
361        at,
362    };
363    with(|b| b.optimize.push(step));
364    Ok(JsValue::undefined())
365}
366
367/// `dl.output(spec)` → the output as it will be: inside a view, the view's
368/// place and rectangle win over what the style asks, so a preset drawn in a
369/// view keeps its paper-independent look (pens, patterns) at the view's place.
370fn native_output(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
371    let mut spec = json_arg(args, 0, ctx)?;
372    if let (Some(obj), Some(keys)) = (spec.as_object_mut(), with(|b| b.view.as_ref().map(|v| v.2.clone()))) {
373        for k in ["address", "slices"] {
374            obj.remove(k);
375        }
376        obj.extend(keys);
377    }
378    let output: OutputSpec = serde_json::from_value(spec.clone()).map_err(|e| fail(ctx, format!("output: {e}")))?;
379    if with(|b| b.output.replace(output).is_some()) {
380        return Err(fail(ctx, "output is set twice"));
381    }
382    JsValue::from_json(&spec, ctx)
383}
384
385/// A view's id, corner, ink, and the output keys its spec sets.
386type ViewHead = (String, (f64, f64), serde_json::Map<String, Value>, Option<String>);
387
388/// The output keys a view's spec sets: `{ id, at: [x, y], size: [w, h] }` in
389/// page mm, and the place (`lat`, `lng`, `scale`, `bearing`, `tileZoom`,
390/// `projection`). The view's id and corner, and those keys.
391fn view_keys(spec: &Value) -> Result<ViewHead, String> {
392    let o = spec.as_object().ok_or("view takes { at, size, lat, lng, scale, … }")?;
393    let pair = |k: &str| -> Result<(f64, f64), String> {
394        match o.get(k).and_then(Value::as_array).map(|a| a.iter().map(Value::as_f64).collect::<Vec<_>>()) {
395            Some(v) if v.len() == 2 && v.iter().all(Option::is_some) => Ok((v[0].unwrap(), v[1].unwrap())),
396            _ => Err(format!("view.{k} is [x, y] in millimetres")),
397        }
398    };
399    let at = pair("at")?;
400    let (w, h) = pair("size")?;
401    if w <= 0.0 || h <= 0.0 {
402        return Err("view.size must be positive".into());
403    }
404    let id = o.get("id").and_then(Value::as_str).ok_or("view.id names the view, as compose.mask occludes it")?.to_string();
405    let mut keys = serde_json::Map::new();
406    keys.insert("width".into(), Value::String(format!("{w}mm")));
407    keys.insert("height".into(), Value::String(format!("{h}mm")));
408    keys.insert("padding".into(), Value::from(0));
409    for k in ["lat", "lng", "scale", "bearing", "tileZoom", "projection"] {
410        if let Some(v) = o.get(k) {
411            keys.insert(k.into(), v.clone());
412        }
413    }
414    let ink = match o.get("ink") {
415        None | Some(Value::Null) => None,
416        Some(Value::String(c)) if !c.trim().is_empty() => Some(c.trim().to_string()),
417        Some(v) => return Err(format!("view.ink is a colour like \"#e4572e\", got {v}")),
418    };
419    Ok((id, at, keys, ink))
420}
421
422/// `dl.viewBegin(spec)`: the graph the next calls build is the view's.
423fn native_view_begin(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
424    let spec = json_arg(args, 0, ctx)?;
425    let view = view_keys(&spec).map_err(|e| fail(ctx, e))?;
426    if BUILDER.with(|b| b.borrow().len()) > VIEW_DEPTH {
427        return Err(fail(ctx, "views nest too deep"));
428    }
429    if with(|b| b.views.iter().any(|v| v.id == view.0)) {
430        return Err(fail(ctx, format!("two views are called {:?}", view.0)));
431    }
432    BUILDER.with(|b| b.borrow_mut().push(Builder { view: Some(view), ..Builder::default() }));
433    Ok(JsValue::undefined())
434}
435
436/// `dl.viewEnd(ok)`: the view's graph is done; it joins the page's views
437/// (`ok`), or is dropped (the style threw).
438fn native_view_end(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
439    let ok = args.first().is_some_and(JsValue::to_boolean);
440    let inner = BUILDER.with(|b| if b.borrow().len() > 1 { b.borrow_mut().pop() } else { None });
441    let Some(inner) = inner else { return Err(fail(ctx, "viewEnd without viewBegin")) };
442    if !ok {
443        return Ok(JsValue::undefined());
444    }
445    attach(inner, ctx)
446}
447
448/// `dl.viewPreset(spec, id)`: a view drawn in a built-in preset, run on its
449/// own (its top-level names never meet the page's).
450fn native_view_preset(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
451    let spec = json_arg(args, 0, ctx)?;
452    let id = string_arg(args, 1, ctx)?;
453    let view = view_keys(&spec).map_err(|e| fail(ctx, e))?;
454    let Some((_, source)) = PRESETS.iter().find(|(p, _)| *p == id) else {
455        let known: Vec<&str> = PRESETS.iter().map(|(p, _)| *p).collect();
456        return Err(fail(ctx, format!("no preset {id:?}; one of {}", known.join(", "))));
457    };
458    if BUILDER.with(|b| b.borrow().len()) > VIEW_DEPTH {
459        return Err(fail(ctx, "views nest too deep"));
460    }
461    let view_id = view.0.clone();
462    BUILDER.with(|b| b.borrow_mut().push(Builder { view: Some(view), ..Builder::default() }));
463    let result = run(source);
464    let inner = BUILDER.with(|b| b.borrow_mut().pop()).expect("pushed above");
465    if let Err(e) = result {
466        return Err(fail(ctx, format!("view {view_id} ({id}): {e}")));
467    }
468    attach(inner, ctx)
469}
470
471/// A finished view's graph, added to the page's views; its id back.
472fn attach(inner: Builder, ctx: &mut Context) -> JsResult<JsValue> {
473    let (id, at, _, ink) = inner.view.clone().expect("a view builder");
474    let grammar = inner.finish().map_err(|e| fail(ctx, format!("view {id}: {}", e.message)))?;
475    with(|b| b.views.push(grammar::View { id: id.clone(), at, grammar: Box::new(grammar), ink }));
476    Ok(JsValue::from(js_string!(id)))
477}
478
479fn native_title(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
480    let text = string_arg(args, 0, ctx)?;
481    with(|b| b.title = Some(text));
482    Ok(JsValue::undefined())
483}
484
485fn native_fail(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
486    let message = string_arg(args, 0, ctx)?;
487    Err(fail(ctx, message))
488}
489
490// ---------------------------------------------------------------------------
491// Errors
492// ---------------------------------------------------------------------------
493
494/// `profile: …` and the like: the grammar's own prefixes mean nothing to a
495/// script author.
496fn strip_kind(message: &str) -> String {
497    message.strip_prefix("profile: ").unwrap_or(message).to_string()
498}
499
500/// The first `line N column M` in a message.
501fn find_at(message: &str) -> Option<At> {
502    let start = message.find("line ")?;
503    let rest = &message[start + 5..];
504    let (line, rest) = rest.split_once(" column ")?;
505    let column: String = rest.chars().take_while(char::is_ascii_digit).collect();
506    Some(At(line.parse().ok()?, column.parse().ok()?))
507}
508
509fn script_error(err: JsError, source: &str, ctx: &mut Context) -> ScriptError {
510    let native = err.try_native(ctx).ok();
511    let message = native.as_ref().map(|n| n.message().to_string());
512    if let (Some(message), Some((failed, at))) = (&message, with(|b| b.failure.take())) {
513        if *message == failed {
514            return ScriptError { message: failed, at };
515        }
516    }
517    let text = err.to_string();
518    let first = text.lines().next().unwrap_or_default();
519    let kind = native.as_ref().map(|n| format!("{}", n.kind())).unwrap_or_default();
520    let message = match (&message, kind.is_empty()) {
521        (Some(m), false) => format!("{kind}: {m}"),
522        _ => first.split(" (").next().unwrap_or(first).to_string(),
523    };
524    // `x is not defined` comes without a reliable position: the first use of
525    // the name.
526    if let Some(name) = message.strip_prefix("ReferenceError: ").and_then(|m| m.strip_suffix(" is not defined")) {
527        if let Some(at) = first_use(source, name) {
528            return ScriptError { at: Some(at), message };
529        }
530    }
531    // Runtime errors: `TypeError: … (profile.js:2:7)`.
532    let marker = format!("({SCRIPT_PATH}:");
533    if let Some(i) = first.rfind(&marker) {
534        let spot = &first[i + marker.len()..first.len().saturating_sub(1)];
535        if let Some((line, column)) = spot.split_once(':') {
536            if let (Ok(line), Ok(column)) = (line.parse(), column.parse()) {
537                return ScriptError { message, at: Some(At(line, column)) };
538            }
539        }
540    }
541    // Syntax errors: `… at line 1, col 9`.
542    if let Some(i) = first.rfind(" at line ") {
543        let spot = &first[i + 9..];
544        if let Some((line, column)) = spot.split_once(", col ") {
545            let column: String = column.chars().take_while(char::is_ascii_digit).collect();
546            if let (Ok(line), Ok(column)) = (line.trim().parse(), column.parse()) {
547                let message = format!("SyntaxError: {}", first[..i].trim_start_matches("SyntaxError: "));
548                return ScriptError { message, at: Some(At(line, column)) };
549            }
550        }
551    }
552    ScriptError { message, at: None }
553}
554
555/// Where `name` first appears as a whole word.
556fn first_use(source: &str, name: &str) -> Option<At> {
557    let word = |c: char| c.is_alphanumeric() || c == '_' || c == '$';
558    for (i, line) in source.lines().enumerate() {
559        let mut from = 0;
560        while let Some(j) = line[from..].find(name) {
561            let start = from + j;
562            let end = start + name.len();
563            let before = line[..start].chars().next_back();
564            let after = line[end..].chars().next();
565            if !before.is_some_and(|c| word(c) || c == '.') && !after.is_some_and(word) {
566                return Some(At(i as u32 + 1, line[..start].chars().count() as u32 + 1));
567            }
568            from = end;
569        }
570    }
571    None
572}
573
574/// Every function the library defines, as `areas.union` or `draw`, sorted:
575/// what `drawland.d.ts` must declare.
576pub fn library_names() -> Result<Vec<String>, ScriptError> {
577    BUILDER.with(|b| b.borrow_mut().push(Builder::default()));
578    let mut ctx = Context::default();
579    install(&mut ctx).map_err(|e| ScriptError { message: format!("library: {e}"), at: None })?;
580    let listing = ctx
581        .eval(Source::from_bytes(
582            "JSON.stringify(['features','areas','engine','lines','fills','burin','ink','modules','draw','compose','output','title','view'].flatMap((n) =>              typeof globalThis[n] === 'function' ? [n] : [n, ...Object.keys(globalThis[n]).map((k) => n + '.' + k)]))",
583        ))
584        .and_then(|v| v.to_string(&mut ctx))
585        .map_err(|e| ScriptError { message: e.to_string(), at: None })?
586        .to_std_string_escaped();
587    BUILDER.with(|b| b.borrow_mut().pop());
588    let mut names: Vec<String> = serde_json::from_str(&listing).unwrap_or_default();
589    names.sort();
590    Ok(names)
591}
592
593#[cfg(test)]
594mod catalog_dts;
595#[cfg(test)]
596mod tests;