@elvishscout/mdstory 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 ElvishScout
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ # MdStory
2
+
3
+ An interactive story format based on Markdown and Handlebars with JavaScript support.
4
+
5
+ Online demo available on <https://mdstory.elvish.cc>.
@@ -0,0 +1,128 @@
1
+ import handlebars from "handlebars";
2
+ import MarkdownIt from "markdown-it";
3
+ import pluginAttrs from "markdown-it-attrs";
4
+ const valueType = (value) => {
5
+ if (typeof value === "string") {
6
+ return "string";
7
+ }
8
+ if (typeof value === "number" || value === null) {
9
+ return "number";
10
+ }
11
+ if (typeof value === "boolean") {
12
+ return "boolean";
13
+ }
14
+ return "object";
15
+ };
16
+ const escapeHtml = (text) => text.replace(/[<>&'"]/g, (ch) => `&#${ch.charCodeAt(0)};`);
17
+ const createElementHtml = (tag, attrs, children) => {
18
+ // prettier-ignore
19
+ const voidTags = [
20
+ "area", "base", "br", "col", "embed", "hr", "img", "input",
21
+ "link", "meta", "param", "source", "track", "wbr",
22
+ ];
23
+ const attrText = Object.entries(attrs)
24
+ .filter(([, value]) => value !== undefined)
25
+ .map(([name, value]) => {
26
+ if (typeof value === "boolean") {
27
+ value = value ? "" : undefined;
28
+ }
29
+ const escapedValue = escapeHtml(value ?? "");
30
+ return `${name}="${escapedValue}"`;
31
+ })
32
+ .join(" ");
33
+ if (voidTags.includes(tag)) {
34
+ return `<${tag} ${attrText}>`;
35
+ }
36
+ return `<${tag} ${attrText}>${children ?? ""}</${tag}>`;
37
+ };
38
+ const createInputHtml = ({ tagMap = {}, name, type, value, required, readonly, }) => {
39
+ const tag = tagMap["input"] ?? "input";
40
+ const inputType = type === "boolean" ? "checkbox" : "text";
41
+ const inputAttrs = {
42
+ name,
43
+ type: inputType,
44
+ value: inputType !== "checkbox" ? (type === "object" ? JSON.stringify(value) : String(value)) : undefined,
45
+ checked: inputType === "checkbox" && value ? "" : undefined,
46
+ required,
47
+ readonly,
48
+ "aria-label": name,
49
+ };
50
+ return createElementHtml(tag, inputAttrs);
51
+ };
52
+ const createSubmitButtonHtml = ({ tagMap = {}, target, children, }) => {
53
+ const tag = tagMap["button"] ?? "button";
54
+ const buttonAttrs = {
55
+ name: "@target",
56
+ type: "submit",
57
+ value: target,
58
+ };
59
+ return createElementHtml(tag, buttonAttrs, children);
60
+ };
61
+ const createInputMarkdown = ({ name, type }) => {
62
+ if (type === "boolean") {
63
+ return `[ ${name}? ]`;
64
+ }
65
+ return `[> ${name} <]`;
66
+ };
67
+ const useHelper = ({ inputs, sets, navs }, options) => {
68
+ return {
69
+ input(type, opt) {
70
+ for (const name in opt.hash) {
71
+ const value = opt.hash[name];
72
+ inputs.push({ name, type, value });
73
+ if (options.format === "html") {
74
+ return createInputHtml({ name, type, value, ...options });
75
+ }
76
+ return createInputMarkdown({ name, type });
77
+ }
78
+ return "";
79
+ },
80
+ set(opt) {
81
+ return Object.entries(opt.hash)
82
+ .map(([name, value]) => {
83
+ const type = valueType(value);
84
+ sets.push({ name, type, value });
85
+ if (options.format === "html") {
86
+ return createInputHtml({ name, type, value, readonly: true, ...options });
87
+ }
88
+ return "";
89
+ })
90
+ .join("");
91
+ },
92
+ nav(target, opt) {
93
+ const text = opt.fn(target).trim();
94
+ navs.push({ text, target });
95
+ if (options.format === "html") {
96
+ return createSubmitButtonHtml({ target: target ?? "", children: text, ...options });
97
+ }
98
+ return "";
99
+ },
100
+ br(num) {
101
+ return new Array(num ?? 1).fill("<br>").join();
102
+ },
103
+ };
104
+ };
105
+ export class Chapter {
106
+ constructor({ id, title, template, hooks }) {
107
+ this.id = id;
108
+ this.title = title;
109
+ this.template = template;
110
+ this.hooks = hooks;
111
+ }
112
+ render(scope, options) {
113
+ const md = new MarkdownIt({ html: true }).use(pluginAttrs);
114
+ const fields = {
115
+ inputs: [],
116
+ sets: [],
117
+ navs: [],
118
+ };
119
+ const handle = handlebars.create();
120
+ handle.registerHelper(useHelper(fields, options));
121
+ let text = handle.compile(this.template)(scope);
122
+ if (options.format === "html") {
123
+ text = md.render(text);
124
+ text = createElementHtml("input", { type: "submit", disabled: true, hidden: true }) + text;
125
+ }
126
+ return { text, ...fields };
127
+ }
128
+ }
@@ -0,0 +1,20 @@
1
+ import { z } from "zod";
2
+ export const ValueSchema = z.any().transform((v) => v);
3
+ export const ScopeSchema = z.record(ValueSchema);
4
+ export const MetadataSchema = z.object({
5
+ title: z.string().default(""),
6
+ globals: ScopeSchema.default({}),
7
+ });
8
+ const TargetSchema = z.string().or(z.null());
9
+ export const StoryHooksSchema = z
10
+ .object({
11
+ onStart: z.function().args(ScopeSchema).returns(ScopeSchema.or(z.void())),
12
+ })
13
+ .partial();
14
+ export const ChapterHooksSchema = z
15
+ .object({
16
+ onEnter: z.function().args(ScopeSchema).returns(ScopeSchema.or(z.void())),
17
+ onLeave: z.function().args(ScopeSchema, ScopeSchema).returns(ScopeSchema.or(z.void())),
18
+ onNavigate: z.function().args(TargetSchema, ScopeSchema, ScopeSchema).returns(TargetSchema.or(z.void())),
19
+ })
20
+ .partial();
@@ -0,0 +1,30 @@
1
+ export class InvalidMetadataError extends Error {
2
+ constructor(content, message) {
3
+ super(message ?? `Invalid metadata:\n\`\`\`\n${content}\n\`\`\``);
4
+ this.content = content;
5
+ }
6
+ }
7
+ export class DuplicateIdError extends Error {
8
+ constructor(id, message) {
9
+ super(message ?? `Two chapters with the same id \`${id}\`.`);
10
+ this.id = id;
11
+ }
12
+ }
13
+ export class EmptyChapterIdError extends Error {
14
+ constructor(message) {
15
+ super(message ?? `Chapter id cannot be empty, either use an non-empty chapter title or explicitly specify an id.`);
16
+ }
17
+ }
18
+ export class ChapterNotFoundError extends Error {
19
+ constructor(target, message) {
20
+ super(message ?? `Chapter \`${target}\` not found.`);
21
+ this.target = target;
22
+ }
23
+ }
24
+ export class InvalidInputError extends Error {
25
+ constructor(name, input, message) {
26
+ super(message ?? `Invalid input \`${input}\` for variable \`${name}\`.`);
27
+ this.name = name;
28
+ this.input = input;
29
+ }
30
+ }
@@ -0,0 +1,4 @@
1
+ export * from "./definitions.js";
2
+ export * from "./story.js";
3
+ export * from "./chapter.js";
4
+ export * from "./error.js";
@@ -0,0 +1,164 @@
1
+ import yaml from "js-yaml";
2
+ import MarkdownIt from "markdown-it";
3
+ import pluginFrontMatter from "markdown-it-front-matter";
4
+ import pluginAttrs from "markdown-it-attrs";
5
+ import { MetadataSchema, StoryHooksSchema, ChapterHooksSchema, } from "./definitions.js";
6
+ import { Chapter } from "./chapter.js";
7
+ import { ChapterNotFoundError, DuplicateIdError, EmptyChapterIdError, InvalidInputError, InvalidMetadataError, } from "./error.js";
8
+ const parstInput = (type, text) => {
9
+ if (type === "boolean") {
10
+ return text === "on";
11
+ }
12
+ if (type === "number") {
13
+ return text ? Number(text) : null;
14
+ }
15
+ if (type === "object") {
16
+ return text ? JSON.parse(text) : null;
17
+ }
18
+ return text;
19
+ };
20
+ const parseFormData = (formData, { inputs, sets }) => {
21
+ const target = formData.get("@target") || null;
22
+ const updates = Object.fromEntries([...inputs, ...sets].map(({ name, type }) => {
23
+ const value = formData.get(name);
24
+ try {
25
+ return [name, parstInput(type, value)];
26
+ }
27
+ catch {
28
+ throw new InvalidInputError(name, value);
29
+ }
30
+ }));
31
+ return { target, updates };
32
+ };
33
+ export const parseStoryContent = (content) => {
34
+ const md = new MarkdownIt({ html: true }).use(pluginAttrs).use(pluginFrontMatter, () => { });
35
+ const tokens = md.parse(content, {});
36
+ let metadata = MetadataSchema.parse({});
37
+ let storyScript = "";
38
+ let stylesheet = "";
39
+ const ignoredRanges = [];
40
+ const divisions = [];
41
+ tokens.forEach((token, i) => {
42
+ if (token.type === "front_matter" && token.meta) {
43
+ try {
44
+ const frontMatter = MetadataSchema.parse(yaml.load(token.meta));
45
+ metadata = { ...metadata, ...frontMatter };
46
+ }
47
+ catch {
48
+ throw new InvalidMetadataError(token.meta);
49
+ }
50
+ }
51
+ else if (token.type === "heading_open" && token.tag === "h1" && token.level === 0 && token.map) {
52
+ const lineno = token.map[0];
53
+ let id = token.attrs?.find(([key]) => key === "id")?.[1] ?? "";
54
+ let title = "";
55
+ const nextToken = tokens[i + 1];
56
+ if (nextToken && nextToken.type === "inline") {
57
+ const content = nextToken.content.trim();
58
+ id || (id = content);
59
+ title = content;
60
+ }
61
+ if (!id) {
62
+ throw new EmptyChapterIdError();
63
+ }
64
+ if (divisions.find(({ id: _id }) => id === _id)) {
65
+ throw new DuplicateIdError(id);
66
+ }
67
+ divisions.push({ id, title, lineno, script: "" });
68
+ }
69
+ else if (token.type === "html_block" && token.map) {
70
+ let regres;
71
+ if ((regres = /^[\s]*<script>(.*)<\/script>[\s]*$/s.exec(token.content))) {
72
+ const script = regres[1].trim();
73
+ if (script) {
74
+ if (divisions.length === 0) {
75
+ storyScript = script;
76
+ }
77
+ else {
78
+ divisions[divisions.length - 1].script = script;
79
+ }
80
+ ignoredRanges.push(token.map);
81
+ }
82
+ }
83
+ else if ((regres = /^[\s]*<style>(.*)<\/style>[\s]*$/s.exec(token.content))) {
84
+ const style = regres[1].trim();
85
+ stylesheet += style;
86
+ ignoredRanges.push(token.map);
87
+ }
88
+ }
89
+ });
90
+ const lines = content.split("\n").map((line, i) => {
91
+ if (ignoredRanges.find(([from, to]) => i >= from && i < to)) {
92
+ return null;
93
+ }
94
+ return line;
95
+ });
96
+ const chapterEntries = divisions.map(({ id, title, lineno, script }, i) => {
97
+ const template = lines
98
+ .slice(lineno, divisions[i + 1]?.lineno)
99
+ .filter((line) => line !== null)
100
+ .join("\n");
101
+ const hooks = script ? ChapterHooksSchema.parse(new Function(script)()) : {};
102
+ return [id, { title, template, hooks }];
103
+ });
104
+ const chapters = Object.fromEntries(chapterEntries);
105
+ const entry = chapterEntries[0]?.[0] || null;
106
+ const hooks = storyScript ? StoryHooksSchema.parse(new Function(storyScript)()) : {};
107
+ return {
108
+ metadata,
109
+ chapters,
110
+ entry,
111
+ hooks,
112
+ stylesheet,
113
+ };
114
+ };
115
+ export class StoryBase {
116
+ constructor({ metadata, chapters, entry, hooks, stylesheet }) {
117
+ const realChapters = Object.fromEntries(Object.entries(chapters).map(([id, options]) => {
118
+ return [id, new Chapter({ id, ...options })];
119
+ }));
120
+ this.metadata = metadata;
121
+ this.globals = metadata.globals;
122
+ this.chapters = realChapters;
123
+ this.entry = (entry && realChapters[entry]) || null;
124
+ this.hooks = hooks;
125
+ this.stylesheet = stylesheet;
126
+ }
127
+ async play(prompt, options) {
128
+ if (this.hooks.onStart) {
129
+ this.hooks.onStart(this.globals);
130
+ }
131
+ let chapter = this.entry;
132
+ while (chapter) {
133
+ let modifiedGlobals = this.globals;
134
+ if (chapter.hooks.onEnter) {
135
+ const modified = chapter.hooks.onEnter(this.globals);
136
+ if (modified !== undefined) {
137
+ modifiedGlobals = Object.assign(modifiedGlobals, modified);
138
+ }
139
+ }
140
+ const renderResult = chapter.render(modifiedGlobals, options);
141
+ const promptResult = await prompt({ chapter, ...renderResult });
142
+ const { target, updates } = promptResult instanceof FormData ? parseFormData(promptResult, renderResult) : promptResult;
143
+ let modifiedTarget = target;
144
+ let modifiedUpdates = updates;
145
+ if (chapter.hooks.onLeave) {
146
+ const modified = chapter.hooks.onLeave(updates, this.globals);
147
+ if (modified !== undefined) {
148
+ modifiedUpdates = Object.assign(updates, modified);
149
+ }
150
+ }
151
+ if (chapter.hooks.onNavigate) {
152
+ const modified = chapter.hooks.onNavigate(target, updates, this.globals);
153
+ if (modified !== undefined) {
154
+ modifiedTarget = modified;
155
+ }
156
+ }
157
+ this.globals = Object.assign(this.globals, modifiedUpdates);
158
+ if (modifiedTarget !== null && !(modifiedTarget in this.chapters)) {
159
+ throw new ChapterNotFoundError(modifiedTarget);
160
+ }
161
+ chapter = modifiedTarget !== null ? this.chapters[modifiedTarget] : null;
162
+ }
163
+ }
164
+ }
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export * from "./base/index.js";
2
+ import { StoryBase, parseStoryContent } from "./base/index.js";
3
+ export class Story extends StoryBase {
4
+ constructor(content) {
5
+ super(parseStoryContent(content));
6
+ }
7
+ }
@@ -0,0 +1,44 @@
1
+ import { ValueType, Value, ChapterHooks, Scope } from "./definitions.js";
2
+ type MarkdownOptions = {};
3
+ type HtmlOptions = {
4
+ tagMap?: Record<string, string>;
5
+ };
6
+ export type RenderOptions = ({
7
+ format: "markdown";
8
+ } & MarkdownOptions) | ({
9
+ format: "html";
10
+ } & HtmlOptions);
11
+ type Fields = {
12
+ inputs: {
13
+ name: string;
14
+ type: ValueType;
15
+ value: Value;
16
+ }[];
17
+ sets: {
18
+ name: string;
19
+ type: ValueType;
20
+ value: Value;
21
+ }[];
22
+ navs: {
23
+ text: string;
24
+ target: string | null;
25
+ }[];
26
+ };
27
+ export type RenderResult = {
28
+ text: string;
29
+ } & Fields;
30
+ export type ChapterOptions = {
31
+ id: string;
32
+ title: string;
33
+ template: string;
34
+ hooks: ChapterHooks;
35
+ };
36
+ export declare class Chapter {
37
+ id: string;
38
+ title: string;
39
+ template: string;
40
+ hooks: ChapterHooks;
41
+ constructor({ id, title, template, hooks }: ChapterOptions);
42
+ render(scope: Scope, options: RenderOptions): RenderResult;
43
+ }
44
+ export {};
@@ -0,0 +1,46 @@
1
+ import { z } from "zod";
2
+ type JsonPrimitive = number | string | boolean | null;
3
+ type JsonArray = JsonValue[];
4
+ type JsonObject = {
5
+ [key: string]: JsonValue;
6
+ };
7
+ type JsonValue = JsonPrimitive | JsonArray | JsonObject;
8
+ export declare const ValueSchema: z.ZodEffects<z.ZodAny, string | number | boolean | JsonArray | JsonObject | null, any>;
9
+ export declare const ScopeSchema: z.ZodRecord<z.ZodString, z.ZodEffects<z.ZodAny, string | number | boolean | JsonArray | JsonObject | null, any>>;
10
+ export declare const MetadataSchema: z.ZodObject<{
11
+ title: z.ZodDefault<z.ZodString>;
12
+ globals: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodEffects<z.ZodAny, string | number | boolean | JsonArray | JsonObject | null, any>>>;
13
+ }, "strip", z.ZodTypeAny, {
14
+ title: string;
15
+ globals: Record<string, string | number | boolean | JsonArray | JsonObject | null>;
16
+ }, {
17
+ title?: string | undefined;
18
+ globals?: Record<string, any> | undefined;
19
+ }>;
20
+ export declare const StoryHooksSchema: z.ZodObject<{
21
+ onStart: z.ZodOptional<z.ZodFunction<z.ZodTuple<[z.ZodRecord<z.ZodString, z.ZodEffects<z.ZodAny, string | number | boolean | JsonArray | JsonObject | null, any>>], z.ZodUnknown>, z.ZodUnion<[z.ZodRecord<z.ZodString, z.ZodEffects<z.ZodAny, string | number | boolean | JsonArray | JsonObject | null, any>>, z.ZodVoid]>>>;
22
+ }, "strip", z.ZodTypeAny, {
23
+ onStart?: ((args_0: Record<string, any>, ...args: unknown[]) => void | Record<string, string | number | boolean | JsonArray | JsonObject | null>) | undefined;
24
+ }, {
25
+ onStart?: ((args_0: Record<string, string | number | boolean | JsonArray | JsonObject | null>, ...args: unknown[]) => void | Record<string, any>) | undefined;
26
+ }>;
27
+ export declare const ChapterHooksSchema: z.ZodObject<{
28
+ onEnter: z.ZodOptional<z.ZodFunction<z.ZodTuple<[z.ZodRecord<z.ZodString, z.ZodEffects<z.ZodAny, string | number | boolean | JsonArray | JsonObject | null, any>>], z.ZodUnknown>, z.ZodUnion<[z.ZodRecord<z.ZodString, z.ZodEffects<z.ZodAny, string | number | boolean | JsonArray | JsonObject | null, any>>, z.ZodVoid]>>>;
29
+ onLeave: z.ZodOptional<z.ZodFunction<z.ZodTuple<[z.ZodRecord<z.ZodString, z.ZodEffects<z.ZodAny, string | number | boolean | JsonArray | JsonObject | null, any>>, z.ZodRecord<z.ZodString, z.ZodEffects<z.ZodAny, string | number | boolean | JsonArray | JsonObject | null, any>>], z.ZodUnknown>, z.ZodUnion<[z.ZodRecord<z.ZodString, z.ZodEffects<z.ZodAny, string | number | boolean | JsonArray | JsonObject | null, any>>, z.ZodVoid]>>>;
30
+ onNavigate: z.ZodOptional<z.ZodFunction<z.ZodTuple<[z.ZodUnion<[z.ZodString, z.ZodNull]>, z.ZodRecord<z.ZodString, z.ZodEffects<z.ZodAny, string | number | boolean | JsonArray | JsonObject | null, any>>, z.ZodRecord<z.ZodString, z.ZodEffects<z.ZodAny, string | number | boolean | JsonArray | JsonObject | null, any>>], z.ZodUnknown>, z.ZodUnion<[z.ZodUnion<[z.ZodString, z.ZodNull]>, z.ZodVoid]>>>;
31
+ }, "strip", z.ZodTypeAny, {
32
+ onEnter?: ((args_0: Record<string, any>, ...args: unknown[]) => void | Record<string, string | number | boolean | JsonArray | JsonObject | null>) | undefined;
33
+ onLeave?: ((args_0: Record<string, any>, args_1: Record<string, any>, ...args: unknown[]) => void | Record<string, string | number | boolean | JsonArray | JsonObject | null>) | undefined;
34
+ onNavigate?: ((args_0: string | null, args_1: Record<string, any>, args_2: Record<string, any>, ...args: unknown[]) => string | void | null) | undefined;
35
+ }, {
36
+ onEnter?: ((args_0: Record<string, string | number | boolean | JsonArray | JsonObject | null>, ...args: unknown[]) => void | Record<string, any>) | undefined;
37
+ onLeave?: ((args_0: Record<string, string | number | boolean | JsonArray | JsonObject | null>, args_1: Record<string, string | number | boolean | JsonArray | JsonObject | null>, ...args: unknown[]) => void | Record<string, any>) | undefined;
38
+ onNavigate?: ((args_0: string | null, args_1: Record<string, string | number | boolean | JsonArray | JsonObject | null>, args_2: Record<string, string | number | boolean | JsonArray | JsonObject | null>, ...args: unknown[]) => string | void | null) | undefined;
39
+ }>;
40
+ export type Value = z.infer<typeof ValueSchema>;
41
+ export type Scope = z.infer<typeof ScopeSchema>;
42
+ export type Metadata = z.infer<typeof MetadataSchema>;
43
+ export type StoryHooks = z.infer<typeof StoryHooksSchema>;
44
+ export type ChapterHooks = z.infer<typeof ChapterHooksSchema>;
45
+ export type ValueType = "string" | "number" | "boolean" | "object";
46
+ export {};
@@ -0,0 +1,20 @@
1
+ export declare class InvalidMetadataError extends Error {
2
+ content: string;
3
+ constructor(content: string, message?: string);
4
+ }
5
+ export declare class DuplicateIdError extends Error {
6
+ id: string;
7
+ constructor(id: string, message?: string);
8
+ }
9
+ export declare class EmptyChapterIdError extends Error {
10
+ constructor(message?: string);
11
+ }
12
+ export declare class ChapterNotFoundError extends Error {
13
+ target: string | null;
14
+ constructor(target: string | null, message?: string);
15
+ }
16
+ export declare class InvalidInputError extends Error {
17
+ name: string;
18
+ input: string | null;
19
+ constructor(name: string, input: string | null, message?: string);
20
+ }
@@ -0,0 +1,4 @@
1
+ export * from "./definitions.js";
2
+ export * from "./story.js";
3
+ export * from "./chapter.js";
4
+ export * from "./error.js";
@@ -0,0 +1,32 @@
1
+ import { StoryHooks, Scope, Metadata, ChapterHooks } from "./definitions.js";
2
+ import { Chapter, RenderOptions, RenderResult } from "./chapter.js";
3
+ export type StoryPrompt = (props: {
4
+ chapter: Chapter;
5
+ } & RenderResult) => Promise<{
6
+ target: string | null;
7
+ updates: Scope;
8
+ } | FormData>;
9
+ type ChapterBody = {
10
+ title: string;
11
+ template: string;
12
+ hooks: ChapterHooks;
13
+ };
14
+ type StoryBody = {
15
+ metadata: Metadata;
16
+ chapters: Record<string, ChapterBody>;
17
+ entry: string | null;
18
+ hooks: StoryHooks;
19
+ stylesheet: string;
20
+ };
21
+ export declare const parseStoryContent: (content: string) => StoryBody;
22
+ export declare class StoryBase {
23
+ metadata: Metadata;
24
+ globals: Scope;
25
+ chapters: Record<string, Chapter>;
26
+ entry: Chapter | null;
27
+ hooks: StoryHooks;
28
+ stylesheet: string;
29
+ constructor({ metadata, chapters, entry, hooks, stylesheet }: StoryBody);
30
+ play(prompt: StoryPrompt, options: RenderOptions): Promise<void>;
31
+ }
32
+ export {};
@@ -0,0 +1,5 @@
1
+ export * from "./base/index.js";
2
+ import { StoryBase } from "./base/index.js";
3
+ export declare class Story extends StoryBase {
4
+ constructor(content: string);
5
+ }
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@elvishscout/mdstory",
3
+ "version": "0.1.0",
4
+ "description": "An interactive story format based on Markdown and Handlebars with JavaScript support",
5
+ "main": "./dist/index.js",
6
+ "type": "module",
7
+ "files": [
8
+ "./dist",
9
+ "./types"
10
+ ],
11
+ "scripts": {
12
+ "build": "tsc",
13
+ "test": "node ./test/index.test.js"
14
+ },
15
+ "devDependencies": {
16
+ "@types/js-yaml": "^4.0.9",
17
+ "@types/markdown-it": "^14.1.2",
18
+ "@types/markdown-it-attrs": "^4.1.3",
19
+ "@types/node": "^22.14.1",
20
+ "inquirer": "^12.6.0",
21
+ "markdown-it-terminal": "^0.4.0",
22
+ "typescript": "~5.7.2"
23
+ },
24
+ "dependencies": {
25
+ "handlebars": "^4.7.8",
26
+ "js-yaml": "^4.1.0",
27
+ "markdown-it": "^14.1.0",
28
+ "markdown-it-attrs": "^4.3.1",
29
+ "markdown-it-front-matter": "^0.2.4",
30
+ "zod": "^3.24.3"
31
+ },
32
+ "types": "./types",
33
+ "keywords": [
34
+ "markdown",
35
+ "handlebars"
36
+ ],
37
+ "author": "Jiakai Jiang",
38
+ "license": "ISC"
39
+ }
@@ -0,0 +1,44 @@
1
+ import { ValueType, Value, ChapterHooks, Scope } from "./definitions.js";
2
+ type MarkdownOptions = {};
3
+ type HtmlOptions = {
4
+ tagMap?: Record<string, string>;
5
+ };
6
+ export type RenderOptions = ({
7
+ format: "markdown";
8
+ } & MarkdownOptions) | ({
9
+ format: "html";
10
+ } & HtmlOptions);
11
+ type Fields = {
12
+ inputs: {
13
+ name: string;
14
+ type: ValueType;
15
+ value: Value;
16
+ }[];
17
+ sets: {
18
+ name: string;
19
+ type: ValueType;
20
+ value: Value;
21
+ }[];
22
+ navs: {
23
+ text: string;
24
+ target: string | null;
25
+ }[];
26
+ };
27
+ export type RenderResult = {
28
+ text: string;
29
+ } & Fields;
30
+ export type ChapterOptions = {
31
+ id: string;
32
+ title: string;
33
+ template: string;
34
+ hooks: ChapterHooks;
35
+ };
36
+ export declare class Chapter {
37
+ id: string;
38
+ title: string;
39
+ template: string;
40
+ hooks: ChapterHooks;
41
+ constructor({ id, title, template, hooks }: ChapterOptions);
42
+ render(scope: Scope, options: RenderOptions): RenderResult;
43
+ }
44
+ export {};
@@ -0,0 +1,46 @@
1
+ import { z } from "zod";
2
+ type JsonPrimitive = number | string | boolean | null;
3
+ type JsonArray = JsonValue[];
4
+ type JsonObject = {
5
+ [key: string]: JsonValue;
6
+ };
7
+ type JsonValue = JsonPrimitive | JsonArray | JsonObject;
8
+ export declare const ValueSchema: z.ZodEffects<z.ZodAny, string | number | boolean | JsonArray | JsonObject | null, any>;
9
+ export declare const ScopeSchema: z.ZodRecord<z.ZodString, z.ZodEffects<z.ZodAny, string | number | boolean | JsonArray | JsonObject | null, any>>;
10
+ export declare const MetadataSchema: z.ZodObject<{
11
+ title: z.ZodDefault<z.ZodString>;
12
+ globals: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodEffects<z.ZodAny, string | number | boolean | JsonArray | JsonObject | null, any>>>;
13
+ }, "strip", z.ZodTypeAny, {
14
+ title: string;
15
+ globals: Record<string, string | number | boolean | JsonArray | JsonObject | null>;
16
+ }, {
17
+ title?: string | undefined;
18
+ globals?: Record<string, any> | undefined;
19
+ }>;
20
+ export declare const StoryHooksSchema: z.ZodObject<{
21
+ onStart: z.ZodOptional<z.ZodFunction<z.ZodTuple<[z.ZodRecord<z.ZodString, z.ZodEffects<z.ZodAny, string | number | boolean | JsonArray | JsonObject | null, any>>], z.ZodUnknown>, z.ZodUnion<[z.ZodRecord<z.ZodString, z.ZodEffects<z.ZodAny, string | number | boolean | JsonArray | JsonObject | null, any>>, z.ZodVoid]>>>;
22
+ }, "strip", z.ZodTypeAny, {
23
+ onStart?: ((args_0: Record<string, any>, ...args: unknown[]) => void | Record<string, string | number | boolean | JsonArray | JsonObject | null>) | undefined;
24
+ }, {
25
+ onStart?: ((args_0: Record<string, string | number | boolean | JsonArray | JsonObject | null>, ...args: unknown[]) => void | Record<string, any>) | undefined;
26
+ }>;
27
+ export declare const ChapterHooksSchema: z.ZodObject<{
28
+ onEnter: z.ZodOptional<z.ZodFunction<z.ZodTuple<[z.ZodRecord<z.ZodString, z.ZodEffects<z.ZodAny, string | number | boolean | JsonArray | JsonObject | null, any>>], z.ZodUnknown>, z.ZodUnion<[z.ZodRecord<z.ZodString, z.ZodEffects<z.ZodAny, string | number | boolean | JsonArray | JsonObject | null, any>>, z.ZodVoid]>>>;
29
+ onLeave: z.ZodOptional<z.ZodFunction<z.ZodTuple<[z.ZodRecord<z.ZodString, z.ZodEffects<z.ZodAny, string | number | boolean | JsonArray | JsonObject | null, any>>, z.ZodRecord<z.ZodString, z.ZodEffects<z.ZodAny, string | number | boolean | JsonArray | JsonObject | null, any>>], z.ZodUnknown>, z.ZodUnion<[z.ZodRecord<z.ZodString, z.ZodEffects<z.ZodAny, string | number | boolean | JsonArray | JsonObject | null, any>>, z.ZodVoid]>>>;
30
+ onNavigate: z.ZodOptional<z.ZodFunction<z.ZodTuple<[z.ZodUnion<[z.ZodString, z.ZodNull]>, z.ZodRecord<z.ZodString, z.ZodEffects<z.ZodAny, string | number | boolean | JsonArray | JsonObject | null, any>>, z.ZodRecord<z.ZodString, z.ZodEffects<z.ZodAny, string | number | boolean | JsonArray | JsonObject | null, any>>], z.ZodUnknown>, z.ZodUnion<[z.ZodUnion<[z.ZodString, z.ZodNull]>, z.ZodVoid]>>>;
31
+ }, "strip", z.ZodTypeAny, {
32
+ onEnter?: ((args_0: Record<string, any>, ...args: unknown[]) => void | Record<string, string | number | boolean | JsonArray | JsonObject | null>) | undefined;
33
+ onLeave?: ((args_0: Record<string, any>, args_1: Record<string, any>, ...args: unknown[]) => void | Record<string, string | number | boolean | JsonArray | JsonObject | null>) | undefined;
34
+ onNavigate?: ((args_0: string | null, args_1: Record<string, any>, args_2: Record<string, any>, ...args: unknown[]) => string | void | null) | undefined;
35
+ }, {
36
+ onEnter?: ((args_0: Record<string, string | number | boolean | JsonArray | JsonObject | null>, ...args: unknown[]) => void | Record<string, any>) | undefined;
37
+ onLeave?: ((args_0: Record<string, string | number | boolean | JsonArray | JsonObject | null>, args_1: Record<string, string | number | boolean | JsonArray | JsonObject | null>, ...args: unknown[]) => void | Record<string, any>) | undefined;
38
+ onNavigate?: ((args_0: string | null, args_1: Record<string, string | number | boolean | JsonArray | JsonObject | null>, args_2: Record<string, string | number | boolean | JsonArray | JsonObject | null>, ...args: unknown[]) => string | void | null) | undefined;
39
+ }>;
40
+ export type Value = z.infer<typeof ValueSchema>;
41
+ export type Scope = z.infer<typeof ScopeSchema>;
42
+ export type Metadata = z.infer<typeof MetadataSchema>;
43
+ export type StoryHooks = z.infer<typeof StoryHooksSchema>;
44
+ export type ChapterHooks = z.infer<typeof ChapterHooksSchema>;
45
+ export type ValueType = "string" | "number" | "boolean" | "object";
46
+ export {};
@@ -0,0 +1,20 @@
1
+ export declare class InvalidMetadataError extends Error {
2
+ content: string;
3
+ constructor(content: string, message?: string);
4
+ }
5
+ export declare class DuplicateIdError extends Error {
6
+ id: string;
7
+ constructor(id: string, message?: string);
8
+ }
9
+ export declare class EmptyChapterIdError extends Error {
10
+ constructor(message?: string);
11
+ }
12
+ export declare class ChapterNotFoundError extends Error {
13
+ target: string | null;
14
+ constructor(target: string | null, message?: string);
15
+ }
16
+ export declare class InvalidInputError extends Error {
17
+ name: string;
18
+ input: string | null;
19
+ constructor(name: string, input: string | null, message?: string);
20
+ }
@@ -0,0 +1,4 @@
1
+ export * from "./definitions.js";
2
+ export * from "./story.js";
3
+ export * from "./chapter.js";
4
+ export * from "./error.js";
@@ -0,0 +1,32 @@
1
+ import { StoryHooks, Scope, Metadata, ChapterHooks } from "./definitions.js";
2
+ import { Chapter, RenderOptions, RenderResult } from "./chapter.js";
3
+ export type StoryPrompt = (props: {
4
+ chapter: Chapter;
5
+ } & RenderResult) => Promise<{
6
+ target: string | null;
7
+ updates: Scope;
8
+ } | FormData>;
9
+ type ChapterBody = {
10
+ title: string;
11
+ template: string;
12
+ hooks: ChapterHooks;
13
+ };
14
+ type StoryBody = {
15
+ metadata: Metadata;
16
+ chapters: Record<string, ChapterBody>;
17
+ entry: string | null;
18
+ hooks: StoryHooks;
19
+ stylesheet: string;
20
+ };
21
+ export declare const parseStoryContent: (content: string) => StoryBody;
22
+ export declare class StoryBase {
23
+ metadata: Metadata;
24
+ globals: Scope;
25
+ chapters: Record<string, Chapter>;
26
+ entry: Chapter | null;
27
+ hooks: StoryHooks;
28
+ stylesheet: string;
29
+ constructor({ metadata, chapters, entry, hooks, stylesheet }: StoryBody);
30
+ play(prompt: StoryPrompt, options: RenderOptions): Promise<void>;
31
+ }
32
+ export {};
@@ -0,0 +1,5 @@
1
+ export * from "./base/index.js";
2
+ import { StoryBase } from "./base/index.js";
3
+ export declare class Story extends StoryBase {
4
+ constructor(content: string);
5
+ }