### Start a story and continue maximally Source: https://github.com/y-lohse/inkjs/blob/master/README.md Creates a Story instance from the loaded JSON and continues it to get all output. ```javascript var inkStory = new Story(json); console.log(inkStory.ContinueMaximally()); //etc ``` -------------------------------- ### Install inkjs via npm Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/README.md Install the inkjs package using npm. ```bash npm install inkjs ``` -------------------------------- ### StartProfiling() Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Story.md Starts profiling. No-op stub (profiler not ported). ```APIDOC ## StartProfiling() ### Description Starts profiling. No-op stub (profiler not ported). ### Method StartProfiling ### Parameters None ### Returns void ``` -------------------------------- ### Example: Compiling with options Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/CompilerOptions.md Shows how to create a Compiler instance with the options object and compile the ink source. ```javascript import { Compiler } from "inkjs/full"; const c = new Compiler(`INCLUDE "knots.ink"\nHello`, options); const story = c.Compile(); ``` -------------------------------- ### Story Usage Example Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Story.md Demonstrates how to create a Story instance, continue through the narrative, and access current choices. ```APIDOC ## Story Usage Example ### Description Create a Story instance and iterate through the narrative using Continue() and currentChoices. ### Code Example ```ts import { Story } from "inkjs"; const story = new Story(storyJson); // string or object while (story.canContinue) { const chunk = story.Continue(); // one line (or async-safe chunk) console.log(chunk); } // Choices at the end of the flow: story.currentChoices.forEach(c => console.log(`— ${c.text} (index ${c.index})`)); ``` ### Properties Used - `canContinue` (boolean) - Whether Continue() can advance. - `Continue()` - Returns the next line of text. - `currentChoices` (Choice[]) - Choices currently offered to the player. ``` -------------------------------- ### Usage Example Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/InkList.md Example of using InkList with story variables in inkjs. ```APIDOC ## Usage Example ### Description Demonstrates how to retrieve an InkList from story variables and modify it. ### Example ```js import { Story, InkList } from "inkjs"; const story = new Story(storyJson); // assume the story declares: LIST colours = red, green, blue // and assigns: my_list = colours.red, colours.green const list = story.variablesState.$("my_list"); console.log(list instanceof InkList); // true console.log(list.Count, list.maxItem, list.minItemapsed()); list.AddItem("green", 2); console.log(story.variablesState.$("my_list")); // includes green:2 ``` ``` -------------------------------- ### Example: Creating CompilerOptions with PosixFileHandler Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/CompilerOptions.md Shows how to instantiate CompilerOptions with a custom error handler and a PosixFileHandler for file-based INCLUDE resolution. ```javascript import { CompilerOptions, PosixFileHandler } from "inkjs/full"; const options = new CompilerOptions( null, // sourceFilename [], // plugins true, // countAllVisits (message, type) => { console.error(`[${type}] ${message}`); }, new PosixFileHandler("./ink") DescriptiveCheckbox(); ``` -------------------------------- ### Example: Using JsonFileHandler for browser environments Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/CompilerOptions.md Shows how to use JsonFileHandler with an in-memory map for platforms without fs/process, such as browsers. ```javascript import { JsonFileHandler } from "inkjs/full"; const memoryFH = new JsonFileHandler({ "knots.ink": "knot innards:\nHello, {~world|universe}!\n-> ->", }); ``` -------------------------------- ### Compiler error checking example Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/errors.md Shows how to check compiler errors after compilation. If errors exist, log them; otherwise, the story is ready. The example includes a placeholder 'story.AddError; // never'. ```typescript const compiler = new Compiler(inkSourceinos); const story = compiler.Compile(); if (compiler.errors.length > 0) { console.error("ink failed to compile", compiler.errors); } else { story.AddError; // never } ``` -------------------------------- ### Example: compile with plugin and file handler Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Compiler.md Compiles ink source with a `CompilerOptions` object that includes a source filename, an error handler, and a `PosixFileHandler` to resolve INCLUDEs. The source uses an INCLUDE directive. ```javascript import { Compiler, PosixFileHandler } from "inkjs/full"; const options = new CompilerOptions({ sourceFilename: "my_story.ink", errorHandler: (msg, type) => console.warn(`[${type}] ${msg}`), fileHandler: new PosixFileHandler(import.meta.dirname), // resolve INCLUDEs }); const story = new Compiler(`INCLUDE ./part.ink\nHello`, options).Compile(); ``` -------------------------------- ### Example: compile and play a story Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Compiler.md Compiles a simple ink source string and continues the story, printing the first line. Uses `Compiler` and `Story` from `inkjs/full`. ```javascript import { Compiler, Story } from "inkjs/full"; const source = ` Hello world! -> END `; const story = new Compiler(source).Compile(); console.log(story.Continue()); // "Hello world!" ``` -------------------------------- ### Quick start: load and continue a story Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/README.md Load a story from JSON, continue while possible, print text and tags, and list choices. Also shows compiling from ink source directly. ```ts import { Story, InkList } from "inkjs"; const story = new Story(storyJson); // storyJson from inklecate while (story.canContinue) { console.log(story.Continue()); // text run console.log(story.currentTags); // tags for that run } story.currentChoices.forEach((c) => console.log(c.text)); // Compile from ink source directly: import { Compiler } from "inkjs/full"; const compiled = new Compiler("Hello {~ world|universe}!\n-> END").Compile(); compiled.ContinueMaximally(); ``` -------------------------------- ### InkList usage example Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/InkList.md Example of retrieving an InkList from a story's variables state, checking its type, and adding an item. Assumes the story declares a list and assigns it. ```javascript import { Story, InkList } from "inkjs"; const story = new Story(storyJson); // assume the story declares: LIST colours = red, green, blue // and assigns: my_list = colours.red, colours.green const list = story.variablesState.$("my_list"); console.log(list instanceof InkList); // true console.log(list.Count, list.maxItem, list.minItemapsed()); list.AddItem("green", 2); console.log(story.variablesState.$("my_list")); // includes green:2 ``` -------------------------------- ### Choice usage example Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Choice.md Shows how to iterate over current choices, log their index, text, and tags, then choose one and continue the story. ```typescript import { Story } from "inkjs"; const story = new Story(storyJson); story.ContinueMaximally(); for (const c of story.currentChoices) { console.log(`${c.index} — ${c.text} (# ${c.tags})`); } // pick one story.ChooseChoiceIndex(0); console.log(story.Continue()); ``` -------------------------------- ### Using the POSIX file handler with inkjs from npm Source: https://github.com/y-lohse/inkjs/blob/master/docs/compiler-differences.md Example of using the POSIX file handler, delivered as a separate inkjs-full-posixhandler.js file, to compile an ink file from a folder. Requires requiring 'inkjs/compiler/FileHandler/PosixFileHandler' and reading the file with fs. ```javascript var inkjs = require('inkjs/full'); var { PosixFileHandler } = require('inkjs/compiler/FileHandler/PosixFileHandler'); const inkFile = fs.readFileSync(`${PATH_TO_STORY_FOLDER}/main.ink`, 'UTF-8').replace(/^\uFEFF/, ''); const fileHandler = new PosixFileHandler(`${PATH_TO_STORY_FOLDER}/`); const errorHandler = (message, errorType) => { console.log(message + "\n"); } const story = new inkjs.Compiler(inkFile, {fileHandler, errorHandler}).Compile(); //story.Continue() ``` -------------------------------- ### Compile ink source to Story Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Compiler.md Imports `Compiler` and `CompilerOptions` from `inkjs/full`, creates a new `Compiler` instance with the ink source and optional options, and calls `Compile()` to get a runtime `Story`. ```typescript import { Compiler, CompilerOptions } from "inkjs/full"; const runtimeStory = new Compiler(inkSource, options).Compile(); // runtimeStory is a Story — play it as usual. ``` -------------------------------- ### Using VariablesState to get/set and observe variables (TypeScript) Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/VariablesState.md Shows how to set and get a variable using the $() method and how to observe changes with ObserveVariable. The observer callback receives the variable name and new value. ```typescript import { Story } from "inkjs"; const story = new Story(storyJson); story.variablesState.$("player_health", 100); console.log(story.variablesState.$("player_health")); story.ObserveVariable("gold", (name: string, value: any) => { console.log(`gold is now ${value}`); }); ``` -------------------------------- ### Choice.pathStringOnChoice (get/set) Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Choice.md Gets or sets the string representation of the target path. Throws NullException when targetPath is null. ```APIDOC ## Choice.pathStringOnChoice (get/set) ### Description Gets or sets the string representation of the target path. Throws NullException when targetPath is null. ### Property pathStringOnChoice: string ### Access - **get** - Returns `targetPath.toString()`. - **set** - Sets the target path from the given string. ### Exceptions - **NullException** - Thrown when `targetPath` is null during get. ``` -------------------------------- ### ContinueAsync(ms) Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Story.md Continues asynchronously, returning text accumulated so far. Can be called again later. Only use on a Story that was NOT started on the main flow. ```APIDOC ## ContinueAsync(ms) ### Description Continues asynchronously, returning text accumulated so far. Can be called again later. Only use on a Story that was NOT started on the main flow. ### Method ContinueAsync ### Parameters - **ms** (number) - Required - The number of milliseconds to continue for, or until it can't. ### Returns string - text accumulated so far ``` -------------------------------- ### Flow Control: ContinueMaximally, ContinueSingleStep, ContinueAsync Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Story.md Use ContinueMaximally to advance the story as far as possible in one tick. ContinueSingleStep forces a single logic step and returns true if progress was made. ContinueAsync is story-safe against re-entrancy and should only be used on a Story not started on the main flow; it returns text accumulated so far and can be called again later. ```TypeScript // Continue the story as far as it can go in this tick story.ContinueMaximally(); // Or force a single logic step (returns true if it made any progress) story.ContinueSingleStep(); // Continue asynchronously (story-safe against re-entrancy): // returns text accumulated so far; you can call it again later. // (Only use on a Story that was NOT started on the main flow.) story.ContinueAsync(5); // continue for ~5 ms, or until it can't ``` -------------------------------- ### $(variableName) - Get variable value Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/VariablesState.md Gets the value of a global or temporary variable. Equivalent to C# VariablesState[variableName]. ```APIDOC ## $(variableName) ### Description Gets the value of a global or temporary variable. Equivalent to C# `VariablesState[variableName]`. ### Method GET (accessor) ### Parameters - **variableName** (string) - Required - The name of the variable to retrieve. ### Returns - **any** - The current value of the variable. ### Example ```ts const health = story.variablesState.$("player_health"); ``` ``` -------------------------------- ### Set and get ink variables with $ function Source: https://github.com/y-lohse/inkjs/blob/master/README.md On platforms without ES2015 Proxies, use the `$` function to set and get variables instead of direct property access. ```javascript _inkStory.variablesState.$('player_health', 100); //instead of _inkStory.variablesState["player_health"] = 100; var health = _inkStory.variablesState.$('player_health'); //instead of var health = _inkStory.variablesState["player_health"]; ``` -------------------------------- ### GetVariableWithName(variableName) Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/VariablesState.md Gets the InkObject for a variable by name. ```APIDOC ## GetVariableWithName(variableName) ### Description Gets the InkObject for a variable by name. ### Parameters - **variableName** (string) - Required - The name of the variable. ### Returns - **InkObject** - The variable's InkObject. ``` -------------------------------- ### Choosing a Choice and Continuing Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Story.md Demonstrates how to use ContinueMaximally() to drain all text, then choose a choice and continue. ```APIDOC ## Choosing a Choice and Continuing ### Description Use ContinueMaximally() to get all remaining text, then select a choice by index and continue the story. ### Code Example ```ts const story = new Story(storyJson); story.ContinueMaximally(); // drains all text to a single string story.ChooseChoiceIndex(0); // pick the first choice (equivalent to ChooseChoiceIndex via choice index) console.log(story.Continue()); // output after the choice ``` ### Methods Used - `ContinueMaximally()` - Continues until the story stops, returning all text as a single string. - `ChooseChoiceIndex(index)` - Selects a choice by its index. - `Continue()` - Returns the next line of text. ``` -------------------------------- ### GetRawVariableWithName(variableName) Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/VariablesState.md Gets the raw InkObject for a variable by name. ```APIDOC ## GetRawVariableWithName(variableName) ### Description Gets the raw InkObject for a variable by name. ### Parameters - **variableName** (string) - Required - The name of the variable. ### Returns - **InkObject** - The raw variable object. ``` -------------------------------- ### Compiler.authorMessages Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Compiler.md Gets the array of AUTHOR messages from the ink source. ```APIDOC ## Compiler.authorMessages ### Description Gets the array of AUTHOR messages from the ink source. ### Returns - **string[]** - Array of author messages. ### Notes These are accumulates; call Compiler.ResetErrors() or create a fresh Compiler per source to clear them. ``` -------------------------------- ### new CompilerOptions(...) Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/CompilerOptions.md Creates a CompilerOptions instance with optional sourceFilename, pluginNames, countAllVisits, errorHandler, and fileHandler. This options object is passed to the Compiler constructor. ```APIDOC ## new CompilerOptions(...) ### Description Creates a CompilerOptions instance with optional sourceFilename, pluginNames, countAllVisits, errorHandler, and fileHandler. This options object is passed to the Compiler constructor. ### Constructor `new CompilerOptions(sourceFilename?, pluginNames?, countAllVisits?, errorHandler?, fileHandler?)` ### Parameters - **sourceFilename** (`string | null`) - Optional - Filename used in error/warning messages and debug metadata (line numbers). No file is read from disk. Default: `null`. - **pluginNames** (`string[]`) - Optional - Names of compiler plugins (not yet implemented — reserved). Default: `[]`. - **countAllVisits** (`boolean`) - Optional - When true, count visits to *all* knots/stitches/weave points (enables `visitCount` everywhere). Default: `false`. - **errorHandler** (`ErrorHandler | null`) - Optional - Called for every parse/compile error, warning and author message. If null, messages are only collected in `compiler.errors/warnings/authorMessages`. Default: `null`. - **fileHandler** (`IFileHandler | null`) - Optional - Resolves `INCLUDE`s. If null (or `DefaultFileHandler`), INCLUDEs throw. Default: `null`. ### Example ```js import { CompilerOptions, PosixFileHandler } from "inkjs/full"; const options = new CompilerOptions( null, // sourceFilename [], // plugins true, // countAllVisits (message, type) => { console.error(`[${type}] ${message}`); }, new PosixFileHandler("./ink") ); ``` ``` -------------------------------- ### Compiler.warnings Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Compiler.md Gets the array of parse/author warnings accumulated during compilation. ```APIDOC ## Compiler.warnings ### Description Gets the array of parse/author warnings accumulated during compilation. ### Returns - **string[]** - Array of warning messages. ### Notes These are accumulates; call Compiler.ResetErrors() or create a fresh Compiler per source to clear them. ``` -------------------------------- ### Path Constructor Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Path.md Creates a new Path instance. Supports empty relative path, parsing a components string, prepending a component, or building from components. ```APIDOC ## Path Constructor ### Description Creates a new Path instance. Supports empty relative path, parsing a components string, prepending a component, or building from components. ### Method constructor ### Signature ```ts constructor(); // empty relative path constructor(componentsString: string); // parse "knot.stitch", ".", "^", etc. constructor(head: Path.Component, tail: Path); // prepend component constructor(head: Path.Component[], relative?: boolean); // build from components ``` ### Parameters - `componentsString` (string) - Optional - The serialized path string to parse. - `head` (Path.Component | Path.Component[]) - Optional - A component or array of components to build the path from. - `tail` (Path) - Optional - A path to append after the head component. - `relative` (boolean) - Optional - Whether the path is relative (defaults to false). ### Returns A new Path instance. ``` -------------------------------- ### TryGetDefaultVariableValue(name) Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/VariablesState.md Tries to get the default value of a variable from global decl. ```APIDOC ## TryGetDefaultVariableValue(name) ### Description Tries to get the default value of a variable from `global decl`. ### Parameters - **name** (string | null) - Required - The name of the variable. ### Returns - **InkObject | null** - The default value object, or null if not found. ``` -------------------------------- ### GetVariable(name) Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/VariablesState.md Gets the value of a variable by name (via namespace helper). ```APIDOC ## GetVariable(name) ### Description Gets the value of a variable by name (via namespace helper). ### Parameters - **name** (string) - Required - The name of the variable. ### Returns - **any** - The variable's value. ``` -------------------------------- ### Navigate Content with ChoosePathString, ChooseChoiceIndex, and More Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Story.md Shows how to divert to a knot or stitch, pass arguments, choose a choice by index, and look up containers and pointers. Note that resetCallstack = false is unsafe and kept only for parity with the C# port. ```TypeScript story.ChoosePathString("knot.sub_stitch", true); // divert (resets call stack) story.ChoosePathString("knot", true, ["arg1"]); // with arguments story.ChooseChoiceIndex(0); // choose a choice by index story.ContentAtPath(new Path("knot_content")); // container lookup story.KnotContainerWithName("knot"); // knot container story.PointerAtPath(path); // content pointer ``` -------------------------------- ### Compiler.errors Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Compiler.md Gets the array of parse/author errors (ErrorType.Author + ErrorType.Error) accumulated during compilation. ```APIDOC ## Compiler.errors ### Description Gets the array of parse/author errors (ErrorType.Author + ErrorType.Error) accumulated during compilation. ### Returns - **string[]** - Array of error messages. ### Notes These are accumulates; call Compiler.ResetErrors() or create a fresh Compiler per source to clear them. ``` -------------------------------- ### Compiler construction with CompilerOptions Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/configuration.md Creates a Compiler instance with an options object specifying source filename, plugin names, visit counting, error handler, and file handler. The Compile() method returns a Story object. ```TypeScript import { Compiler, CompilerOptions } from "inkjs/full"; const options = new CompilerOptions( "my_story.ink", // sourceFilename [], // pluginNames false, // countAllVisits onError, // errorHandler fileHandler // fileHandler (is: IFileHandler) // see below (null) ); const story = new Compiler(inkSourceString, options).Compile(); ``` -------------------------------- ### EvaluateFunction without output Source: https://github.com/y-lohse/inkjs/blob/master/README.md Calls EvaluateFunction normally to get the return value of an ink function. ```javascript var result = EvaluateFunction('my_ink_function', ['arg1', 'arg2']); //result is the return value of my_ink_function("arg1", "arg2") ``` -------------------------------- ### Use full bundle with compiler Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/README.md Import the full inkjs bundle to access the Compiler and compile ink source directly. ```js const inkjs = require("inkjs/full"); const story = new inkjs.Compiler(`Hello world!`).Compile(); ``` -------------------------------- ### Full type reference Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/types.md Links to full type reference documentation for Choice, ChoicePoint, Path, InkList, Story, StoryState, and VariablesState. ```APIDOC ## Full type reference - [Choice.md](api-reference/Choice.md) — `Choice`, `ChoicePoint`. - [ChoicePoint.md](api-reference/ChoicePoint.md) — flags & flow. - [Path.md](api-reference/Path.md) — `Path`, `Path.Component`, namespace. - [InkList.md](api-reference/InkList.md) — `InkList`, `InkListItem`, serialised list format. - [Story.md](api-reference/Story.md) — all `Story` members + namespace types. - [StoryState.md](api-reference/StoryState.md) — `StoryState` + patch + flow. - [VariablesState.md](api-reference/VariablesState.md) — `VariablesState`, `$`, observers. ``` -------------------------------- ### Import and compile an ink file with inkjs Source: https://github.com/y-lohse/inkjs/blob/master/docs/working-with-typescript-and-webpack.md Use this to import the .ink file and compile it with the Compiler from 'inkjs/full'. The imported data is a string containing the ink source. ```javascript import { Compiler } from 'inkjs/full'; import data from '../assets/myStory.ink'; const inkStory = new Compiler(data).Compile(); ``` -------------------------------- ### Load inkjs in browser via script tag Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/README.md Include the inkjs browser bundle from unpkg and create a Story instance using the global inkjs object. ```html ``` -------------------------------- ### Story Constructor (string) Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Story.md Creates a Story instance from a raw JSON string, typically the contents of a .ink.json file. Validates version numbers and root token presence. ```APIDOC ## Story Constructor (string) ### Description Creates a Story instance from a raw JSON string, typically the contents of a .ink.json file. Validates version numbers and root token presence. ### Method Constructor ### Signature constructor(jsonString: string) ### Parameters - **jsonString** (string) - Required - Raw story JSON output from `story.ToJson()`. ### Throws - **Error** - If the JSON is malformed, version is incompatible, or root token is missing. ### Example ```ts const story = new Story(jsonString); ``` ``` -------------------------------- ### Story Constructor (Container, ListDefinition[]) Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Story.md Creates a Story instance directly from a Container tree and list definitions. Used by compiler internals; version validation only occurs in the JSON path. ```APIDOC ## Story Constructor (Container, ListDefinition[]) ### Description Creates a Story instance directly from a Container tree and list definitions. Used by compiler internals; version validation only occurs in the JSON path. ### Method Constructor ### Signature constructor(contentContainer: Container, lists: ListDefinition[] | null = null) ### Parameters - **contentContainer** (Container) - Required - The root Container tree. - **lists** (ListDefinition[] | null) - Optional - List definitions, defaults to null. ### Example ```ts const story = new Story(container, lists); ``` ``` -------------------------------- ### Access Global Tags and Content Hierarchy Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Story.md Retrieves global tags, tags for a specific container, tags at the start of a flow container, and a debug string of the content hierarchy. ```TypeScript story.globalTags; // tags at the very top story.TagsForContentAtPath(path); // tags for a knot/stitch container story.TagsAtStartOfFlowContainerWithPathString(pathString); story.BuildStringOfHierarchy(); // debug string of all content containers ``` -------------------------------- ### Runtime story error handling with try/catch Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/errors.md Shows how to catch StoryException when loading and continuing a story. If the error is a StoryException, log a warning; otherwise rethrow. ```typescript try { const story = new Story(jsonString); story.Continue(); } catch (e) { if (e instanceof StoryException) { console.warn("story error:", e.message); } else { throw e; } } ``` -------------------------------- ### SwitchToDefaultFlow() Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Story.md Switches back to the default flow. ```APIDOC ## SwitchToDefaultFlow() ### Description Switches back to the default flow. ### Method SwitchToDefaultFlow ### Parameters None ### Returns void ``` -------------------------------- ### Path Methods Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Path.md Methods for manipulating and querying Path instances. ```APIDOC ## Path Methods ### Description Methods for manipulating and querying Path instances. ### Methods #### GetComponent(index) Returns the component at the given index. - `index` (number) - The index of the component. - Returns: `Path.Component` #### PathByAppendingPath(pathToAppend) Returns a new Path that is the concatenation of this path and the given path. - `pathToAppend` (Path) - The path to append. - Returns: `Path` #### PathByAppendingComponent(c) Returns a new Path that is this path plus one component. - `c` (Path.Component) - The component to append. - Returns: `Path` #### ConvertPathToRelative(otherPath) Returns a relative path from this path to the given path. - `otherPath` (Path) - The target path. - Returns: `Path` #### CompactPathString(otherPath) Returns the shortest of the two path strings (relative vs global). - `otherPath` (Path) - The other path to compare. - Returns: `string` #### Equals(otherPath) Checks component-wise equality with another path. - `otherPath` (Path) - The path to compare. - Returns: `boolean` #### toString() Returns the componentsString. - Returns: `string` ``` -------------------------------- ### Path Static Members Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Path.md Static properties and helpers for Path. ```APIDOC ## Path Static Members ### Description Static properties and helpers for Path. ### Static Properties - `parentId` (string) - Static string marker for parent (`"^"`). - `self` (Path) - Empty relative path (`"."`). - `parent` (Path) - Single `^` component. ### Static Methods - `Path.Component.ToParent()` - Returns a Component representing the parent. - `Path.Component.Parent` - Static property for parent component. - `Path.Component.Self` - Static property for self component. ``` -------------------------------- ### inkjs-compiler CLI help output Source: https://github.com/y-lohse/inkjs/blob/master/README.md Shows the usage and options for the inkjs-compiler command-line tool. The -p flag enables play mode, which is automatic when a JSON file is passed. The -k flag keeps inklecate running after the story completes. ```shell $ node inkjs-compiler.js -h Usage: inkjs-compiler -o : Output file name -c: Count all visits to knots, stitches and weave points, not just those referenced by TURNS_SINCE and read counts. -p: Play mode (automatic if a json file is passed as argument) -s: Print stats about story including word count in JSON format -k: Keep inklecate running in play mode even after story is complete ``` -------------------------------- ### InkList Class - Constructors and Static Methods Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/types.md InkList extends Map and represents a list of ink items with associated values. Provides multiple constructors and static factory methods. ```APIDOC ## InkList Class - Constructors and Static Methods ### Description InkList extends Map and represents a list of ink items with associated values. Provides multiple constructors and static factory methods. ### Constructors - `new InkList()` - Creates an empty InkList. - `new InkList(otherList: InkList)` - Creates a copy of another InkList. - `new InkList(singleOriginListName: string, originStory: Story)` - Creates an InkList from a single origin list name. - `new InkList(singleElement: KeyValuePair)` - Creates an InkList with a single element. ### Static Methods - `static FromString(myListItem: string, originStory: Story): InkList` - Creates an InkList from a string representation. - `static isInkList(obj: any): boolean` - Checks if an object is an InkList. ``` -------------------------------- ### Choosing a choice and continuing the story Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Story.md Creates a Story instance, drains all text with ContinueMaximally(), picks the first choice with ChooseChoiceIndex(0), and logs the output after the choice with Continue(). ```TypeScript const story = new Story(storyJson); story.ContinueMaximally(); // drains all text to a single string story.ChooseChoiceIndex(0); // pick the first choice (equivalent to ChooseChoiceIndex via choice index) console.log(story.Continue()); // output after the choice ``` -------------------------------- ### ContinueSingleStep() Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Story.md Forces a single logic step and returns true if it made any progress. ```APIDOC ## ContinueSingleStep() ### Description Forces a single logic step. Returns true if it made any progress. ### Method ContinueSingleStep ### Parameters None ### Returns boolean - true if progress was made ``` -------------------------------- ### InkList Constructor Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/InkList.md Creates an InkList instance. Supports empty, copy, single-origin, and single-element constructors. ```APIDOC ## InkList Constructor ### Description Creates an InkList instance. Supports empty, copy, single-origin, and single-element constructors. ### Method constructor ### Signature ```ts constructor(); constructor(otherList: InkList); constructor(singleOriginListName: string, originStory: Story); constructor(singleElement: KeyValuePair); ``` ### Parameters - **otherList** (InkList) - Optional - Copy constructor (copies `origins`/`_originNames`). - **singleOriginListName** (string) - Optional - Origin list name (e.g. `"colours"`); membership is resolved against the story’s list definitions via `originStory.listDefinitions`. Throws new `Error` if the origin isn't found. - **originStory** (Story) - Required when `singleOriginListName` is provided - The story used to resolve list definitions. - **singleElement** (KeyValuePair) - Optional - Single-element list (from `AddItem` payloads). ### Public Fields - **origins** (ListDefinition[] | null) - Default: `null` - List origins. - **_originNames** (string[] | null) - Default: `[]` - Origin names. ### Example ```ts // Empty list const emptyList = new InkList(); // Copy constructor const copyList = new InkList(otherList); // Single-origin list const coloursList = new InkList("colours", story); // Single-element list const singleElementList = new InkList({ item: new InkListItem("colours", "red"), value: 1 }); ``` ``` -------------------------------- ### InkList.FromString Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/InkList.md Builds a one-item list from an item name (e.g. "colours.red" or "red") using the story's list definitions. Throws if not found. ```APIDOC ## InkList.FromString ### Description Builds a one-item list from an item name (e.g. "colours.red" or "red") using the story's list definitions. Throws if not found. ### Method static ### Signature ```ts public static FromString(myListItem: string, originStory: Story): InkList; ``` ### Parameters - **myListItem** (string) - Required - The item name, e.g. "colours.red" or "red". - **originStory** (Story) - Required - The story used to resolve list definitions. ### Returns - **InkList** - A new InkList containing the single item. ### Throws - **Error** - If the item is not found in the story's list definitions. ### Example ```ts const list = InkList.FromString("colours.red", story); ``` ``` -------------------------------- ### Load JSON file with fs and strip BOM Source: https://github.com/y-lohse/inkjs/blob/master/README.md Loads an ink JSON file using fs.readFileSync and strips the UTF-8 BOM that inklecate outputs. ```javascript var fs = require('fs'); var json = fs.readFileSync('./ink_file.json', 'UTF-8').replace(/^\uFEFF/, ''); //strips the BOM ``` -------------------------------- ### Webpack rule to load .ink files as asset/source Source: https://github.com/y-lohse/inkjs/blob/master/docs/working-with-typescript-and-webpack.md Add this rule to your Webpack configuration to load .ink files and inline their content as a string. Useful for programs that unconditionally use a single Ink file. ```javascript rules: [ { test: /\.ink$/i, type: 'asset/source', }, // ... and then the rest of your rules ]; ``` -------------------------------- ### Path class declaration with constructor overloads Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Path.md Shows the Path class with its static parentId, fields, and four constructor overloads for creating empty relative paths, parsing strings, prepending components, and building from components. ```TypeScript export class Path { public static parentId = "^"; public _isRelative: boolean; public _components: Path.Component[]; public _componentsString: string | null; constructor(); // empty relative path constructor(componentsString: string); // parse "knot.stitch", ".", "^", etc. constructor(head: Path.Component, tail: Path); // prepend component constructor(head: Path.Component[], relative?: boolean); // build from components } ``` -------------------------------- ### InkList Class - Instance Methods and Properties Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/types.md Methods for adding, removing, and querying items in an InkList, along with list algebra operations and comparison operators. ```APIDOC ## InkList Class - Instance Methods and Properties ### Description Methods for adding, removing, and querying items in an InkList, along with list algebra operations and comparison operators. ### Properties - `origins` (ListDefinition[] | null) - The list definitions associated with this InkList. - `_originNames` (string[] | null) - The origin names. - `Count` (number) - The number of items in the list. - `orderedItems` (KeyValuePair[]) - The items in order. - `maxItem` (InkListItem | null) - The item with the maximum value. - `minItem` (InkListItem | null) - The item with the minimum value. - `originOfMaxItem` (ListDefinition | null) - The origin of the max item. - `originOfMinItem` (ListDefinition | null) - The origin of the min item. ### Methods - `AddItem(item: InkListItem | string, value?: number): void` - Adds an item to the list. - `ContainsItemNamed(itemName: string): boolean` - Checks if the list contains an item with the given name. - `ContainsKey(key: InkListItem): boolean` - Checks if the list contains the given key. - `Add(item: InkListItem, value: number): void` - Adds an item with a value. - `Remove(item: InkListItem): boolean` - Removes an item and returns true if removed. - `Union(otherList: InkList): InkList` - Returns the union of two lists. - `Intersect(otherList: InkList): InkList` - Returns the intersection of two lists. - `Without(otherList: InkList): InkList` - Returns the list without items from another list. - `HasIntersection(otherList: InkList): boolean` - Checks if there is an intersection. - `MaxAsList(): InkList` - Returns a list with only the max item. - `MinAsList(): InkList` - Returns a list with only the min item. - `ListWithSubRange(minBound, maxBound): InkList` - Returns a subrange of the list. - `ListWithSubList(minBound, maxBound): InkList` - Returns a sublist. - `Contains(list: InkList): boolean` - Checks if this list contains another list. - `Contains(itemName: string): boolean` - Checks if the list contains an item by name. - `Contains(key: InkListItem): boolean` - Checks if the list contains a key. - `GreaterThan(otherList: InkList): boolean` - Checks if this list is greater than another. - `GreaterThanOrEquals(otherList: InkList): boolean` - Checks if this list is greater than or equal to another. - `LessThan(otherList: InkList): boolean` - Checks if this list is less than another. - `LessThanOrEquals(otherList: InkList): boolean` - Checks if this list is less than or equal to another. - `Equals(otherInkList: InkList): boolean` - Checks equality with another InkList. ``` -------------------------------- ### ContinueMaximally() Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Story.md Continues the story as far as it can go in the current tick. ```APIDOC ## ContinueMaximally() ### Description Continues the story as far as it can go in the current tick. ### Method ContinueMaximally ### Parameters None ### Returns void ``` -------------------------------- ### Content Navigation Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Story.md Methods to navigate the story content by diverting to paths, choosing choices, and looking up containers. ```APIDOC ## Content Navigation ### Description Methods to navigate the story content by diverting to paths, choosing choices, and looking up containers. ### Methods #### ChoosePathString(path, resetCallstack, arguments?) - **Parameters**: - `path` (string) - Required - The path to divert to (e.g., "knot.sub_stitch"). - `resetCallstack` (boolean) - Required - Whether to reset the call stack. Note: `false` is unsafe and disallowed in the C# port; kept for parity. - `arguments` (string[]) - Optional - Arguments to pass to the path. - **Description**: Diverts to the specified path, optionally resetting the call stack. #### ChooseChoiceIndex(index) - **Parameters**: - `index` (number) - Required - The index of the choice to choose. - **Description**: Chooses a choice by its index. #### ContentAtPath(path) - **Parameters**: - `path` (Path) - Required - The path to look up. - **Returns**: Container - The container at the given path. #### KnotContainerWithName(name) - **Parameters**: - `name` (string) - Required - The name of the knot. - **Returns**: Container - The knot container. #### PointerAtPath(path) - **Parameters**: - `path` (Path) - Required - The path to get a pointer for. - **Returns**: Pointer - The content pointer at the given path. ``` -------------------------------- ### Story Constructor (object) Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Story.md Creates a Story instance from an already-parsed story JSON object. Used by Compiler's Compile() and save/load pipelines. ```APIDOC ## Story Constructor (object) ### Description Creates a Story instance from an already-parsed story JSON object. Used by Compiler's Compile() and save/load pipelines. ### Method Constructor ### Signature constructor(json: Record) ### Parameters - **json** (Record) - Required - Already-parsed story JSON object. ### Throws - **Error** - If the JSON is malformed, version is incompatible, or root token is missing. ### Example ```ts const story = new Story(jsonObject); ``` ``` -------------------------------- ### Load JSON file with require Source: https://github.com/y-lohse/inkjs/blob/master/README.md Loads an ink JSON file using Node's require. ```javascript var json = require('./ink_file.json'); ``` -------------------------------- ### Import inkjs module Source: https://github.com/y-lohse/inkjs/blob/master/README.md Loads the inkjs Story class using ES6 import syntax. ```javascript import { Story } from 'inkjs'; ``` -------------------------------- ### ChoicePoint.toString() Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Choice.md Returns a string representation of the ChoicePoint, e.g. "Choice -> {target}". ```APIDOC ## ChoicePoint.toString() ### Description Returns a string representation of the ChoicePoint, e.g. "Choice -> {target}". ### Method toString() ### Returns - **string** - A string representation of the ChoicePoint. ``` -------------------------------- ### Basic Story continuation and choice iteration Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Story.md Imports Story from inkjs, creates a new Story instance with storyJson (string or object), and loops while canContinue is true, logging each chunk from Continue(). After the flow ends, iterates currentChoices to log each choice text and index. ```TypeScript import { Story } from "inkjs"; const story = new Story(storyJson); // string or object while (story.canContinue) { const chunk = story.Continue(); // one line (or async-safe chunk) console.log(chunk); } // Choices at the end of the flow: story.currentChoices.forEach(c => console.log(`— ${c.text} (index ${c.index})`)); ``` -------------------------------- ### Load story JSON with fetch and create inkjs.Story Source: https://github.com/y-lohse/inkjs/blob/master/README.md Use this snippet to load a story from a JSON file via fetch, which requires a web server due to CORS. It fetches 'story.json', converts the response to text, then creates a new inkjs.Story instance and calls continueStory(). ```javascript fetch('story.json') .then(function (response) { return response.text(); }) .then(function (storyContent) { story = new inkjs.Story(storyContent); continueStory(); }); ``` -------------------------------- ### ChoicePoint toString() implementation Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/ChoicePoint.md The toString() method returns a string in the format 'ChoicePoint -> {target}', where target is the path string or 'null' if no path is set. ```typescript public toString(): string { return "ChoicePoint -> " + (this.pathOnChoice?.toString() || "null"); } ``` -------------------------------- ### Compiler.Compile() Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Compiler.md Compiles the ink source string into a runtime Story object. Returns null if parse/compile errors occur, and errors are available via the errors getter. ```APIDOC ## Compiler.Compile() ### Description Compiles the ink source string into a runtime Story object. Returns null if parse/compile errors occur, and errors are available via the errors getter. ### Method Compile ### Returns - **Story** - The compiled runtime story. If parse/compile errors occurred, returns null (and errors is non-empty). Throw on compile-error via options.errorHandler. ### Example ```ts import { Compiler, Story } from "inkjs/full"; const source = ` Hello world! -> END `; const story = new Compiler(source).Compile(); console.log(story.Continue()); // "Hello world!" ``` ``` -------------------------------- ### Compiler.RetrieveDebugSourceForLatestContent() Source: https://github.com/y-lohse/inkjs/blob/master/_autodocs/api-reference/Compiler.md Retrieves debug source information for the most recently compiled content. ```APIDOC ## Compiler.RetrieveDebugSourceForLatestContent() ### Description Retrieves debug source information for the most recently compiled content. ### Returns - **void** - This method does not return a value. ```