@thi.ng/proctext 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/CHANGELOG.md ADDED
@@ -0,0 +1,17 @@
1
+ # Change Log
2
+
3
+ - **Last updated**: 2024-07-19T14:56:21Z
4
+ - **Generator**: [thi.ng/monopub](https://thi.ng/monopub)
5
+
6
+ All notable changes to this project will be documented in this file.
7
+ See [Conventional Commits](https://conventionalcommits.org/) for commit guidelines.
8
+
9
+ **Note:** Unlisted _patch_ versions only involve non-code or otherwise excluded changes
10
+ and/or version bumps of transitive dependencies.
11
+
12
+ ## [0.1.0](https://github.com/thi-ng/umbrella/tree/@thi.ng/proctext@0.1.0) (2024-07-19)
13
+
14
+ #### 🚀 Features
15
+
16
+ - import as new pkg ([1f96e4d](https://github.com/thi-ng/umbrella/commit/1f96e4d))
17
+ - update grammar, case-sensitive var names ([059bffb](https://github.com/thi-ng/umbrella/commit/059bffb))
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,337 @@
1
+ <!-- This file is generated - DO NOT EDIT! -->
2
+ <!-- Please see: https://github.com/thi-ng/umbrella/blob/develop/CONTRIBUTING.md#changes-to-readme-files -->
3
+ # ![@thi.ng/proctext](https://media.thi.ng/umbrella/banners-20230807/thing-proctext.svg?de076745)
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@thi.ng/proctext.svg)](https://www.npmjs.com/package/@thi.ng/proctext)
6
+ ![npm downloads](https://img.shields.io/npm/dm/@thi.ng/proctext.svg)
7
+ [![Mastodon Follow](https://img.shields.io/mastodon/follow/109331703950160316?domain=https%3A%2F%2Fmastodon.thi.ng&style=social)](https://mastodon.thi.ng/@toxi)
8
+
9
+ > [!NOTE]
10
+ > This is one of 189 standalone projects, maintained as part
11
+ > of the [@thi.ng/umbrella](https://github.com/thi-ng/umbrella/) monorepo
12
+ > and anti-framework.
13
+ >
14
+ > 🚀 Please help me to work full-time on these projects by [sponsoring me on
15
+ > GitHub](https://github.com/sponsors/postspectacular). Thank you! ❤️
16
+
17
+ - [About](#about)
18
+ - [Features](#features)
19
+ - [Line comments](#line-comments)
20
+ - [Multi-value variables](#multi-value-variables)
21
+ - [Recursive variable expansion](#recursive-variable-expansion)
22
+ - [Variable assignments](#variable-assignments)
23
+ - [Hidden assignments](#hidden-assignments)
24
+ - [Dynamic, indirect variable references](#dynamic-indirect-variable-references)
25
+ - [Controlled randomness](#controlled-randomness)
26
+ - [Status](#status)
27
+ - [Installation](#installation)
28
+ - [Dependencies](#dependencies)
29
+ - [Usage examples](#usage-examples)
30
+ - [API](#api)
31
+ - [Authors](#authors)
32
+ - [License](#license)
33
+
34
+ ## About
35
+
36
+ Extensible procedural text generation engine with dynamic, mutable state, indirection, randomizable & recursive variable expansions.
37
+
38
+ ## Features
39
+
40
+ The generator works with a simple plain text format, supporting the following
41
+ features:
42
+
43
+ ### Line comments
44
+
45
+ Lines starting with `#` are comments and completely ignored, and invisible in
46
+ the output. No block comments are available.
47
+
48
+ ### Multi-value variables
49
+
50
+ Text generation and expansion relies on variables, which are defined inline
51
+ (inside the text given to the generator). New variables can be defined as
52
+ follows and each variable can define one or more possible values (one value per
53
+ line!):
54
+
55
+ ```text
56
+ [name]
57
+ alice
58
+ bob
59
+ ciara
60
+ ```
61
+
62
+ If more than a single value is given, a [semi-random
63
+ choice](#controlled-randomness) will be made for each instance/occurrence of the
64
+ var...
65
+
66
+ Variables are case-sensitive (i.e. `NAME` is a different var than `name`) and
67
+ can also be re-defined overridden in different parts of the document.
68
+
69
+ Variables are referenced via: `<name>`:
70
+
71
+ ```ts tangle:export/readme-intro.ts
72
+ import { generate } from "@thi.ng/proctext";
73
+
74
+ const { result } = await generate(`
75
+ [name]
76
+ alice
77
+ bob
78
+
79
+ [action]
80
+ walked
81
+ cycled
82
+ ran
83
+ swam
84
+
85
+ [place]
86
+ office
87
+ shop
88
+ cafe
89
+ lake
90
+
91
+ [time]
92
+ this morning
93
+ last night
94
+ a week ago
95
+
96
+ # The actual generated text...
97
+ <time> <name> <action> to the <place>.
98
+ `);
99
+
100
+ console.log(result);
101
+
102
+ // last night alice cycled to the cafe.
103
+ ```
104
+
105
+ ### Recursive variable expansion
106
+
107
+ Variable values can contain cyclic references and/or references to other
108
+ variables.
109
+
110
+ > [!IMPORTANT]
111
+ > In the case of cyclic refs, you MUST provide at least one non-cyclic option
112
+ > to avoid infinite recursion!
113
+
114
+ ```ts tangle:export/readme-var-recursion.ts
115
+ import { generate } from "@thi.ng/proctext";
116
+
117
+ const { result } = await generate(`
118
+ [activity]
119
+ walking and <activity_alt>
120
+ hiking and <activity_alt>
121
+ # the next option is cyclic...
122
+ cycling, <activity>
123
+
124
+ [activity_alt]
125
+ sleeping
126
+ coding
127
+
128
+ I enjoy <activity>.
129
+ `);
130
+
131
+ console.log(result);
132
+
133
+ // I enjoy cycling, walking and coding.
134
+ ```
135
+
136
+ ### Variable assignments
137
+
138
+ New variables can be declared & initialized via `<varname=existing>`. This will
139
+ create a new variable `varname` with a choice value of variable `existing`
140
+ (which must already be defined).
141
+
142
+ ```ts tangle:export/readme-var-assign.ts
143
+ import { generate } from "@thi.ng/proctext";
144
+
145
+ const { result } = await generate(`
146
+ [name]
147
+ Alice
148
+ Bob
149
+ Charlie
150
+ Dora
151
+
152
+ Let's pick some random names: <hero1=name> and <hero2=name>.
153
+
154
+ But now we can use them as constants:
155
+ <hero1>, <hero1>, <hero1> & <hero2>, <hero2>, <hero2>
156
+ `);
157
+
158
+ console.log(result);
159
+
160
+ // Let's pick some random names: Dora and Bob.
161
+ //
162
+ // But now we can use them as constants:
163
+ // Dora, Dora, Dora & Bob, Bob, Bob
164
+ ```
165
+
166
+ ### Hidden assignments
167
+
168
+ Normally, variable assignments are also causing the chosen value to be emitted
169
+ as part of the generated text. Sometimes it is useful to _not_ do so and
170
+ emission can be surpressed/hidden by using the prefix `!` as part of the
171
+ assignment, like so:
172
+
173
+ ```ts tangle:export/readme-hidden-var.ts
174
+ import { generate } from "@thi.ng/proctext";
175
+
176
+ const { result } = await generate(`
177
+ [name]
178
+ Asterix
179
+ Obelix
180
+
181
+ # hidden assignment
182
+ <!hero=name>
183
+ My name is <hero>.`);
184
+
185
+ console.log(result);
186
+
187
+ // My name is Asterix.
188
+ ```
189
+
190
+ ### Dynamic, indirect variable references
191
+
192
+ Given a variable assignment like `<hero=name>`, we can use dots in the name to
193
+ lookup derived variables with their name based on current value(s).
194
+
195
+ For the following example:
196
+
197
+ - assume the assignment of `<hero=name>` picked value `a`
198
+ - now the var lookup `<hero.job>` will look for a var called `a.job`
199
+ - there's only one option for `a.job`, i.e. `astronaut`
200
+ - the lookup `hero.job.desc` will then look for `astronaut.desc`
201
+
202
+ ```ts tangle:export/readme-indirect.ts
203
+ import { generate } from "@thi.ng/proctext";
204
+
205
+ const { result } = await generate(`
206
+ [name]
207
+ A
208
+ B
209
+
210
+ [A.job]
211
+ astronaut
212
+
213
+ [B.job]
214
+ baker
215
+
216
+ [astronaut.desc]
217
+ shooting for the stars
218
+ flying to the moon
219
+
220
+ [baker.desc]
221
+ baking bread
222
+
223
+ <hero=name> is a <hero.job>, <hero.job.desc>.`);
224
+
225
+ console.log(result);
226
+
227
+ ```
228
+
229
+ ### Controlled randomness
230
+
231
+ The selection of variable choices is determined by the configured [PRNG
232
+ instance](https://thi.ng/random), the number of recent values selected/memorized
233
+ and the number of attempts made to pick a new unique choice. All of these can be
234
+ configured via options given to `generate()`:
235
+
236
+ ```ts
237
+ import { generate } from "@thi.ng/proctext";
238
+ import { SYSTEM } from "@thi.ng/random";
239
+
240
+ // here we show default options used
241
+ generate(`...`, {
242
+ rnd: SYSTEM,
243
+ maxHist: 1,
244
+ maxTrials: 10
245
+ });
246
+ ```
247
+
248
+ The `maxHist = 1` means that for each variable only the last value picked will
249
+ be memorized. If more than 1 value options exists for a variable, successive var
250
+ expansions will not result in duplicates, e.g.
251
+
252
+ ```text
253
+ [name]
254
+ a
255
+ b
256
+
257
+ <name> <name> <name>
258
+ ```
259
+
260
+ ...will only ever result in one of these two sequences: `a b a` or `b a b`.
261
+
262
+ ## Status
263
+
264
+ **ALPHA** - bleeding edge / work-in-progress
265
+
266
+ [Search or submit any issues for this package](https://github.com/thi-ng/umbrella/issues?q=%5Bproctext%5D+in%3Atitle)
267
+
268
+ ## Installation
269
+
270
+ ```bash
271
+ yarn add @thi.ng/proctext
272
+ ```
273
+
274
+ ESM import:
275
+
276
+ ```ts
277
+ import * as pro from "@thi.ng/proctext";
278
+ ```
279
+
280
+ Browser ESM import:
281
+
282
+ ```html
283
+ <script type="module" src="https://esm.run/@thi.ng/proctext"></script>
284
+ ```
285
+
286
+ [JSDelivr documentation](https://www.jsdelivr.com/)
287
+
288
+ For Node.js REPL:
289
+
290
+ ```js
291
+ const pro = await import("@thi.ng/proctext");
292
+ ```
293
+
294
+ Package sizes (brotli'd, pre-treeshake): ESM: 1.14 KB
295
+
296
+ ## Dependencies
297
+
298
+ - [@thi.ng/api](https://github.com/thi-ng/umbrella/tree/develop/packages/api)
299
+ - [@thi.ng/arrays](https://github.com/thi-ng/umbrella/tree/develop/packages/arrays)
300
+ - [@thi.ng/associative](https://github.com/thi-ng/umbrella/tree/develop/packages/associative)
301
+ - [@thi.ng/defmulti](https://github.com/thi-ng/umbrella/tree/develop/packages/defmulti)
302
+ - [@thi.ng/parse](https://github.com/thi-ng/umbrella/tree/develop/packages/parse)
303
+ - [@thi.ng/random](https://github.com/thi-ng/umbrella/tree/develop/packages/random)
304
+ - [@thi.ng/strings](https://github.com/thi-ng/umbrella/tree/develop/packages/strings)
305
+
306
+ ## Usage examples
307
+
308
+ One project in this repo's
309
+ [/examples](https://github.com/thi-ng/umbrella/tree/develop/examples)
310
+ directory is using this package:
311
+
312
+ | Screenshot | Description | Live demo | Source |
313
+ |:-----------------------------------------------------------------------------------------------------------------------|:-----------------------------------------------------------------------------------------|:------------------------------------------------------|:-----------------------------------------------------------------------------------|
314
+ | <img src="https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/examples/procedural-text.jpg" width="240"/> | Procedural stochastic text generation via custom DSL, parse grammar & AST transformation | [Demo](https://demo.thi.ng/umbrella/procedural-text/) | [Source](https://github.com/thi-ng/umbrella/tree/develop/examples/procedural-text) |
315
+
316
+ ## API
317
+
318
+ [Generated API docs](https://docs.thi.ng/umbrella/proctext/)
319
+
320
+ ## Authors
321
+
322
+ - [Karsten Schmidt](https://thi.ng)
323
+
324
+ If this project contributes to an academic publication, please cite it as:
325
+
326
+ ```bibtex
327
+ @misc{thing-proctext,
328
+ title = "@thi.ng/proctext",
329
+ author = "Karsten Schmidt",
330
+ note = "https://thi.ng/proctext",
331
+ year = 2023
332
+ }
333
+ ```
334
+
335
+ ## License
336
+
337
+ &copy; 2023 - 2024 Karsten Schmidt // Apache License 2.0
package/api.d.ts ADDED
@@ -0,0 +1,36 @@
1
+ import type { Fn, MaybePromise } from "@thi.ng/api";
2
+ import type { IRandom } from "@thi.ng/random";
3
+ export interface Var {
4
+ opts: string[];
5
+ history: string[];
6
+ }
7
+ export interface GeneratorContext {
8
+ /**
9
+ * Object of variables and their possible expansions (value options).
10
+ */
11
+ vars: Record<string, Var>;
12
+ /**
13
+ * Object of modifier functions to transform.
14
+ */
15
+ mods: Record<string, Fn<string, MaybePromise<string>>>;
16
+ /**
17
+ * PRNG to use for selection variable options (see {@link Var.opts}).
18
+ */
19
+ rnd: IRandom;
20
+ /**
21
+ * Max number of choices to record per variable. When picking a possible
22
+ * value for resolving a variable, the generator attempts to pick values
23
+ * which are different than the last N choices.
24
+ *
25
+ * @defaultValue 1
26
+ */
27
+ maxHist: number;
28
+ /**
29
+ * Max attempts to find a new unique choice for variable
30
+ * expansions/resolution
31
+ *
32
+ * @defaultValue 10
33
+ */
34
+ maxTrials: number;
35
+ }
36
+ //# sourceMappingURL=api.d.ts.map
package/api.js ADDED
File without changes
package/generate.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ import type { GeneratorContext } from "./api.js";
2
+ /**
3
+ * Default variable modifiers (capitalize, uppercase, lowercase)
4
+ */
5
+ export declare const DEFAULT_MODIFIERS: GeneratorContext["mods"];
6
+ /**
7
+ * Parser grammar rules for the custom text/DSL format used for this text
8
+ * generator. These rules were created with & exported from this playground URL:
9
+ *
10
+ * Source:
11
+ * https://demo.thi.ng/umbrella/parse-playground/#l9oCWyMgbWFpbiBwYXJzZXIgcnVsZQptYWluOiA8U1RBUlQ-ICggPGRlZj4gfCA8Y29tbWVudD4gfCA8YmluZGluZz4gfCA8d29yZD4gKSogPEVORD4gPT4gaG9pc3QgOwoKIyB2YXJpYWJsZSBkZWZpbml0aW9uCmRlZjogPFdTMD4gPExTVEFSVD4gJ1snISA8aWQ-ICddJyEgPEROTD4gKDxjb21tZW50PiB8IDx2YWx1ZT4pKyA8RE5MPiA7CmlkOiAoIDxBTFBIQV9OVU0-IHwgWy5cdTAwMmRdICkrID0-IGpvaW4gOwp2YWx1ZTogLig_KzxETkw-KSA9PiBqb2luIDsKCiMgdmFyaWFibGUgYmluZGluZ3MKYmluZGluZzogJzwnISAoPHNldHZhcj4gfCA8dmFyPikgJz4nISA9PiBob2lzdCA7CnZhcjogPGlkPiA8bW9kaWZpZXI-PyA7Cm1vZGlmaWVyOiA8bW9kaWQ-KyA7Cm1vZGlkOiAnOychIDxBTFBIQV9OVU0-KyA9PiBqb2luIDsKc2V0dmFyOiAnISc_IDxpZD4gJz0nISA8dmFyPiA7CgojIGxpbmUgY29tbWVudApjb21tZW50OiA8TFNUQVJUPiAnIycgLig_KzxETkw-KSA9PiBkaXNjYXJkIDsKCiMgdmVyYmF0aW0gdGV4dAp3b3JkOiAoIDxBTFBIQV9OVU0-IHwgWyA_IS4sJyJAIyQlJigpe307Oi8qPStcdTAwMmRcdTAwNWJcdTAwNWRcdTAwMGFdICkrID0-IGpvaW4gO6RtYWlu2gETW25hbWVdCkFsaWNlCiMgY29tbWVudCBpbnNpZGUgbGlzdApCb2IKCltwbGFjZV0KdG93bgp0aGUgd29vZHMKCiMgQ29tbWVudCBsaW5lClthY3Rpdml0eV0KY3ljbGluZyBhbmQgPGFjdC5hbHQ-Cmhpa2luZwoKT25jZSB1cG9uIGEgdGltZSwgPGhlcm8xPW5hbWU-IGFuZCA8aGVybzI9bmFtZT4gd2VudCB0byA8cGxhY2U-LiA8aGVybzE-IHRoZW4gZGlkIHNvbWUgPGFjdGl2aXR5PiwgYnV0IDxoZXJvMj4gY2hvc2UgdG8gZG8gPGFjdGl2aXR5O3VjPiBpbnN0ZWFkLgoKVGhlIGVuZC6goKCg
12
+ */
13
+ export declare const GRAMMAR: import("@thi.ng/parse").Language | undefined;
14
+ /**
15
+ * Main text generation function. First parses input string, then (if there were
16
+ * no parse errors) traverses the document AST and generates text according to
17
+ * the rules and provided options (e.g. predefined vars, modifiers etc). Returns
18
+ * promise to an object with resulting text and processing status/error.
19
+ *
20
+ * @remarks
21
+ * If the generation was successful, the result object will also contain the
22
+ * update {@link GeneratorContext}, which can then be re-used for future
23
+ * invocations (i.e. to retain state between multiple generations).
24
+ *
25
+ * @param src
26
+ * @param ctx
27
+ */
28
+ export declare const generate: (src: string, ctx?: Partial<GeneratorContext>) => Promise<{
29
+ type: string;
30
+ result: string;
31
+ ctx: GeneratorContext;
32
+ err?: undefined;
33
+ } | {
34
+ type: string;
35
+ err: Error;
36
+ result?: undefined;
37
+ ctx?: undefined;
38
+ }>;
39
+ //# sourceMappingURL=generate.d.ts.map
package/generate.js ADDED
@@ -0,0 +1,145 @@
1
+ import { peek } from "@thi.ng/arrays/peek";
2
+ import { mergeDeepObj } from "@thi.ng/associative/merge-deep";
3
+ import { DEFAULT, defmulti } from "@thi.ng/defmulti/defmulti";
4
+ import { defContext } from "@thi.ng/parse/context";
5
+ import { defGrammar } from "@thi.ng/parse/grammar";
6
+ import { SYSTEM } from "@thi.ng/random/system";
7
+ import { pickRandomUnique } from "@thi.ng/random/unique-indices";
8
+ import { capitalize, lower, upper } from "@thi.ng/strings/case";
9
+ const DEFAULT_MODIFIERS = {
10
+ cap: capitalize,
11
+ uc: upper,
12
+ lc: lower
13
+ };
14
+ const GRAMMAR = defGrammar(`
15
+ # main parser rule
16
+ main: <START> ( <def> | <comment> | <binding> | <word> )* <END> => hoist ;
17
+
18
+ # variable definition
19
+ def: <WS0> <LSTART> '['! <id> ']'! <DNL> (<comment> | <value>)+ <DNL> ;
20
+ id: ( <ALPHA_NUM> | [.\\u002d] )+ => join ;
21
+ value: .(?+<DNL>) => join ;
22
+
23
+ # variable bindings
24
+ binding: '<'! (<setvar> | <var>) '>'! => hoist ;
25
+ var: <id> <modifier>? ;
26
+ modifier: <modid>+ ;
27
+ modid: ';'! <ALPHA_NUM>+ => join ;
28
+ setvar: '!'? <id> '='! <var> ;
29
+
30
+ # line comment
31
+ comment: <LSTART> '#' .(?+<DNL>) => discard ;
32
+
33
+ # verbatim text
34
+ word: ( <ALPHA_NUM> | [ ?!.,'"@#$%&(){};:/*=+\\u002d\\u005b\\u005d\\u000a] )+ => join ;
35
+ `);
36
+ const __parse = (src, opts) => {
37
+ const ctx = defContext(src, opts);
38
+ return { result: GRAMMAR.rules.main(ctx), ctx };
39
+ };
40
+ const generate = async (src, ctx) => {
41
+ try {
42
+ const { result, ctx: parseCtx } = __parse(src.trim());
43
+ if (result) {
44
+ const $ctx = mergeDeepObj(
45
+ {
46
+ vars: {},
47
+ mods: DEFAULT_MODIFIERS,
48
+ rnd: SYSTEM,
49
+ maxTrials: 10
50
+ },
51
+ ctx
52
+ );
53
+ const acc = [];
54
+ await __transformScope(parseCtx.root, $ctx, acc);
55
+ return {
56
+ type: parseCtx.done ? "success" : "partial",
57
+ result: acc.join(""),
58
+ ctx: $ctx
59
+ };
60
+ } else {
61
+ return { type: "error", err: new Error(`parse error`) };
62
+ }
63
+ } catch (e) {
64
+ return { type: "error", err: e };
65
+ }
66
+ };
67
+ const __transformScope = defmulti(
68
+ (x) => x.id,
69
+ {},
70
+ {
71
+ // fallback handler for unknown tree nodes (usually a grammar error)
72
+ [DEFAULT]: async (scope) => {
73
+ throw new Error(`missing impl for scope ID: ${scope.id}`);
74
+ },
75
+ // handler for processing the root node (just traverses children)
76
+ root: async ({ children }, ctx, acc) => {
77
+ if (!children) return;
78
+ for (let x of children[0].children)
79
+ await __transformScope(x, ctx, acc);
80
+ },
81
+ // handler for a new variable definition and its possible values
82
+ def: async ({ children }, ctx) => {
83
+ ctx.vars[children[0].result] = {
84
+ opts: children[1].children.map((x) => x.result),
85
+ history: []
86
+ };
87
+ },
88
+ // handler for variable lookups
89
+ var: async (scope, ctx, acc) => {
90
+ acc.push(await __expandVar(scope, ctx));
91
+ },
92
+ // handler for variable assignments
93
+ setvar: async ({ children }, ctx, acc) => {
94
+ const choice = await __expandVar(children[2], ctx);
95
+ ctx.vars[children[1].result] = {
96
+ opts: [choice],
97
+ history: [choice]
98
+ };
99
+ if (!children[0].result) acc.push(choice);
100
+ },
101
+ // handler for verbatim text
102
+ word: async ({ result }, _, acc) => {
103
+ acc.push(result);
104
+ }
105
+ }
106
+ );
107
+ const __resolveVarName = (name, ctx) => {
108
+ if (name.indexOf(".") == -1) return name;
109
+ let resolved = "";
110
+ for (let x of name.split(".")) {
111
+ const $name = resolved + "." + x;
112
+ const $var = resolved ? ctx.vars[$name] : ctx.vars[x];
113
+ if ($var)
114
+ resolved = ($var.history.length ? peek($var.history) : "") || $name;
115
+ }
116
+ return resolved;
117
+ };
118
+ const __expandVar = async ({ children }, ctx) => {
119
+ const id = __resolveVarName(children[0].result, ctx);
120
+ const $var = ctx.vars[id];
121
+ if (!$var) throw new Error(`unknown variable: ${id}`);
122
+ pickRandomUnique(1, $var.opts, $var.history, ctx.maxTrials, ctx.rnd);
123
+ if ($var.history.length > ctx.maxHist) $var.history.shift();
124
+ const choice = peek($var.history);
125
+ const result = await generate(choice, ctx);
126
+ if (result.err) {
127
+ throw new Error(
128
+ result.err.message.includes("recursion") ? `error expanding variable: ${id} (cycle detected)` : result.err.message
129
+ );
130
+ }
131
+ let value = result.result;
132
+ if (children[1].children) {
133
+ for (let mod of children[1].children) {
134
+ const modFn = ctx.mods[mod.result];
135
+ if (modFn) value = await modFn(value);
136
+ else throw new Error(`unknown modifier: ${mod.result}`);
137
+ }
138
+ }
139
+ return value;
140
+ };
141
+ export {
142
+ DEFAULT_MODIFIERS,
143
+ GRAMMAR,
144
+ generate
145
+ };
package/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./api.js";
2
+ export * from "./generate.js";
3
+ //# sourceMappingURL=index.d.ts.map
package/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./api.js";
2
+ export * from "./generate.js";
package/package.json ADDED
@@ -0,0 +1,86 @@
1
+ {
2
+ "name": "@thi.ng/proctext",
3
+ "version": "0.1.0",
4
+ "description": "Extensible procedural text generation engine with dynamic, mutable state, indirection, randomizable & recursive variable expansions",
5
+ "type": "module",
6
+ "module": "./index.js",
7
+ "typings": "./index.d.ts",
8
+ "sideEffects": false,
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "https://github.com/thi-ng/umbrella.git"
12
+ },
13
+ "homepage": "https://thi.ng/proctext",
14
+ "funding": [
15
+ {
16
+ "type": "github",
17
+ "url": "https://github.com/sponsors/postspectacular"
18
+ },
19
+ {
20
+ "type": "patreon",
21
+ "url": "https://patreon.com/thing_umbrella"
22
+ }
23
+ ],
24
+ "author": "Karsten Schmidt (https://thi.ng)",
25
+ "license": "Apache-2.0",
26
+ "scripts": {
27
+ "build": "yarn build:esbuild && yarn build:decl",
28
+ "build:decl": "tsc --declaration --emitDeclarationOnly",
29
+ "build:esbuild": "esbuild --format=esm --platform=neutral --target=es2022 --tsconfig=tsconfig.json --outdir=. src/**/*.ts",
30
+ "clean": "rimraf --glob '*.js' '*.d.ts' '*.map' doc",
31
+ "doc": "typedoc --excludePrivate --excludeInternal --out doc src/index.ts",
32
+ "doc:ae": "mkdir -p .ae/doc .ae/temp && api-extractor run --local --verbose",
33
+ "doc:readme": "bun ../../tools/src/module-stats.ts && bun ../../tools/src/readme.ts",
34
+ "pub": "yarn npm publish --access public",
35
+ "test": "bun test",
36
+ "tool:tangle": "../../node_modules/.bin/tangle src/**/*.ts"
37
+ },
38
+ "dependencies": {
39
+ "@thi.ng/api": "^8.11.6",
40
+ "@thi.ng/arrays": "^2.9.11",
41
+ "@thi.ng/associative": "^6.3.65",
42
+ "@thi.ng/defmulti": "^3.0.44",
43
+ "@thi.ng/parse": "^2.4.47",
44
+ "@thi.ng/random": "^3.8.5",
45
+ "@thi.ng/strings": "^3.8.0"
46
+ },
47
+ "devDependencies": {
48
+ "@microsoft/api-extractor": "^7.47.0",
49
+ "esbuild": "^0.23.0",
50
+ "typedoc": "^0.26.3",
51
+ "typescript": "^5.5.3"
52
+ },
53
+ "keywords": [
54
+ "typescript"
55
+ ],
56
+ "publishConfig": {
57
+ "access": "public"
58
+ },
59
+ "browser": {
60
+ "process": false,
61
+ "setTimeout": false
62
+ },
63
+ "engines": {
64
+ "node": ">=18"
65
+ },
66
+ "files": [
67
+ "./*.js",
68
+ "./*.d.ts"
69
+ ],
70
+ "exports": {
71
+ ".": {
72
+ "default": "./index.js"
73
+ },
74
+ "./api": {
75
+ "default": "./api.js"
76
+ },
77
+ "./generate": {
78
+ "default": "./generate.js"
79
+ }
80
+ },
81
+ "thi.ng": {
82
+ "status": "alpha",
83
+ "year": 2023
84
+ },
85
+ "gitHead": "c7aaa453b01a45e5235517db9d2a283b97abac96\n"
86
+ }