This page follows a problem from the moment the engine notices it to the dialog the game’s developer reads, or to the silence when nothing notices it. It covers FancyError, the debug module that the starter game loads before the engine, and monogatari.debug, the console logger. Read Architecture first; Debugging the Engine is the companion page on finding bugs in the engine itself.

What it’s for

Monogatari’s errors are written for the person making the game, not for the player. When a script names a label that doesn’t exist, the engine shows a dialog with what went wrong, where (the label and the step), what the script may have meant, and how to fix it. A player of a published game should never see one.

Three pieces share the work:

  • FancyError (src/lib/FancyError.ts) is part of the engine. It keeps a catalog of error templates by id, fills one in with the details a caller passes, and shows it as a dialog. Every subsystem reports through FancyError.show(id, context).
  • The debug module (debug/index.js, built to dist/engine/debug/debug.js) is a separate script. Loading it is what turns the dialogs on: it sets the global MonogatariDebug, fills the catalog with 43 templates, brings the Prism syntax highlighter for the code samples in the dialogs, and shows a dialog for the errors the browser reports: a mistake in one of the game’s files while the page loads, or an error thrown later. The starter game loads it first; removing that line turns every dialog off.
  • monogatari.debug is Artemis’s Debug class behind a proxy: the console methods (log, debug, warn, error, groupCollapsed, trace…), each printing only at or above a level, and the narrating ones only while the debug module is loaded. The engine uses it to narrate the life cycle of every statement.

The files

File What it does Cypress specs
src/lib/FancyError.ts The FancyError class: register(), show(), the queue and pop(), render() of the details, the dialog’s markup, pageHadErrors() error_dialogs.spec.js, actions/functions.spec.js, actions/conditionals.spec.js, actions/reversible_functions.spec.js, actions/hide_character.spec.js, actions/show_canvas.spec.js, actions/show_video.spec.js, actions/hide_textbox.spec.js (all check that .fancy-error appears; hide_textbox.spec.js also checks that nothing shows at level 0)
debug/index.js The debug module’s source: sets window.MonogatariDebug (with registerErrors and pageErrors), registerErrors() with every template, the error listener the same specs, since cy.open() loads dist/index.html with the module
debug/vendor/prism.js PrismJS 1.15.0, imported by debug/index.js; highlights the code samples inside the dialogs none
build.ts buildDebug() bundles debug/index.js into dist/engine/debug/debug.js (IIFE, minified, linked source map) none
dist/engine/debug/debug.js The committed debug bundle the starter game loads all specs
dist/index.html Loads engine/debug/debug.js before engine/core/monogatari.js all specs
dist/js/main.js Calls monogatari.debug.level(5) before monogatari.init() all specs
src/monogatari.ts The debug getter (the DEBUG proxy over Artemis Debug, which silences the narrating methods without the module), the starting level of 1 when the module is loaded, _setupRegistry() (Pandora’s Registry.onError → engine:component:lifecycle_error), and the engine’s own FancyError.show() calls error_dialogs.spec.js, actions/functions.spec.js
src/engine/ui.ts displayInitialScreen() shows engine:script:label_not_found, and skips it when the script is empty after a page error (FancyError.pageHadErrors()) none
src/engine/lifecycle.ts Where a statement’s failures go: run() reports a throwing function statement as engine:run:function_error, and lets an action’s failure propagate without a dialog actions/functions.spec.js
src/lib/types/index.ts FancyErrorProps, ErrorTemplate, ErrorContext, QueuedError none
src/style/monogatari.css .fancy-error list and summary styles; the dialog itself uses the .modal styles none
cypress/support/commands.js cy.open() sets the level to 5 again after the page loads all specs

How it works

Loading: two scripts, one catalog

dist/index.html loads its scripts in the <head>, in this order: engine/debug/debug.js, engine/core/monogatari.js, js/options.js, js/storage.js, js/script.js, js/main.js. The order matters.

sequenceDiagram participant Page as dist/index.html participant Debug as debug.js participant Engine as monogatari.js participant Main as js/main.js Page->>Debug: load (document still loading) Debug->>Debug: Prism, window.MonogatariDebug Debug->>Page: listen for DOMContentLoaded and for error Page->>Engine: load: window.Monogatari, FancyError with an empty catalog Engine->>Engine: level 1, since MonogatariDebug exists Page->>Main: load: monogatari.debug.level(5), $_ready(init) Page-->>Debug: DOMContentLoaded (first listener) Debug->>Engine: registerErrors(window.Monogatari.FancyError): 43 templates Page-->>Main: DOMContentLoaded (second listener) Main->>Engine: monogatari.init('#monogatari') Engine->>Engine: _setupRegistry(): Registry.debug, Registry.onError
  1. The debug bundle runs first. Prism defines window.Prism. Then window.MonogatariDebug = { enabled: true, version: '1.0.0', registerErrors, pageErrors }: this object is the switch every check in the engine looks for.
  2. The engine bundle runs next. When it finds MonogatariDebug and the level is still 0, it sets the level to 1 (ERROR), so the dialogs are on even if the game never sets a level, or its js/main.js fails before it does.
  3. Since the document is still loading, waitForMonogatari() waits for DOMContentLoaded. By then the engine has loaded, so it calls registerErrors(window.Monogatari.FancyError) at once (it would poll with requestAnimationFrame otherwise). The templates go into the engine’s own FancyError, the one src/index.ts exports, so the engine and the module share one catalog. An error shown before that, by code that runs while the page loads, doesn’t wait: show() calls MonogatariDebug.registerErrors() itself when it gets an id it doesn’t know.
  4. js/main.js sets the level to 5 when it loads and starts init() from $_ready(), a DOMContentLoaded listener added after the debug module’s. Listeners run in the order they were added, so the catalog is full before init() starts.
  5. init() calls _setupRegistry(). With MonogatariDebug present, Registry.debug = true makes Pandora log every registration ([Pandora] Registered: <alert-modal>…). Registry.onError() turns any error Pandora catches in a component into engine:component:lifecycle_error, and logs it with console.error.

