worldformat 0.0.0-stage → 0.3.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) 2026 L. C. Maren
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 CHANGED
@@ -1,3 +1,91 @@
1
- # Temporary Holding Version
1
+ # World Format
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Reference implementation of the **World** text format.
4
+
5
+ This repository contains a minimal parser and related utilities
6
+ for reading and writing World documents.
7
+
8
+ The World format is a human-editable snapshot format designed for
9
+ small systems and human–AI workflows.
10
+
11
+ ## Status
12
+
13
+ ⚠️ Experimental.
14
+
15
+ - APIs may change without notice
16
+ - No stability or backward-compatibility guarantees
17
+ - Test coverage is minimal or nonexistent
18
+
19
+ ## Specification
20
+
21
+ The format definition lives here:
22
+
23
+ https://worldformat.org
24
+
25
+ This repository follows the specification, but may lead or lag it
26
+ as the format evolves.
27
+
28
+ ## Usage
29
+
30
+ ```sh
31
+ npm install worldformat
32
+ ```
33
+
34
+ ```ts
35
+ import { parse, stringify, validate } from "worldformat";
36
+
37
+ const world = parse(`
38
+ [task]
39
+ name = "Test"
40
+ done = false
41
+ `);
42
+ // → { task: { name: "Test", done: false } }
43
+
44
+ validate("name = 1"); // → false: an attribute needs a node above it
45
+ ```
46
+
47
+ `parse` throws on an invalid document; `validate` returns `false` instead.
48
+
49
+ `stringify` writes a world back as text:
50
+
51
+ ```ts
52
+ stringify({ task: [{ name: "A" }, { name: "B" }] });
53
+ // → '[task]\nname = "A"\n\n[task]\nname = "B"\n'
54
+ ```
55
+
56
+ `parse(stringify(world))` gives back `world`, except that arrays of 0 or 1
57
+ items come back the way `parse` reads them: a one-item array as that object,
58
+ an empty array as an absent key. The output is normalized, so comments and
59
+ layout from a hand-written document are not kept.
60
+
61
+ `stringify` throws on anything the format can't hold: values other than
62
+ strings, numbers and booleans (such as `null` or arrays of primitives),
63
+ strings containing `"` or a line break, `NaN`, `Infinity` and `-0`,
64
+ repeated nodes that have child nodes, and keys that `parse` would misread.
65
+
66
+ `parse` accepts some text that `stringify` won't write back, such as
67
+ `x = "say "hi""` or an unquoted `x = foo` (which reads as `NaN`). If a
68
+ document must stay writable, check that `stringify(parse(text))` succeeds
69
+ before saving it.
70
+
71
+ The package is ESM only.
72
+
73
+ ## Scope
74
+
75
+ This repository may grow to include:
76
+
77
+ - parsers
78
+ - generators
79
+ - format utilities
80
+
81
+ It intentionally does **not** include:
82
+
83
+ - schema enforcement
84
+ - validation rules
85
+ - storage layers
86
+
87
+ Those concerns belong elsewhere.
88
+
89
+ ## License
90
+
91
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,13 @@
1
+ type AnyObj = Record<string, any>;
2
+ export declare function parse(text: string): AnyObj;
3
+ export declare function validate(text: string): boolean;
4
+ /**
5
+ * Write a World document for `world`, the inverse of `parse`.
6
+ *
7
+ * `parse(stringify(world))` deep-equals `world`, except that arrays of 0 or 1
8
+ * items come back the way `parse` reads them: a one-item array as that object,
9
+ * an empty array as an absent key. Anything else the format can't hold
10
+ * throws. Comments and layout are not kept; the output is normalized.
11
+ */
12
+ export declare function stringify(world: Record<string, unknown>): string;
13
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,207 @@
1
+ function parseValue(raw) {
2
+ // string
3
+ if (raw.startsWith('"') && raw.endsWith('"')) {
4
+ return raw.slice(1, -1);
5
+ }
6
+ // boolean
7
+ if (raw === "true")
8
+ return true;
9
+ if (raw === "false")
10
+ return false;
11
+ // number
12
+ return Number(raw);
13
+ }
14
+ export function parse(text) {
15
+ const root = {};
16
+ const lines = text.split(/\r?\n/);
17
+ let currentPath = null;
18
+ let currentNode = null;
19
+ for (const rawLine of lines) {
20
+ const line = stripComment(rawLine);
21
+ if (!line)
22
+ continue;
23
+ // Node declaration
24
+ if (line.startsWith("[") && line.endsWith("]")) {
25
+ const path = line.slice(1, -1).split("/");
26
+ let cursor = root;
27
+ for (let i = 0; i < path.length; i++) {
28
+ const key = path[i];
29
+ const isLeaf = i === path.length - 1;
30
+ if (isLeaf) {
31
+ if (!(key in cursor)) {
32
+ cursor[key] = {};
33
+ currentNode = cursor[key];
34
+ }
35
+ else if (Array.isArray(cursor[key])) {
36
+ const obj = {};
37
+ cursor[key].push(obj);
38
+ currentNode = obj;
39
+ }
40
+ else {
41
+ const first = cursor[key];
42
+ const obj = {};
43
+ cursor[key] = [first, obj];
44
+ currentNode = obj;
45
+ }
46
+ }
47
+ else {
48
+ if (!(key in cursor)) {
49
+ cursor[key] = {};
50
+ }
51
+ else if (Array.isArray(cursor[key])) {
52
+ throw new Error(`Ambiguous parent path: "${path.slice(0, i + 1).join("/")}"`);
53
+ }
54
+ cursor = cursor[key];
55
+ }
56
+ }
57
+ currentPath = path;
58
+ continue;
59
+ }
60
+ // Attribute
61
+ if (currentNode) {
62
+ const idx = line.indexOf("=");
63
+ if (idx === -1) {
64
+ throw new Error(`Invalid line: "${line}"`);
65
+ }
66
+ const key = line.slice(0, idx).trim();
67
+ const rawValue = line.slice(idx + 1).trim();
68
+ currentNode[key] = parseValue(rawValue);
69
+ continue;
70
+ }
71
+ // If we reach here, the line is invalid
72
+ throw new Error(`Invalid line: "${line}"`);
73
+ }
74
+ return root;
75
+ }
76
+ export function validate(text) {
77
+ try {
78
+ parse(text);
79
+ return true;
80
+ }
81
+ catch {
82
+ return false;
83
+ }
84
+ }
85
+ function stripComment(line) {
86
+ let inString = false;
87
+ for (let i = 0; i < line.length; i++) {
88
+ const ch = line[i];
89
+ if (ch === '"') {
90
+ inString = !inString;
91
+ continue;
92
+ }
93
+ if (ch === "#" && !inString) {
94
+ return line.slice(0, i).trim();
95
+ }
96
+ }
97
+ return line.trim();
98
+ }
99
+ /**
100
+ * Write a World document for `world`, the inverse of `parse`.
101
+ *
102
+ * `parse(stringify(world))` deep-equals `world`, except that arrays of 0 or 1
103
+ * items come back the way `parse` reads them: a one-item array as that object,
104
+ * an empty array as an absent key. Anything else the format can't hold
105
+ * throws. Comments and layout are not kept; the output is normalized.
106
+ */
107
+ export function stringify(world) {
108
+ if (!isPlainObject(world)) {
109
+ throw new Error("Cannot stringify: the world must be a plain object");
110
+ }
111
+ const blocks = [];
112
+ writeNode([], world, blocks);
113
+ return blocks.length ? blocks.join("\n\n") + "\n" : "";
114
+ }
115
+ function writeNode(path, obj, blocks) {
116
+ const attrs = [];
117
+ const children = [];
118
+ for (const [key, value] of Object.entries(obj)) {
119
+ if (isPlainObject(value)) {
120
+ children.push([key, value]);
121
+ }
122
+ else if (Array.isArray(value)) {
123
+ if (value.length > 0)
124
+ children.push([key, value]);
125
+ }
126
+ else {
127
+ if (path.length === 0) {
128
+ throw new Error(`Cannot stringify "${key}": an attribute needs a node; the root holds only nodes`);
129
+ }
130
+ checkAttributeKey(path, key);
131
+ attrs.push(`${key} = ${formatValue(path, key, value)}`);
132
+ }
133
+ }
134
+ if (path.length > 0 && (attrs.length > 0 || children.length === 0)) {
135
+ blocks.push([`[${path.join("/")}]`, ...attrs].join("\n"));
136
+ }
137
+ for (const [key, value] of children) {
138
+ const childPath = [...path, key];
139
+ checkNodeKey(childPath);
140
+ if (!Array.isArray(value)) {
141
+ writeNode(childPath, value, blocks);
142
+ }
143
+ else if (value.length === 1) {
144
+ writeNode(childPath, arrayItem(childPath, value[0]), blocks);
145
+ }
146
+ else {
147
+ for (const item of value) {
148
+ const node = arrayItem(childPath, item);
149
+ for (const [k, v] of Object.entries(node)) {
150
+ if (isPlainObject(v) || Array.isArray(v)) {
151
+ throw new Error(`Cannot stringify "${childPath.join("/")}/${k}": a repeated node can't have child nodes`);
152
+ }
153
+ }
154
+ writeNode(childPath, node, blocks);
155
+ }
156
+ }
157
+ }
158
+ }
159
+ function arrayItem(path, item) {
160
+ if (!isPlainObject(item)) {
161
+ throw new Error(`Cannot stringify "${path.join("/")}": array items must be plain objects`);
162
+ }
163
+ return item;
164
+ }
165
+ function formatValue(path, key, value) {
166
+ const where = `"${[...path, key].join("/")}"`;
167
+ if (typeof value === "string") {
168
+ if (value.includes('"')) {
169
+ throw new Error(`Cannot stringify ${where}: strings can't contain '"'`);
170
+ }
171
+ if (/[\r\n]/.test(value)) {
172
+ throw new Error(`Cannot stringify ${where}: strings can't contain line breaks`);
173
+ }
174
+ return `"${value}"`;
175
+ }
176
+ if (typeof value === "number") {
177
+ if (!Number.isFinite(value) || Object.is(value, -0)) {
178
+ const shown = Object.is(value, -0) ? "-0" : String(value);
179
+ throw new Error(`Cannot stringify ${where}: ${shown} isn't supported`);
180
+ }
181
+ return String(value);
182
+ }
183
+ if (typeof value === "boolean")
184
+ return String(value);
185
+ const kind = value === null ? "null" : typeof value === "object" ? "a non-plain object" : typeof value;
186
+ throw new Error(`Cannot stringify ${where}: ${kind} isn't a string, number or boolean`);
187
+ }
188
+ function checkNodeKey(path) {
189
+ const key = path[path.length - 1];
190
+ if (key === "" || /[/#"\r\n]/.test(key)) {
191
+ throw new Error(`Cannot stringify "${path.join("/")}": a node key must be non-empty and can't contain '/', '#', '"' or line breaks`);
192
+ }
193
+ }
194
+ function checkAttributeKey(path, key) {
195
+ if (key === "" ||
196
+ key !== key.trim() ||
197
+ key.startsWith("[") ||
198
+ /[=#"\r\n]/.test(key)) {
199
+ throw new Error(`Cannot stringify "${[...path, key].join("/")}": an attribute key must be non-empty, have no surrounding spaces, not start with '[', and can't contain '=', '#', '"' or line breaks`);
200
+ }
201
+ }
202
+ function isPlainObject(value) {
203
+ if (typeof value !== "object" || value === null)
204
+ return false;
205
+ const proto = Object.getPrototypeOf(value);
206
+ return proto === Object.prototype || proto === null;
207
+ }
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "worldformat",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.0",
4
+ "description": "Reference implementation of the World format (parser, stringifier and related utilities).",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "sideEffects": false,
18
+ "scripts": {
19
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
20
+ "check": "tsc --noEmit",
21
+ "test": "tsx tests/parse.test.ts && tsx tests/stringify.test.ts",
22
+ "prepack": "pnpm build"
23
+ },
24
+ "keywords": [
25
+ "worldformat",
26
+ "parser",
27
+ "stringify"
28
+ ],
29
+ "author": "L. C. Maren",
30
+ "license": "MIT",
31
+ "packageManager": "pnpm@10.27.0",
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/lcmaren/worldformat.git"
35
+ },
36
+ "homepage": "https://github.com/lcmaren/worldformat#readme",
37
+ "bugs": {
38
+ "url": "https://github.com/lcmaren/worldformat/issues"
39
+ },
40
+ "devDependencies": {
41
+ "@types/node": "^25.0.3",
42
+ "tsx": "^4.21.0",
43
+ "typescript": "^5.9.3"
44
+ }
45
+ }