cortico-world-fun 0.2.1 → 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.
@@ -0,0 +1,428 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { areasNow, phaseAt } from './phases.js';
3
+ import { hoursState } from './venues.js';
4
+
5
+ const MAX_RAW_BYTES = 32 * 1024;
6
+ const ID_RE = /^[a-z0-9_-]{1,24}$/;
7
+ const PLACE_ID_RE = /^[a-z0-9_-]{1,40}$/;
8
+ const TIME_RE = /^(?:[01]\d|2[0-3]):[0-5]\d$/;
9
+ const UNSAFE_TEXT_RE = /(?:https?:\/\/|ftp:\/\/|file:\/\/|javascript:|data:|vbscript:|<|>|(?:^|\s)(?:\/|\\\\|\.\.?(?:\/|\\)|[A-Za-z]:[\\/])|(?:^|\s)[\w.-]+(?:[\\/][\w.-]+)+|(?:^|[^\w])(?:eval|Function|fetch|XMLHttpRequest|require|import)\s*\()/i;
10
+
11
+ function isRecord(value) {
12
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
13
+ const proto = Object.getPrototypeOf(value);
14
+ return proto === Object.prototype || proto === null;
15
+ }
16
+
17
+ function addUnknownKeys(value, allowed, path, errors) {
18
+ for (const key of Object.keys(value)) {
19
+ if (!allowed.has(key)) errors.push(`${path}.${key}: unsupported field`);
20
+ }
21
+ }
22
+
23
+ function textValue(value, path, max, errors, { required = true } = {}) {
24
+ if (value === undefined && !required) return undefined;
25
+ if (typeof value !== 'string') {
26
+ errors.push(`${path}: must be a string`);
27
+ return undefined;
28
+ }
29
+ const normalized = value.replace(/\r\n?/g, '\n').replace(/[\t\n ]+/g, ' ').trim();
30
+ if (required && !normalized) errors.push(`${path}: must not be empty`);
31
+ if (normalized.length > max) errors.push(`${path}: exceeds ${max} characters`);
32
+ if (UNSAFE_TEXT_RE.test(normalized)) errors.push(`${path}: executable or network/path content is not allowed`);
33
+ return normalized;
34
+ }
35
+
36
+ function validId(value, path, errors) {
37
+ if (typeof value !== 'string' || !ID_RE.test(value)) {
38
+ errors.push(`${path}: must match [a-z0-9_-]{1,24}`);
39
+ return undefined;
40
+ }
41
+ return value;
42
+ }
43
+
44
+ function canonicalRevision(content) {
45
+ return createHash('sha256').update(JSON.stringify(content), 'utf8').digest('hex').slice(0, 32);
46
+ }
47
+
48
+ function parseRaw(raw, errors) {
49
+ let value = raw;
50
+ if (typeof raw === 'string') {
51
+ if (Buffer.byteLength(raw, 'utf8') > MAX_RAW_BYTES) {
52
+ errors.push('root: JSON exceeds 32 KB');
53
+ return null;
54
+ }
55
+ try {
56
+ value = JSON.parse(raw);
57
+ } catch {
58
+ errors.push('root: invalid JSON');
59
+ return null;
60
+ }
61
+ } else {
62
+ try {
63
+ const encoded = JSON.stringify(raw);
64
+ if (typeof encoded !== 'string' || Buffer.byteLength(encoded, 'utf8') > MAX_RAW_BYTES) {
65
+ errors.push('root: JSON exceeds 32 KB or is not serializable');
66
+ return null;
67
+ }
68
+ } catch {
69
+ errors.push('root: value is not serializable JSON');
70
+ return null;
71
+ }
72
+ }
73
+ return value;
74
+ }
75
+
76
+ function normalizeWhen(raw, path, errors) {
77
+ if (raw === undefined) return undefined;
78
+ if (!isRecord(raw)) {
79
+ errors.push(`${path}: must be an object`);
80
+ return undefined;
81
+ }
82
+ addUnknownKeys(raw, new Set(['from', 'to', 'phases', 'minVisits']), path, errors);
83
+ const out = {};
84
+ if ((raw.from === undefined) !== (raw.to === undefined)) {
85
+ errors.push(`${path}: from and to must be supplied together`);
86
+ }
87
+ if (raw.from !== undefined) {
88
+ if (typeof raw.from !== 'string' || !TIME_RE.test(raw.from)) errors.push(`${path}.from: must be HH:MM`);
89
+ else out.from = raw.from;
90
+ }
91
+ if (raw.to !== undefined) {
92
+ if (typeof raw.to !== 'string' || !TIME_RE.test(raw.to)) errors.push(`${path}.to: must be HH:MM`);
93
+ else out.to = raw.to;
94
+ }
95
+ if (out.from !== undefined && out.to !== undefined && out.from === out.to) {
96
+ errors.push(`${path}: from and to must describe a non-empty time window`);
97
+ }
98
+ if (raw.phases !== undefined) {
99
+ if (!Array.isArray(raw.phases) || raw.phases.length > 16) {
100
+ errors.push(`${path}.phases: must be an array of at most 16 phase ids`);
101
+ } else {
102
+ const phases = [];
103
+ for (const [index, phase] of raw.phases.entries()) {
104
+ const id = validId(phase, `${path}.phases[${index}]`, errors);
105
+ if (id !== undefined) phases.push(id);
106
+ }
107
+ if (new Set(phases).size !== phases.length) errors.push(`${path}.phases: ids must be unique`);
108
+ out.phases = phases;
109
+ }
110
+ }
111
+ if (raw.minVisits !== undefined) {
112
+ if (!Number.isInteger(raw.minVisits) || raw.minVisits < 0 || raw.minVisits > 100000) {
113
+ errors.push(`${path}.minVisits: must be an integer from 0 to 100000`);
114
+ } else out.minVisits = raw.minVisits;
115
+ }
116
+ return out;
117
+ }
118
+
119
+ /** Validate and canonicalize an authored version-1 story pack. */
120
+ export function validateStoryPack(raw) {
121
+ const errors = [];
122
+ const value = parseRaw(raw, errors);
123
+ if (!isRecord(value)) {
124
+ if (value !== null) errors.push('root: must be an object');
125
+ return { ok: false, pack: null, errors };
126
+ }
127
+ addUnknownKeys(value, new Set(['version', 'id', 'title', 'description', 'placeId', 'start', 'nodes']), '$', errors);
128
+ if (value.version !== 1) errors.push('version: must equal 1');
129
+ const id = validId(value.id, 'id', errors);
130
+ let placeId;
131
+ if (typeof value.placeId !== 'string' || !PLACE_ID_RE.test(value.placeId)) {
132
+ errors.push('placeId: must match [a-z0-9_-]{1,40}');
133
+ } else placeId = value.placeId;
134
+ const start = validId(value.start, 'start', errors);
135
+ const title = textValue(value.title, 'title', 80, errors);
136
+ const description = textValue(value.description, 'description', 240, errors, { required: false });
137
+
138
+ const nodes = [];
139
+ const rawNodes = value.nodes;
140
+ if (!Array.isArray(rawNodes) || rawNodes.length < 1 || rawNodes.length > 16) {
141
+ errors.push('nodes: must contain 1 to 16 nodes');
142
+ } else {
143
+ for (const [index, rawNode] of rawNodes.entries()) {
144
+ const path = `nodes[${index}]`;
145
+ if (!isRecord(rawNode)) {
146
+ errors.push(`${path}: must be an object`);
147
+ continue;
148
+ }
149
+ addUnknownKeys(rawNode, new Set(['id', 'area', 'event', 'prompt', 'when', 'choices', 'next']), path, errors);
150
+ const nodeId = validId(rawNode.id, `${path}.id`, errors);
151
+ const area = textValue(rawNode.area, `${path}.area`, 80, errors);
152
+ const event = textValue(rawNode.event, `${path}.event`, 120, errors);
153
+ const prompt = textValue(rawNode.prompt, `${path}.prompt`, 160, errors, { required: false });
154
+ const when = normalizeWhen(rawNode.when, `${path}.when`, errors);
155
+ let next;
156
+ if (rawNode.next !== undefined) next = validId(rawNode.next, `${path}.next`, errors);
157
+
158
+ let choices;
159
+ if (rawNode.choices !== undefined) {
160
+ if (!Array.isArray(rawNode.choices) || rawNode.choices.length < 2 || rawNode.choices.length > 4) {
161
+ errors.push(`${path}.choices: must contain 2 to 4 options`);
162
+ } else {
163
+ choices = [];
164
+ for (const [choiceIndex, rawChoice] of rawNode.choices.entries()) {
165
+ const choicePath = `${path}.choices[${choiceIndex}]`;
166
+ if (!isRecord(rawChoice)) {
167
+ errors.push(`${choicePath}: must be an object`);
168
+ continue;
169
+ }
170
+ addUnknownKeys(rawChoice, new Set(['id', 'label', 'result', 'next']), choicePath, errors);
171
+ const choiceId = validId(rawChoice.id, `${choicePath}.id`, errors);
172
+ if (choiceId === 'skip') errors.push(`${choicePath}.id: skip is reserved`);
173
+ const label = textValue(rawChoice.label, `${choicePath}.label`, 160, errors);
174
+ const result = textValue(rawChoice.result, `${choicePath}.result`, 160, errors);
175
+ let choiceNext;
176
+ if (rawChoice.next !== undefined) choiceNext = validId(rawChoice.next, `${choicePath}.next`, errors);
177
+ choices.push({ id: choiceId, label, result, ...(choiceNext !== undefined ? { next: choiceNext } : {}) });
178
+ }
179
+ if (choices.length === rawNode.choices.length && new Set(choices.map((choice) => choice.id)).size !== choices.length) {
180
+ errors.push(`${path}.choices: ids must be unique`);
181
+ }
182
+ }
183
+ if (rawNode.next !== undefined) errors.push(`${path}: use either choices or next, not both`);
184
+ }
185
+ nodes.push({
186
+ id: nodeId,
187
+ area,
188
+ event,
189
+ ...(prompt !== undefined ? { prompt } : {}),
190
+ ...(when !== undefined ? { when } : {}),
191
+ ...(choices !== undefined ? { choices } : {}),
192
+ ...(next !== undefined ? { next } : {}),
193
+ });
194
+ }
195
+ }
196
+
197
+ if (nodes.length === rawNodes?.length) {
198
+ const ids = nodes.map((node) => node.id);
199
+ if (new Set(ids).size !== ids.length) errors.push('nodes: ids must be unique');
200
+ const nodeIds = new Set(ids);
201
+ if (start !== undefined && !nodeIds.has(start)) errors.push('start: node does not exist');
202
+ const choiceIds = new Set();
203
+ for (const node of nodes) {
204
+ if (node.choices) {
205
+ for (const choice of node.choices) {
206
+ if (choice.id !== undefined) choiceIds.add(choice.id);
207
+ if (choice.next !== undefined && !nodeIds.has(choice.next)) errors.push(`nodes.${node.id}.choices.${choice.id}: next node does not exist`);
208
+ }
209
+ }
210
+ if (node.next !== undefined && !nodeIds.has(node.next)) errors.push(`nodes.${node.id}.next: node does not exist`);
211
+ }
212
+ if (choiceIds.size < nodes.flatMap((node) => node.choices ?? []).length) errors.push('choices: ids must be unique within a pack');
213
+
214
+ if (start !== undefined && nodeIds.has(start)) {
215
+ const byId = new Map(nodes.map((node) => [node.id, node]));
216
+ const reached = new Set();
217
+ const visiting = new Set();
218
+ const visited = new Set();
219
+ let cycle = false;
220
+ const visit = (nodeId) => {
221
+ if (visiting.has(nodeId)) { cycle = true; return; }
222
+ if (visited.has(nodeId)) return;
223
+ const node = byId.get(nodeId);
224
+ if (!node) return;
225
+ visiting.add(nodeId);
226
+ reached.add(nodeId);
227
+ const edges = node.choices ? node.choices.map((choice) => choice.next).filter(Boolean) : (node.next ? [node.next] : []);
228
+ for (const target of edges) visit(target);
229
+ visiting.delete(nodeId);
230
+ visited.add(nodeId);
231
+ };
232
+ visit(start);
233
+ if (cycle) errors.push('nodes: graph must not contain cycles');
234
+ if (reached.size !== nodes.length) errors.push('nodes: every node must be reachable from start');
235
+ const hasTerminal = nodes.some((node) => reached.has(node.id) && (
236
+ node.choices ? node.choices.some((choice) => !choice.next) : !node.next
237
+ ));
238
+ if (!hasTerminal) errors.push('nodes: graph must have a terminal path');
239
+ }
240
+ }
241
+
242
+ if (errors.length) return { ok: false, pack: null, errors };
243
+ const content = {
244
+ version: 1,
245
+ id,
246
+ title,
247
+ ...(description !== undefined ? { description } : {}),
248
+ placeId,
249
+ start,
250
+ nodes,
251
+ };
252
+ const pack = { ...content, revision: canonicalRevision(content) };
253
+ return { ok: true, pack, errors: [] };
254
+ }
255
+
256
+ /** Check whether a structurally valid pack can be used with a venue catalog. */
257
+ export function storyAvailability(pack, venues) {
258
+ const warnings = [];
259
+ const venueList = Array.isArray(venues) ? venues : (venues ? [venues] : []);
260
+ const venue = venueList.find((item) => item?.id === pack?.placeId);
261
+ const placeName = typeof venue?.name === 'string' ? venue.name : (pack?.placeId ?? '');
262
+ if (!venue) {
263
+ warnings.push(`Place “${pack?.placeId ?? ''}” is not available.`);
264
+ return { available: false, placeName, warnings };
265
+ }
266
+ const venueAreas = new Set(Array.isArray(venue.areas) ? venue.areas : []);
267
+ const missingAreas = [...new Set((Array.isArray(pack.nodes) ? pack.nodes : []).map((node) => node?.area).filter((area) => typeof area === 'string' && !venueAreas.has(area)))];
268
+ if (missingAreas.length) warnings.push(`Missing areas: ${missingAreas.join(', ')}.`);
269
+ const phases = new Set(Array.isArray(venue.phases) ? venue.phases.map((phase) => phase?.key).filter((key) => typeof key === 'string') : []);
270
+ const referencedPhases = [...new Set((Array.isArray(pack.nodes) ? pack.nodes : []).flatMap((node) => node?.when?.phases ?? []))];
271
+ const missingPhases = referencedPhases.filter((key) => !phases.has(key));
272
+ if (missingPhases.length) warnings.push(`Unsupported phases: ${missingPhases.join(', ')}.`);
273
+ return { available: warnings.length === 0, placeName, warnings };
274
+ }
275
+
276
+ function progressId(value) {
277
+ return typeof value === 'string' && ID_RE.test(value) ? value : null;
278
+ }
279
+
280
+ /** Keep only the small JSON-safe cursor snapshots needed to resume a story. */
281
+ export function normalizeStoryProgress(raw) {
282
+ if (!Array.isArray(raw)) return [];
283
+ const out = [];
284
+ for (const item of raw) {
285
+ if (out.length >= 32) break;
286
+ if (!isRecord(item)) continue;
287
+ const packId = progressId(item.packId);
288
+ const nodeId = progressId(item.nodeId);
289
+ const revision = typeof item.revision === 'string' && item.revision.length > 0 && item.revision.length <= 100 && /^[A-Za-z0-9_-]+$/.test(item.revision)
290
+ ? item.revision : null;
291
+ if (!packId || !nodeId || !revision || typeof item.done !== 'boolean') continue;
292
+ const waitingChoiceId = item.waitingChoiceId === null || item.waitingChoiceId === undefined
293
+ ? null
294
+ : (typeof item.waitingChoiceId === 'string' && /^[A-Za-z0-9:_-]{1,100}$/.test(item.waitingChoiceId) ? item.waitingChoiceId : null);
295
+ if (item.waitingChoiceId != null && waitingChoiceId === null) continue;
296
+ if (!Array.isArray(item.options) || item.options.length > 4) continue;
297
+ const options = [];
298
+ let invalidOptions = false;
299
+ for (const option of item.options) {
300
+ if (!isRecord(option) || !progressId(option.id)) { invalidOptions = true; break; }
301
+ if (option.next !== null && option.next !== undefined && !progressId(option.next)) { invalidOptions = true; break; }
302
+ options.push({ id: option.id, next: option.next ?? null });
303
+ }
304
+ if (invalidOptions || new Set(options.map((option) => option.id)).size !== options.length) continue;
305
+ if (waitingChoiceId && (options.length < 2 || options.length > 4 || item.done)) continue;
306
+ if (!waitingChoiceId && options.length) continue;
307
+ out.push({ packId, revision, nodeId, waitingChoiceId, options, done: item.done });
308
+ }
309
+ return out;
310
+ }
311
+
312
+ function inWindow(from, to, nowMin) {
313
+ if (from === undefined || to === undefined) return true;
314
+ const parse = (value) => Number(value.slice(0, 2)) * 60 + Number(value.slice(3, 5));
315
+ const start = parse(from);
316
+ const end = parse(to);
317
+ const now = Number(nowMin);
318
+ if (!Number.isFinite(now)) return false;
319
+ return end > start ? now >= start && now < end : now >= start || now < end;
320
+ }
321
+
322
+ function nodeMatches(node, venue, area, nowMin, visits) {
323
+ if (node.area !== area || hoursState(venue, nowMin) === 'closed') return false;
324
+ if (!areasNow(venue, nowMin).includes(area)) return false;
325
+ const when = node.when;
326
+ if (!when) return true;
327
+ if (!inWindow(when.from, when.to, nowMin)) return false;
328
+ if (when.minVisits !== undefined && !(Number(visits) >= when.minVisits)) return false;
329
+ if (when.phases?.length) {
330
+ const phaseKey = phaseAt(venue, nowMin).phase?.key;
331
+ if (!phaseKey || !when.phases.includes(phaseKey)) return false;
332
+ }
333
+ return true;
334
+ }
335
+
336
+ function validatedPack(raw) {
337
+ if (!isRecord(raw)) return null;
338
+ const { revision, ...content } = raw;
339
+ const result = validateStoryPack(content);
340
+ if (!result.ok || (revision !== undefined && revision !== result.pack.revision)) return null;
341
+ return result.pack;
342
+ }
343
+
344
+ /** Select the one matching story step, returning a cloned next progress snapshot. */
345
+ export function pickStory(catalog, venue, area, nowMin, session, visits) {
346
+ if (!Array.isArray(catalog) || !venue || typeof area !== 'string' || !Number.isFinite(Number(nowMin)) || Number(nowMin) < 0 || Number(nowMin) >= 1440 || hoursState(venue, nowMin) === 'closed') return null;
347
+ const current = normalizeStoryProgress(session?.storyProgress);
348
+ const candidates = [];
349
+ for (const row of catalog) {
350
+ if (!row || row.enabled !== true || !row.pack) continue;
351
+ const pack = validatedPack(row.pack);
352
+ if (!pack || pack.placeId !== venue.id || !storyAvailability(pack, [venue]).available) continue;
353
+ const existingIndex = current.findIndex((entry) => entry.packId === pack.id);
354
+ const existing = existingIndex >= 0 ? current[existingIndex] : null;
355
+ // A cursor from another revision is deliberately paused, never silently restarted.
356
+ if (existing && existing.revision !== pack.revision) continue;
357
+ if (existing && (existing.done || existing.waitingChoiceId)) continue;
358
+ candidates.push({
359
+ pack,
360
+ existingIndex,
361
+ existing,
362
+ active: Boolean(existing && !existing.done && !existing.waitingChoiceId),
363
+ });
364
+ }
365
+ candidates.sort((left, right) => Number(right.active) - Number(left.active));
366
+
367
+ for (const candidate of candidates) {
368
+ const { pack, existingIndex, existing } = candidate;
369
+ const cursor = existing?.nodeId ?? pack.start;
370
+ const node = pack.nodes.find((candidate) => candidate.id === cursor);
371
+ if (!node || !nodeMatches(node, venue, area, nowMin, visits)) continue;
372
+
373
+ const progress = current.map((entry) => ({ ...entry, options: entry.options.map((option) => ({ ...option })) }));
374
+ let entry;
375
+ if (existingIndex >= 0) entry = progress[existingIndex];
376
+ else {
377
+ if (progress.length >= 32) continue;
378
+ entry = { packId: pack.id, revision: pack.revision, nodeId: node.id, waitingChoiceId: null, options: [], done: false };
379
+ progress.push(entry);
380
+ }
381
+
382
+ let choice = null;
383
+ if (node.choices) {
384
+ const choiceId = `story:${pack.id}:${pack.revision}:${node.id}`;
385
+ entry.waitingChoiceId = choiceId;
386
+ entry.options = node.choices.map((option) => ({ id: option.id, next: option.next ?? null }));
387
+ choice = {
388
+ id: choiceId,
389
+ event: node.event,
390
+ area: node.area,
391
+ prompt: node.prompt ?? node.event,
392
+ options: node.choices.map(({ id, label, result }) => ({ id, label, result })),
393
+ };
394
+ } else if (node.next) {
395
+ entry.nodeId = node.next;
396
+ entry.waitingChoiceId = null;
397
+ entry.options = [];
398
+ } else {
399
+ entry.done = true;
400
+ entry.waitingChoiceId = null;
401
+ entry.options = [];
402
+ }
403
+ return { event: node.event, choice, progress };
404
+ }
405
+ return null;
406
+ }
407
+
408
+ /** Resolve an offered choice using its serialized edge snapshot (or finish on skip). */
409
+ export function advanceStoryChoice(rawProgress, choiceId, optionId) {
410
+ const progress = normalizeStoryProgress(rawProgress).map((entry) => ({ ...entry, options: entry.options.map((option) => ({ ...option })) }));
411
+ const index = progress.findIndex((entry) => entry.waitingChoiceId === choiceId);
412
+ if (index < 0) return progress;
413
+ const entry = progress[index];
414
+ const selected = entry.options.find((option) => option.id === optionId);
415
+ const skip = optionId === null || optionId === undefined || optionId === 'skip';
416
+ if (skip) {
417
+ entry.done = true;
418
+ } else if (!selected) {
419
+ return progress;
420
+ } else if (selected.next) {
421
+ entry.nodeId = selected.next;
422
+ } else {
423
+ entry.done = true;
424
+ }
425
+ entry.waitingChoiceId = null;
426
+ entry.options = [];
427
+ return progress;
428
+ }