The debug module never runs a check on the script itself: it has no script check. Every error comes from the engine at the moment a statement runs, or from the browser.

Showing an error: FancyError.show()

flowchart TD call["FancyError.show(id, context)"] --> gate{"MonogatariDebug is an object<br/>and Debug.currentLevel > 0?"} gate -- no --> nothing(["Nothing happens"]) gate -- yes --> lookup{"id in the catalog?"} lookup -- no --> catalog["MonogatariDebug.registerErrors(),<br/>then look again"] lookup -- yes --> known catalog --> known{"id in the catalog<br/>and context not a string?"} known -- yes --> fill["Fill {{key}} in title, message, props<br/>add context keys that start in capitals<br/>or contain a space to the props"] known -- no --> legacy["Legacy call: the id is the title,<br/>the second argument the message,<br/>the third the props"] fill --> body{"Does the page<br/>have a body yet?"} legacy --> body body -- no --> later["queue.unshift(error),<br/>pop() once the page is ready"] body -- yes --> open{"A [data-error] dialog<br/>already visible?"} open -- yes --> queue["queue.unshift(error)"] open -- no --> modal["Prepend the dialog to body,<br/>attach the Ok handler, Prism.highlightAll()"] modal --> ok["Ok: remove the dialog, pop()"] ok --> next["queue.pop(): show the oldest waiting error"]

In order:

  1. The gate. show() does nothing unless MonogatariDebug is an object and Debug.currentLevel is above 0. Both are needed: the module alone shows nothing at level 0, which is what hide_textbox.spec.js checks. Artemis starts at level 0, and the engine raises it to 1 when it loads after the module (step 2 of the loading above), so a game whose main.js doesn’t call monogatari.debug.level() still sees the dialogs.
  2. The template. register(id, { title, message, props }) stores a template in FancyError.registry, a Map. show() looks the id up, and asks the debug module to fill the catalog when it isn’t there yet. When it’s there and the second argument is an object, interpolate() replaces every {{key}} in the title and message with context[key], and interpolateProps() does the same through the props, nested objects and arrays included. A placeholder whose key the context lacks stays as written, so a template that names the wrong key shows it. In the props, contextHtml() turns each value into the dialog’s HTML. Text is escaped, so a statement with a player’s name in it can’t add markup to the dialog; the one exception is a code block the caller built, <code class='language-…'>…</code> (inside <pre> or not), which keeps its element for Prism, with its text escaped. Text a caller already escaped shows once: safeText() unescapes before escaping. Anything else goes through formatValue(): numbers as they are, undefined and null as (none), a function or a class by its name, an element as its escaped markup, a list as its items joined with , (an empty one as (none)), any other object as escaped JSON. The title and the message get formatValue() alone, since the dialog escapes them whole. Before 2.9.0, text went into the props as it was, and each caller had to escape what came from the player. A prop that is only a placeholder, like '{{elements}}', keeps a value that holds elements as it is, so render() can lay out their markup.
  3. Extra details. Any context key that starts with a capital letter or contains a space is added to the props, text escaped as above: run() passes 'Error Message', 'File Name' and 'Line Number' this way when a function statement throws.
  4. The legacy call. An id that isn’t in the catalog takes the old three-argument path: show(title, message, props). A catalog-style call with an unknown id therefore shows the id as the title and [object Object] as the message. The debug module’s own error listener uses this path on purpose.
  5. One at a time. If a dialog with data-error is visible, the new error goes to the front of FancyError.queue. Otherwise the dialog is prepended to <body> and its Ok button gets a handler that removes it and calls pop(), which takes the oldest queued error from the end of the queue. Before the page has a <body> (code in the <head>’s scripts), errors wait in the queue, and the first is shown once the page is ready.
  6. pop() checks nothing else. An error only gets into the queue after passing show()’s gate, so pop() shows it on any host. Until 2.9.0, pop() also required a page opened from a file, localhost or 127.0.0.1, and on any other host every error after the first stayed in the queue (Exercise 2).

The dialog

generateModalHtml() builds the markup: a div.fancy-error.modal.modal--active with a data-error attribute holding a random id (Util.uuid()), the title in an <h2>, the message in a <p>, a “Details” section from render(props), a “Need More Help?” section with the links in HELP_LINKS (the v2 Help page, Discord and GitHub’s issues), and an Ok button. The title and message are escaped (escapeHtml()); the props aren’t escaped whole, because templates put markup in them on purpose (<pre><code class='language-javascript'>…</code></pre> samples, links), but the values from the context in them are (step 2).

