worldformat 0.2.0 → 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/README.md CHANGED
@@ -32,7 +32,7 @@ npm install worldformat
32
32
  ```
33
33
 
34
34
  ```ts
35
- import { parse, validate } from "worldformat";
35
+ import { parse, stringify, validate } from "worldformat";
36
36
 
37
37
  const world = parse(`
38
38
  [task]
@@ -46,6 +46,28 @@ validate("name = 1"); // → false: an attribute needs a node above it
46
46
 
47
47
  `parse` throws on an invalid document; `validate` returns `false` instead.
48
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
+
49
71
  The package is ESM only.
50
72
 
51
73
  ## Scope
package/dist/index.d.ts CHANGED
@@ -1,4 +1,13 @@
1
1
  type AnyObj = Record<string, any>;
2
2
  export declare function parse(text: string): AnyObj;
3
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;
4
13
  export {};
package/dist/index.js CHANGED
@@ -96,3 +96,112 @@ function stripComment(line) {
96
96
  }
97
97
  return line.trim();
98
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,7 +1,7 @@
1
1
  {
2
2
  "name": "worldformat",
3
- "version": "0.2.0",
4
- "description": "Reference implementation of the World format (parser and related utilities).",
3
+ "version": "0.3.0",
4
+ "description": "Reference implementation of the World format (parser, stringifier and related utilities).",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
@@ -18,12 +18,13 @@
18
18
  "scripts": {
19
19
  "build": "rm -rf dist && tsc -p tsconfig.build.json",
20
20
  "check": "tsc --noEmit",
21
- "test": "tsx tests/parse.test.ts",
21
+ "test": "tsx tests/parse.test.ts && tsx tests/stringify.test.ts",
22
22
  "prepack": "pnpm build"
23
23
  },
24
24
  "keywords": [
25
25
  "worldformat",
26
- "parser"
26
+ "parser",
27
+ "stringify"
27
28
  ],
28
29
  "author": "L. C. Maren",
29
30
  "license": "MIT",