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