render(props) lays the props out in two passes:

Value First pass (“Details”) Second pass
an element, a NodeList, an HTMLCollection or an array holding elements the key, then each element’s escaped outerHTML in <pre><code class='language-markup'>
any other array an open <details> with a list, each item through formatValue()
a plain object a rule, an <h3> with the key capitalized (Help), then each property: a key starting with _ prints its value as a paragraph, any other key as in the first pass
anything else <p><b>Key</b>: value</p>, the value through formatValue()

The dialog for a jump to a label that doesn't exist: the title and message from the template, the details filled in from the context, and the Help section from a nested object
action:jump:label_not_found, shown by the Jump action's willApply()

While the dialog is open, the game can’t move forward: shouldProceed() in src/engine/lifecycle.ts refuses while any .modal is visible (“Extra condition check failed.”), and the dialog has the modal class. The player has to press Ok first.

What reaches the developer

Not every failure turns into a dialog. These are the cases checked in the starter game, served, with the module loaded and the level at 5:

What went wrong What the developer sees After it
A syntax error in js/script.js (a missing comma) “There is a mistake in js/script.js”, with the file, the line, the browser’s message and what it means for the game (opened from the file, the browser hides the line and the message: the file still shows) None of js/script.js ran; engine:script:label_not_found is skipped, since the empty script is the same mistake
A syntax error in js/main.js “There is a mistake in js/main.js”, although the line that sets the level never ran: the level starts at 1 with the module The game doesn’t start
A function statement throws engine:run:function_error, with the error’s message The next click goes on after it
jump to a label that doesn’t exist action:jump:label_not_found The next click goes on after it
A label without end or jump runs out engine:script:label_ended The game stays on the label’s last statement
{{name}} that isn’t in the storage engine:storage:variable_not_found The line shows {{name}} as written
A component throws in willMount(), render() or didMount() engine:component:lifecycle_error, lifecycle connectedCallback The element stays without its content
An object statement no action takes ({ 'Choise': { … } }) engine:run:no_action The next click goes on after it
An action’s constructor, willApply(), apply() or didApply() throws engine:run:statement_failed, unless the action showed a dialog of its own The next click goes on after it
A music file that can’t be fetched Nothing on screen (Media and Assets, Exercise 4) The music doesn’t play
An error thrown after the page loaded (a timer, a click handler) “An Unknown Error Occurred”, with the message, the file and the line Depends on the code
A rejected promise nobody catches Nothing; the console only Depends on the code
A second error while a dialog is open Queued; shown after Ok

After a failed statement the game stays playable. proceed() sets the global _engine_block before it calls next(), and next() clears it whether the statement’s run resolved or rejected, so the next click runs the statement after the failed one. run() also clears the deprecated block global when a function statement throws, and remembers the failed position, so going back steps over it. Statements and Actions covers that flow.

run() reports the two kinds of failing code differently. A function statement runs inside a try that shows engine:run:function_error and resolves the run with { advance: false }. An action’s constructor, willApply(), apply() and didApply() run inside blocks that log, report and rethrow, and next() swallows the rejection. Throwing from willApply() is how an action cancels its statement, usually after showing its own error (Jump does), so the report is engine:run:statement_failed only when no dialog opened while the statement ran: run() counts the open [data-error] dialogs and FancyError.queue when it starts, and compares when it fails.

The debug module’s error listener

debug/index.js adds a window error listener, and sorts what it hears by when it happens:

  • While the page loads (document.readyState is 'loading'), with a file: a mistake in one of the game’s files. The file comes from document.currentScript, which is the failing <script> while the browser reports its error, syntax errors included. That holds even when the browser hides the error’s details from the page, as Chrome and Firefox do for a page opened from a file (the message is Script error. and the line 0). The error goes into MonogatariDebug.pageErrors, and on DOMContentLoaded, once js/main.js has set its level, the module shows debug:page:file_error: “There is a mistake in js/script.js”, with the line (or Not given), the browser’s message and what a mistake in that file means for the game (FILE_CONSEQUENCES).
  • After that: “An Unknown Error Occurred”, shown at once with the legacy three-argument call: the message, the file and the line.

ResizeObserver loop messages, which Chrome reports when a page resizes things too often in one frame, are skipped.

pageErrors is also how the engine avoids a second, misleading dialog: when the script has no labels at all and a page error happened, displayInitialScreen() skips engine:script:label_not_found (FancyError.pageHadErrors()).

The listener only hears error events. A rejected promise fires unhandledrejection instead, and most of the engine is async, so a throw inside an async method never reaches it.

The dialog for a missing comma in js/script.js, shown by the debug module's error listener while the page loads
There is a mistake in js/script.js: the file, the line, the browser's message and what happens now

Console logging: monogatari.debug

monogatari.debug returns DEBUG, a Proxy over Artemis’s Debug class created once in src/monogatari.ts. Its get trap hands out every property as it is, except the narrating methods in DEBUG_TRACE_METHODS (log, debug, info, table, the groups, the timers, trace, count, dir…): without the debug module, those come back as functions that do nothing. error(), warn(), warning() and assert() still print at their levels, and level(), setLevel() and isEnabled() work as before. So a released game, which drops the module, prints its errors and warnings and nothing else, whatever level its js/main.js sets.

Until 2.9.0 the proxy had an apply trap instead, which only catches calls to the proxy itself (monogatari.debug()); method calls went straight to Debug, so the check gated nothing and a released game at level 5 printed its whole trace.

Each method prints at or above a level of Artemis’s DebugLevel:

Level Name What prints
0 NONE nothing, and no dialogs
1 ERROR error(), assert()
2 WARNING and warn(), warning()
3 INFO and info()
4 DEBUG and log(), debug(), table(), group(), groupCollapsed(), groupEnd(), trace(), time()…
5 ALL the same as 4: no method needs 5

INFO and up need the debug module, as above.

The engine’s calls are mostly debug(), groupCollapsed() and groupEnd(): every statement opens a “Run Cycle [Dialog]” group with “Action Will Apply”, “Action Applying”, “Action Did Apply” inside, every rollback a “Revert Cycle” group, and each proceed() a “shouldProceed Check” group listing OK Dialog or FAIL Choice per action and component. Chrome files console.debug() under the Verbose level, which its console hides by default.

Besides monogatari.debug, the engine writes with console.warn() and console.error() directly in about 70 places, so these print at any level: the persistent-storage permission, the first run without saved settings, the service worker on a file page, IndexedDB being unavailable, Preload and Unload problems, the audio player’s worklets, and the component errors from Registry.onError.

Without the debug module

Removing <script src="./engine/debug/debug.js"></script> from index.html:

  • no dialog ever shows, since MonogatariDebug is undefined;
  • the catalog stays empty and Pandora’s Registry.debug stays off;
  • the level stays where js/main.js sets it (Artemis starts at 0), and only error() and warn() print at it: the step-by-step trace is off (with the starter’s level 5 and four lines played, the console gets 4 warnings, against about 400 debug messages and 10 groups with the module);
  • the window error listener is gone, so a syntax error in js/script.js leaves the page without a dialog.

That is how a game ships without dialogs. To silence its errors and warnings as well, lower the level in js/main.js (monogatari.debug.level(0)).

The data

From src/lib/types/index.ts:

/**
 * Error properties for FancyError display
 */
export interface FancyErrorProps {
  [key: string]: unknown;
}

/**
 * Error template for registered errors
 */
export interface ErrorTemplate {
  title: string;
  message: string;
  props: FancyErrorProps;
}

/**
 * Context object for error template interpolation
 */
export interface ErrorContext {
  [key: string]: unknown;
}

/**
 * Queued error object
 */
export interface QueuedError {
  id: string;
  title: string;
  message: string;
  props: FancyErrorProps;
}

QueuedError.id is the dialog’s random data-error value, not the catalog id. The catalog id is never shown in the dialog.

The global the debug module sets, from debug/index.js:

window.MonogatariDebug = {
  enabled: true,
  version: '1.0.0',
};

The engine checks its type (typeof MonogatariDebug === 'object'), and since 2.9.0 also uses registerErrors (FancyError.show() fills the catalog with it when an error comes before DOMContentLoaded) and pageErrors (the errors in the game’s files while the page loaded, read by FancyError.pageHadErrors()). Nothing reads enabled or version.

The catalog

Ids follow type:identifier:error_id, the convention in the comment on FancyError.register(). debug/index.js registers 68; the engine shows 67 of them and the debug module one, debug:page:file_error. Every registered message is shown somewhere: for a new message, grep -rn "'<id>'" src should find the call that shows it.

Id Shown by
action:canvas:invalid_mode, action:canvas:object_not_found src/actions/Canvas.ts
action:conditional:branch_not_found, action:conditional:negative_value, action:conditional:non_integer_value src/actions/Conditional.ts
action:dialog:textbox_hidden src/actions/Dialog.ts
action:function:apply_error, action:function:revert_error src/actions/Function.ts
action:hide_canvas:not_shown src/actions/HideCanvas.ts
action:hide_character:character_not_found, action:hide_character:not_shown src/actions/HideCharacter.ts
action:hide_character_layer:character_not_found, action:hide_character_layer:layer_not_shown src/actions/HideCharacterLayer.ts
action:hide_image:not_shown src/actions/HideImage.ts
action:jump:label_not_found src/actions/Jump.ts
action:message:not_found src/actions/Message.ts
action:notification:invalid_time, action:notification:not_found src/actions/Notify.ts
action:show_character:character_not_found, action:show_character:sprite_not_found src/actions/ShowCharacter.ts
action:show_character_layer:character_not_found, action:show_character_layer:sprite_not_found, action:show_character_layer:layer_not_listed src/actions/ShowCharacterLayer.ts
action:vibrate:invalid_time src/actions/Vibrate.ts
action:video:invalid_mode src/actions/Video.ts
action:wait:invalid_time nothing (see Exercise 1)
component:language_selection_screen:metadata_not_found src/components/language-selection-screen/index.ts
engine:component:already_registered, engine:component:unregister_after_setup, engine:component:lifecycle_error src/monogatari.ts
engine:element:not_ready, engine:script:language_not_found src/monogatari.ts
engine:lifecycle:should_proceed_error, engine:lifecycle:will_proceed_error, engine:lifecycle:should_rollback_error, engine:lifecycle:will_rollback_error src/engine/lifecycle.ts
engine:run:function_error src/engine/lifecycle.ts
engine:music:not_defined, engine:script:label_not_found, engine:screen:not_found src/engine/ui.ts
engine:storage:variable_not_found, engine:storage:variable_loop, engine:translation:key_not_found, engine:translation:language_not_found src/engine/i18n.ts
engine:storage:filesystem_no_bridge src/engine/persistence.ts
debug:page:file_error debug/index.js, its error listener
engine:storage:filesystem_no_answer src/lib/FileSystemStorage.ts

Diagnosing Errors explains each one for game developers.

Rules and why

  • Report the developer’s mistakes with FancyError.show(), not throw. A throw inside an action ends up swallowed by next(); a dialog tells the developer what to fix. Throw after showing only when the statement must not go on (Jump does both).
  • Every id the engine shows has a template in debug/index.js. Without one, the dialog shows the raw id and [object Object]. Add the template in the same change as the show() call, and rebuild both bundles.
  • Pass the label and the step. Every template has 'Label': '{{label}}' and 'Step': '{{step}}'; they are how the developer finds the statement. Pass the statement too, wrapped in <code class='language-javascript'>.
  • Report from willApply() or apply(), never from a constructor. revert() builds the previous statement’s action with prepareAction() to undo it, so a constructor runs again when the player goes back. Before 2.9.0, HideCharacter, HideCharacterLayer, Notify and Vibrate reported from their constructors, so their dialogs read Statement "undefined" (the constructor runs before _setStatement()), and a rollback over vibrate 5s showed its dialog a second time.
  • Pass text as it is. The dialog shows every value of the context as text, so a player’s typing can’t add markup, and text escaped twice would show its &lt;. A code block, <code class='language-javascript'>"${this._statement}"</code>, is the one markup a value can carry.
  • Keep the dialog for developers. The dialogs need the debug module; a release removes its script tag. Don’t make game behavior depend on whether a dialog showed.
  • The debug module is built, not edited in dist/. Change debug/index.js and run bun build.ts --debug; the bundle in dist/engine/debug/ is committed (Building and Packaging).

How to make the common changes

Add an error to the catalog

  1. Add the template to registerErrors() in debug/index.js, next to its subsystem’s:

    FancyError.register('action:shake:invalid_intensity', {
      title: 'The shake intensity "{{intensity}}" is not a number',
      message: 'Monogatari attempted to shake the screen but couldn\'t read the intensity given.',
      props: {
        'Intensity': '{{intensity}}',
        'Statement': '{{statement}}',
        'Label': '{{label}}',
        'Step': '{{step}}',
        'Help': {
          '_': 'Give the intensity as a whole number, for example:',
          '_1': '<pre><code class=\'language-javascript\'>"shake 3"</code></pre>',
        },
      },
    });
  2. Show it where the problem is noticed, with every placeholder in the context:

    import { FancyError } from './../lib/FancyError';
    
    override async willApply(): Promise<void> {
      if (Number.isNaN(this.intensity)) {
        FancyError.show ('action:shake:invalid_intensity', {
          intensity: this.writtenIntensity,
          statement: `<code class='language-javascript'>"${this._statement}"</code>`,
          label: this.engine.state ('label'),
          step: this.engine.state ('step')
        });
      }
    }
  3. Rebuild both bundles: bun build.ts --browser and bun build.ts --debug (or bun run build for everything, with lint and the type check).

  4. Add a Cypress test that checks .fancy-error appears, as actions/conditionals.spec.js does.

  5. Add the error to Diagnosing Errors.

Show extra details from the caller

Keys of the context that start with a capital letter or contain a space go into the details without a placeholder:

FancyError.show('engine:run:function_error', {
  label: engine.state('label'),
  step: engine.state('step'),
  'Error Message': error.message,
});

Log something only maintainers need

Use this.engine.debug, at the level that fits: debug() for the narration of what happens, warn() for a recoverable problem the developer should know about. Group a multi-step operation with groupCollapsed() and close it with groupEnd() on every path, error paths included, or every later message nests inside it.

Pitfalls and history

  • The queue used to empty only on a developer’s machine. pop() checked for a local page since the JavaScript version of FancyError; in 52fcadfe it became isDevEnvironment() (file:, localhost or 127.0.0.1). show() never had that check, so on a real host the first error showed and the rest waited in FancyError.queue forever. 2.9.0 removed the check. Exercise 2.
  • The level became a gate in 88425293. Until then, the module alone turned the dialogs on, and from then until 2.9.0 a game whose main.js didn’t set a level showed nothing, a typo in main.js included. 2.9.0 starts the level at 1 when the module is loaded.
  • Late errors used to be silent. The error listener was added in 4fc1a5ce (2019), when the point was script typos while the page loads. Until 2.9.0 it waited for DOMContentLoaded even when the event had passed. Exercise 4.
  • Unknown statements and failing actions were silent, and blocked the game, until 2.9.0. run() threw “The action did not match any of the ones registered.” without a dialog, logged “Apply Failed” with debug() only, and next() left _engine_block on after any rejection. 2.9.0 added engine:run:no_action and engine:run:statement_failed, and next() releases the lock (src/engine/lifecycle.ts). Exercise 3 builds the first one on the v2.8.1 tag.
  • A missing variable emptied the line before 2.9.0. replaceVariables() returned '' for the whole statement after showing engine:storage:variable_not_found. 2.9.0 leaves the variable in the text, so the rest of the line shows.
  • Prism needs the exact class. 16 statements in src/ were wrapped in <code class='language=javascript'>, with = instead of -, until 2.9.0, so Prism left them plain. Copy language-javascript from an existing call.
  • The help links are in the engine. The “Need More Help?” section is HELP_LINKS in src/lib/FancyError.ts, not in the debug module, so changing a link means an engine release. 2.8.1 still linked two services that are gone.
  • Errors from the mount and unmount only. Pandora 0.5 calls Registry.onError() from a component’s connectedCallback() (willMount, render, didMount) and disconnectedCallback(). A later render that throws, after a setState(), isn’t caught there: it reaches the browser as an uncaught error, and no dialog shows.
  • The title and message used to be raw HTML. 52fcadfe added escapeHtml() for them; the props stay raw by design.
  • “Lit is in dev mode” in the console. Engines before 2.9.0 bundled Pandora 0.5.0, built with Lit’s development build, so their games print that warning. It isn’t the engine’s error and the debug module has nothing to do with it; 2.9.0 bundles Pandora 0.5.1, which doesn’t print it.

Exercises

Do these in a scratch copy of the repository, not your working branch. The checks follow How Each Part Works: a Cypress spec in cypress/e2e/exercises/, or a Playwright script when Cypress can’t reproduce the situation. Each change to src/ needs bun build.ts --browser before the check, and each change to debug/ needs bun build.ts --debug.

Exercise 1: make Wait report a time it can’t read

What to do. Do this one on the v2.8.1 tag, where the bug is: make the scratch copy with git worktree add --detach ../monogatari-exercises v2.8.1. There, wait 5s waits for a click, because the Wait constructor turns a time that isn’t a number into null. The catalog already has action:wait:invalid_time, and nothing shows it. Make wait 5s show it, while wait and wait 500 keep working without a dialog.

Hint. Keep the time as written in a field and report from willApply(), not from the constructor: read the rule about rollback above. Vibrate shows the same kind of error.

Check. The spec below fails before your change (no .fancy-error) and passes after it. cypress/e2e/actions/wait.spec.js still passes.

Solution

src/actions/Wait.ts:

 import Action from './../lib/Action';
+import { FancyError } from './../lib/FancyError';
 import { ActionApplyResult, ActionRevertResult } from '../lib/types';

@@
   // When null, we wait for the click instead of a specific amount of time
   time: number | null = null;

+  // The time as written, kept to report it when it isn't a number
+  writtenTime: string | undefined;
+
   constructor([action, time]: string[]) {
     super();

+    this.writtenTime = time;
     this.time = !isNaN(Number(time)) ? parseInt(time) : null;
   }

+  override async willApply(): Promise<void> {
+    if (typeof this.writtenTime === 'string' && this.time === null) {
+      FancyError.show('action:wait:invalid_time', {
+        time: this.writtenTime,
+        statement: `<code class='language=javascript'>"${this._statement}"</code>`,
+        label: this.engine.state('label'),
+        step: this.engine.state('step')
+      });
+    }
+  }
+
   override async apply(): Promise<void> {

cypress/e2e/exercises/wait-invalid-time.spec.js:

context('Wait reports a time it cannot read', () => {
  beforeEach(() => {
    cy.open();
  });

  it('Shows action:wait:invalid_time for "wait 5s"', function() {
    this.monogatari.setting('TypeAnimation', false);
    this.monogatari.script({
      'Start': [
        'Before',
        'wait 5s',
        'After',
      ],
    });

    cy.start();
    cy.get('text-box').contains('Before');
    cy.proceed();
    cy.get('.fancy-error h2').should('contain', 'The specified time was not an integer');
    cy.get('.fancy-error').should('contain', '5s');
  });

  it('Shows nothing for "wait" and "wait 500"', function() {
    this.monogatari.setting('TypeAnimation', false);
    this.monogatari.script({
      'Start': [
        'Before',
        'wait 500',
        'Middle',
        'wait',
        'After',
      ],
    });

    cy.start();
    cy.proceed();
    cy.wait(600);
    cy.get('text-box').contains('Middle');
    cy.proceed();
    cy.get('.fancy-error').should('not.exist');
    cy.proceed();
    cy.get('text-box').contains('After');
  });
});
bun build.ts --browser
bunx cypress run --browser chromium --spec 'cypress/e2e/exercises/wait-invalid-time.spec.js,cypress/e2e/actions/wait.spec.js'

The statement in the context keeps the language=javascript spelling the other actions used in 2.8.1; fixing all 16 is a change of its own.

2.9.0 fixed it the same way, in src/actions/Wait.ts: it keeps the word that isn’t a number in invalidTime and reports it from willApply(), and it reads the time as the first word after wait that isn’t empty, so 'wait 500' with two spaces waits 500 milliseconds. Compare your change with that file, and its tests in cypress/e2e/actions/wait.spec.js.

Exercise 2: show queued errors on a real host

What to do. This bug is fixed in 2.9.0, so do this exercise on the v2.8.1 tag, in a scratch worktree: git worktree add ../monogatari-v2.8.1 v2.8.1. Show two errors at once on a page whose host isn’t localhost or 127.0.0.1, press Ok on the first, and see that the second never appears. Change FancyError so it does, without changing when errors show at all.

Hint. Compare the condition in show() with the one in pop(). An error only gets into the queue after passing show()’s check.

Check. Cypress always serves the game from localhost, so this check is a Playwright script that maps a made-up host name to your machine. Serve dist/ (cd dist && python3 -m http.server 8080 --bind 127.0.0.1), then run node check-error-queue.mjs 8080: it prints FAIL before the change and PASS after it.

Solution

src/lib/FancyError.ts:

 	static pop (): void {
-		if (FancyError.isDevEnvironment() && typeof Prism !== 'undefined') {
-			if (FancyError.queue.length > 0) {
-				const error = FancyError.queue.pop()!;
-				$_('body').prepend(FancyError.generateModalHtml(error));
-				FancyError.attachDismissHandler(error.id);
-			}
+		// show () already decided these errors should be seen: it only queues
+		// them when the debug module is loaded and the level is above 0.
+		if (FancyError.queue.length > 0) {
+			const error = FancyError.queue.pop()!;
+			$_('body').prepend(FancyError.generateModalHtml(error));
+			FancyError.attachDismissHandler(error.id);
 		}
 	}

isDevEnvironment() has no other caller after this; remove it too, or keep it for a later use. bunx tsc --noEmit and bunx eslint src/lib/FancyError.ts pass either way. 2.9.0 made the same change, and removed isDevEnvironment(): compare with pop() in src/lib/FancyError.ts on develop.

check-error-queue.mjs, anywhere outside the repository (it needs playwright-core and a Chromium; adjust both paths to your machine):

// Usage: node check-error-queue.mjs <port>
// Opens the game under a host name that isn't localhost or 127.0.0.1, the way
// players reach a published game, and checks that a queued error is shown once
// the first one is dismissed.
import { chromium } from 'playwright-core';

const PORT = process.argv[2] || '8080';

const browser = await chromium.launch({
  executablePath: '/usr/bin/chromium',
  args: ['--host-resolver-rules=MAP game.test 127.0.0.1'],
});

const page = await browser.newPage();

await page.goto(`http://game.test:${PORT}/`);
await page.waitForFunction(() => window.Monogatari && window.Monogatari.default.global('_didInit') === true);

await page.evaluate(() => {
  const { FancyError } = window.Monogatari;

  FancyError.show('engine:script:label_not_found', { startLabel: 'First', availableLabels: [] });
  FancyError.show('engine:script:label_not_found', { startLabel: 'Second', availableLabels: [] });
});

await page.click('.fancy-error button');

const titles = await page.evaluate(() => [...document.querySelectorAll('.fancy-error h2')].map((title) => title.textContent));
await browser.close();

if (titles.length === 1 && titles[0].includes('Second')) {
  console.log('PASS: the second error is shown after the first is dismissed');
  process.exit(0);
}

console.log(`FAIL: dialogs on screen after dismissing the first: ${JSON.stringify(titles)}`);
process.exit(1);

--host-resolver-rules makes Chromium send game.test to 127.0.0.1 while the page’s location.hostname stays game.test, which is what isDevEnvironment() reads.

Exercise 3: report a statement no action takes

This exercise starts from 2.8.1, which had no dialog for this. Make the scratch copy from the tag: git worktree add --detach ../monogatari-exercises v2.8.1.

What to do. Put { 'Choise': { 'Yes': { 'Text': 'Yes', 'Do': 'next' } } } in a script and play up to it: nothing happens, and every click after it is refused. Make the engine show a new error, engine:run:no_action, naming the statement and the registered actions. Reaching the end of a label (no statement at all) must not show it.

Hint. Find where run() gives up when prepareAction() returns null. Which kinds of statement can get there, given that Dialog takes every string? The template goes in debug/index.js.

Check. The spec fails before the change and passes after it; actions/choices.spec.js, conditionals.spec.js, functions.spec.js and reversible_functions.spec.js still pass.

Solution

src/engine/lifecycle.ts, in run():

 	if (action === null) {
+		// A string always matches (Dialog takes any), so only an object can get
+		// here with a statement. Past the end of a label, the statement is undefined.
+		if (typeof statement === 'object') {
+			FancyError.show ('engine:run:no_action', {
+				statement: `<code class='language-javascript'>${JSON.stringify (statement)}</code>`,
+				availableActions: engine.actions ().map ((registered) => registered.id).join (', '),
+				label: engine.state ('label'),
+				step: engine.state ('step')
+			});
+		}
+
 		throw new Error ('The action did not match any of the ones registered.');
 	}

debug/index.js, in registerErrors(), before engine:run:function_error:

FancyError.register('engine:run:no_action', {
  title: 'No action can run this statement',
  message: 'Monogatari reached an object statement that none of the registered actions matched, so the game stopped there.',
  props: {
    'Statement': '{{statement}}',
    'Label': '{{label}}',
    'Step': '{{step}}',
    'Help': {
      '_': 'Check the statement for typos. An object statement starts with the name of its action, like Choice, Conditional or Notify.',
      '_1': 'Registered actions: {{availableActions}}',
    },
  },
});

cypress/e2e/exercises/unknown-statement.spec.js:

context('A statement no action takes', () => {
  beforeEach(() => {
    cy.open();
  });

  it('Shows engine:run:no_action for a misspelled object statement', function() {
    this.monogatari.setting('TypeAnimation', false);
    this.monogatari.script({
      'Start': [
        'One',
        { 'Choise': { 'Yes': { 'Text': 'Yes', 'Do': 'next' } } },
        'end',
      ],
    });

    cy.start();
    cy.get('text-box').contains('One');
    cy.proceed();
    cy.get('.fancy-error h2').should('contain', 'No action can run this statement');
    cy.get('.fancy-error').should('contain', 'Choise');
  });

  it('Shows nothing for a statement an action takes', function() {
    this.monogatari.setting('TypeAnimation', false);
    this.monogatari.script({
      'Start': [
        'One',
        { 'Choice': { 'Yes': { 'Text': 'Yes', 'Do': 'next' } } },
        'end',
      ],
    });

    cy.start();
    cy.proceed();
    cy.get('choice-container').should('exist');
    cy.get('.fancy-error').should('not.exist');
  });

  it('Shows nothing past the end of a label', function() {
    this.monogatari.setting('TypeAnimation', false);
    this.monogatari.script({
      'Start': [
        'One',
      ],
    });

    cy.start();
    cy.proceed();
    cy.get('.fancy-error').should('not.exist');
  });
});
bun build.ts --browser && bun build.ts --debug
bunx cypress run --browser chromium --spec 'cypress/e2e/exercises/unknown-statement.spec.js'

The game is still stuck after the dialog: the error is now visible, and the flag that blocks it is Statements and Actions’ business. 2.9.0 made the same change in run() (src/engine/lifecycle.ts), and fixed the lock in next(): compare the two.

Exercise 4: show errors thrown during play

What to do. This bug is fixed in 2.9.0, so do this exercise on the v2.8.1 tag, in a scratch worktree: git worktree add ../monogatari-v2.8.1 v2.8.1. Throw an error from a timer after the game started: the console shows it, the screen doesn’t. Change the debug module so an error thrown after the page loaded shows “An Unknown Error Occurred” as a load-time one does. A syntax error in js/script.js must still show its dialog.

Hint. Read the last block of debug/index.js. What does addEventListener('DOMContentLoaded', …) do once the event has fired? document.readyState tells you which case you’re in.

Check. The spec fails before the change and passes after it. Cypress fails a test on any uncaught error, so the spec turns that off with cy.on('uncaught:exception', () => false), and it builds the failing function with the game window’s Function, so the error is thrown in the game’s window and not in the spec’s.

Solution

debug/index.js, the error listener:

   window.addEventListener('error', (event) => {
     const { message, lineno, filename } = event;

-    // Once the DOM is ready, a Fancy Error will be shown providing more information
-    window.addEventListener('DOMContentLoaded', () => {
+    const report = () => {
       // Use Monogatari's FancyError if available
       const FancyError = window.Monogatari?.FancyError;
       if (FancyError) {
         FancyError.show (
           …
         );
       }
-    });
+    };
+
+    // An error while the page loads waits for the DOM so the dialog has a
+    // body to go in. Once the page has loaded, show it right away.
+    if (document.readyState === 'loading') {
+      window.addEventListener('DOMContentLoaded', report);
+    } else {
+      report();
+    }
   });

cypress/e2e/exercises/late-errors.spec.js:

context('Errors after the page loaded', () => {
  beforeEach(() => {
    cy.open();
  });

  it('Shows a dialog for an error thrown while playing', function() {
    // The error is the point of this test: don't let it fail the spec.
    cy.on('uncaught:exception', () => false);

    cy.window().then((win) => {
      // Built in the game's window, so the error is thrown there and
      // not in the spec's own window.
      const failLater = new win.Function(`
        setTimeout(() => {
          throw new Error ('Late failure');
        }, 0);

        return true;
      `);

      this.monogatari.setting('TypeAnimation', false);
      this.monogatari.script({
        'Start': [
          'One',
          failLater,
          'Two',
          'end',
        ],
      });
    });

    cy.start();
    cy.proceed();
    cy.get('text-box').contains('Two');
    cy.get('.fancy-error h2').should('contain', 'An Unknown Error Occurred');
    cy.get('.fancy-error').should('contain', 'Late failure');
  });
});
bun build.ts --debug
bunx cypress run --browser chromium --spec 'cypress/e2e/exercises/late-errors.spec.js'

To check the load-time case still works, break dist/js/script.js with a missing comma, serve dist/ and open it: “An Unknown Error Occurred” names the file and the line. 2.9.0 went further: it separates the two cases, giving a mistake found while the page loads its own dialog (“There is a mistake in js/script.js”), and its test is “Shows an error thrown after the game started” in cypress/e2e/error_dialogs.spec.js. Rejected promises still don’t show: that needs an unhandledrejection listener, a bigger change, because some engine code leaves a refused proceed() unhandled (src/actions/InputModal.ts, Message.ts and Video.ts call it without a catch), and those would show as errors.