@bendyline/gezel-script-stdlib 1.0.0 → 1.0.1
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/package.json +2 -2
- package/scripts/storeRecords.ts +386 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bendyline/gezel-script-stdlib",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.1",
|
|
4
4
|
"description": "Standard gate-script library packed into the app. Plain defineScript sources resolved in place by the script runner (scope: 'standard'); read-only, trusted, versioned with the app.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"keywords": [
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"!scripts/**/*.test.ts"
|
|
42
42
|
],
|
|
43
43
|
"dependencies": {
|
|
44
|
-
"@bendyline/gezel-sdk": "1.0.
|
|
44
|
+
"@bendyline/gezel-sdk": "1.0.1"
|
|
45
45
|
},
|
|
46
46
|
"devDependencies": {
|
|
47
47
|
"@types/node": "^24.13.3",
|
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
import { type InferredInput, defineScript, gezel } from '@bendyline/gezel-sdk';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Generic CRUD over a small record store in the project workspace, in one
|
|
5
|
+
* of two layouts chosen by the binding:
|
|
6
|
+
*
|
|
7
|
+
* - `folder-per-record` — each record lives at `<root>/<id>/record.json`
|
|
8
|
+
* (`{ version: 1, id, ...fields }`), and `<root>/index.json` holds a
|
|
9
|
+
* regenerated summary (`{ version: 1, records: [{ id, ...scalars }] }`)
|
|
10
|
+
* so pages and gezels can render a roster without N reads.
|
|
11
|
+
* - `single-file` — every record lives in `<root>.json` as
|
|
12
|
+
* `{ version: 1, records: { [id]: fields } }`.
|
|
13
|
+
*
|
|
14
|
+
* Persistence discipline mirrors `@bendyline/gezel-sdk/stores`: files are
|
|
15
|
+
* pretty-printed with a trailing newline, a missing file means "no store
|
|
16
|
+
* yet", and corrupt JSON or an unknown `version` throws — user data is
|
|
17
|
+
* never silently reset. Ids are validated against a strict pattern before
|
|
18
|
+
* any path is built; supplied ids are never laundered into a usable one.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
export const meta = defineScript({
|
|
22
|
+
name: 'storeRecords',
|
|
23
|
+
description:
|
|
24
|
+
'Action: generic CRUD (create/update/delete/get/list) over a workspace record store — one folder per record with a regenerated index.json, or a single <root>.json file.',
|
|
25
|
+
kind: 'action',
|
|
26
|
+
inputs: {
|
|
27
|
+
action: {
|
|
28
|
+
type: 'choice',
|
|
29
|
+
description: 'Operation to perform.',
|
|
30
|
+
required: true,
|
|
31
|
+
options: [
|
|
32
|
+
{ value: 'create' },
|
|
33
|
+
{ value: 'update' },
|
|
34
|
+
{ value: 'delete' },
|
|
35
|
+
{ value: 'get' },
|
|
36
|
+
{ value: 'list' },
|
|
37
|
+
],
|
|
38
|
+
},
|
|
39
|
+
id: {
|
|
40
|
+
type: 'string',
|
|
41
|
+
description:
|
|
42
|
+
'Record id (lowercase letters, digits, dashes; max 80 chars). Required for get/update/delete. Optional for create — generated from fields.slug, fields.title, or a random suffix when omitted.',
|
|
43
|
+
},
|
|
44
|
+
fields: {
|
|
45
|
+
type: 'json',
|
|
46
|
+
description:
|
|
47
|
+
'Record body for create/update: an object of field values. The id field is immutable and stripped from the body.',
|
|
48
|
+
},
|
|
49
|
+
root: {
|
|
50
|
+
type: 'string',
|
|
51
|
+
description: 'Workspace-relative root directory of the store (bind-provided).',
|
|
52
|
+
required: true,
|
|
53
|
+
},
|
|
54
|
+
mode: {
|
|
55
|
+
type: 'choice',
|
|
56
|
+
description: 'Store layout (bind-provided).',
|
|
57
|
+
required: true,
|
|
58
|
+
options: [{ value: 'folder-per-record' }, { value: 'single-file' }],
|
|
59
|
+
},
|
|
60
|
+
},
|
|
61
|
+
outputs: {
|
|
62
|
+
ok: { type: 'boolean', description: 'True when the operation completed; failures throw.' },
|
|
63
|
+
action: { type: 'string', description: 'The operation that ran.' },
|
|
64
|
+
id: {
|
|
65
|
+
type: 'string',
|
|
66
|
+
description: 'Affected record id (create/get/update/delete).',
|
|
67
|
+
nullable: true,
|
|
68
|
+
},
|
|
69
|
+
record: { type: 'json', description: 'The record, id included (create/get/update).' },
|
|
70
|
+
records: {
|
|
71
|
+
type: 'array',
|
|
72
|
+
description: 'Every record, sorted by id (list).',
|
|
73
|
+
itemType: 'object',
|
|
74
|
+
},
|
|
75
|
+
total: { type: 'number', description: 'Record count (list).', nullable: true },
|
|
76
|
+
},
|
|
77
|
+
requires: ['workspace.read', 'workspace.write'],
|
|
78
|
+
} as const);
|
|
79
|
+
|
|
80
|
+
type Fields = Record<string, unknown>;
|
|
81
|
+
|
|
82
|
+
const ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,79}$/;
|
|
83
|
+
|
|
84
|
+
const input = gezel.input as InferredInput<typeof meta>;
|
|
85
|
+
|
|
86
|
+
function fail(message: string): never {
|
|
87
|
+
throw new Error(message);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const root = String(input.root ?? '')
|
|
91
|
+
.replace(/\\+/g, '/')
|
|
92
|
+
.replace(/\/+$/, '');
|
|
93
|
+
if (!root) fail('root must be a non-empty workspace-relative path.');
|
|
94
|
+
|
|
95
|
+
const mode = input.mode;
|
|
96
|
+
const storeFile = `${root}.json`;
|
|
97
|
+
const indexFile = `${root}/index.json`;
|
|
98
|
+
|
|
99
|
+
function recordFile(id: string): string {
|
|
100
|
+
return `${root}/${id}/record.json`;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function slugify(text: string): string {
|
|
104
|
+
return text
|
|
105
|
+
.toLowerCase()
|
|
106
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
107
|
+
.replace(/^-+|-+$/g, '')
|
|
108
|
+
.slice(0, 80)
|
|
109
|
+
.replace(/-+$/, '');
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Supplied ids are validated, never laundered: slugifying '../x' into a
|
|
113
|
+
// usable id would silently resolve a hostile input to a real record.
|
|
114
|
+
function requireSuppliedId(raw: unknown): string {
|
|
115
|
+
if (typeof raw !== 'string' || !ID_PATTERN.test(raw)) {
|
|
116
|
+
fail(
|
|
117
|
+
`Invalid record id ${JSON.stringify(raw ?? null)}: expected 1-80 chars of lowercase letters, digits, and dashes, starting with a letter or digit (no path separators or dots).`,
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
return raw;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function generatedId(fields: Fields): string {
|
|
124
|
+
for (const candidate of [fields.slug, fields.title]) {
|
|
125
|
+
if (typeof candidate === 'string') {
|
|
126
|
+
const slug = slugify(candidate);
|
|
127
|
+
if (ID_PATTERN.test(slug)) return slug;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return `rec-${Math.random().toString(36).slice(2, 8).padEnd(6, '0')}`;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function normalizedFields(): Fields {
|
|
134
|
+
const raw: unknown = input.fields;
|
|
135
|
+
if (raw === undefined || raw === null) return {};
|
|
136
|
+
if (typeof raw !== 'object' || Array.isArray(raw)) {
|
|
137
|
+
fail('fields must be a JSON object of field values.');
|
|
138
|
+
}
|
|
139
|
+
const body: Fields = {};
|
|
140
|
+
for (const [key, value] of Object.entries(raw as Fields)) {
|
|
141
|
+
// id is immutable identity and version is the file-format stamp;
|
|
142
|
+
// neither may be smuggled in through the body.
|
|
143
|
+
if (key === 'id' || key === 'version') continue;
|
|
144
|
+
body[key] = value;
|
|
145
|
+
}
|
|
146
|
+
return body;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function parseVersioned(path: string, raw: string): Fields {
|
|
150
|
+
let parsed: unknown;
|
|
151
|
+
try {
|
|
152
|
+
parsed = JSON.parse(raw);
|
|
153
|
+
} catch (err) {
|
|
154
|
+
fail(
|
|
155
|
+
`Store file ${path} is not valid JSON (${err instanceof Error ? err.message : String(err)}). Fix or remove the file; it will not be overwritten automatically.`,
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
|
159
|
+
fail(`Store file ${path} must contain a JSON object.`);
|
|
160
|
+
}
|
|
161
|
+
const version = (parsed as { version?: unknown }).version;
|
|
162
|
+
if (version !== 1) {
|
|
163
|
+
fail(`Store file ${path} has unsupported version ${String(version)} (expected 1).`);
|
|
164
|
+
}
|
|
165
|
+
return parsed as Fields;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// The structural fs interface throws on both missing and unreadable, so a
|
|
169
|
+
// failed read means "no record/store yet" (same rule as the sdk stores).
|
|
170
|
+
async function readJsonIfPresent(path: string): Promise<Fields | null> {
|
|
171
|
+
let raw: string;
|
|
172
|
+
try {
|
|
173
|
+
raw = await gezel.fs.read(path);
|
|
174
|
+
} catch {
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
return parseVersioned(path, raw);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async function writeJson(path: string, value: unknown): Promise<void> {
|
|
181
|
+
await gezel.fs.write(path, `${JSON.stringify(value, null, 2)}\n`);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function recordFromFile(id: string, file: Fields): Fields {
|
|
185
|
+
// The folder name is the authoritative id — a hand-renamed folder must
|
|
186
|
+
// not surface a record whose id cannot be fetched back.
|
|
187
|
+
const record: Fields = { id };
|
|
188
|
+
for (const [key, value] of Object.entries(file)) {
|
|
189
|
+
if (key === 'version' || key === 'id') continue;
|
|
190
|
+
record[key] = value;
|
|
191
|
+
}
|
|
192
|
+
return record;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async function folderEntries(): Promise<Array<{ name: string; isDirectory: boolean }>> {
|
|
196
|
+
try {
|
|
197
|
+
return await gezel.fs.list(root);
|
|
198
|
+
} catch {
|
|
199
|
+
return [];
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async function folderIds(): Promise<string[]> {
|
|
204
|
+
return (await folderEntries())
|
|
205
|
+
.filter((entry) => entry.isDirectory)
|
|
206
|
+
.map((entry) => entry.name)
|
|
207
|
+
.sort();
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async function folderList(): Promise<Fields[]> {
|
|
211
|
+
const records: Fields[] = [];
|
|
212
|
+
for (const id of await folderIds()) {
|
|
213
|
+
const file = await readJsonIfPresent(recordFile(id));
|
|
214
|
+
// A folder without a record.json is not a record (e.g. a leftover
|
|
215
|
+
// emptied folder — see remove()).
|
|
216
|
+
if (file === null) continue;
|
|
217
|
+
records.push(recordFromFile(id, file));
|
|
218
|
+
}
|
|
219
|
+
return records;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
async function regenerateFolderIndex(): Promise<void> {
|
|
223
|
+
const records = await folderList();
|
|
224
|
+
const index = {
|
|
225
|
+
version: 1,
|
|
226
|
+
records: records.map((record) => {
|
|
227
|
+
const summary: Fields = { id: record.id };
|
|
228
|
+
for (const [key, value] of Object.entries(record)) {
|
|
229
|
+
if (key === 'id') continue;
|
|
230
|
+
const kind = typeof value;
|
|
231
|
+
if (kind === 'string' || kind === 'number' || kind === 'boolean') summary[key] = value;
|
|
232
|
+
}
|
|
233
|
+
return summary;
|
|
234
|
+
}),
|
|
235
|
+
};
|
|
236
|
+
await writeJson(indexFile, index);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// Object.hasOwn everywhere: 'constructor' is a valid id but an inherited
|
|
240
|
+
// key on every parsed object — a plain `records[id]` check would resolve it.
|
|
241
|
+
function loadedRecords(file: Fields | null): Record<string, unknown> {
|
|
242
|
+
if (file === null) return {};
|
|
243
|
+
const records = file.records;
|
|
244
|
+
if (records === undefined) return {};
|
|
245
|
+
if (typeof records !== 'object' || records === null || Array.isArray(records)) {
|
|
246
|
+
fail(
|
|
247
|
+
`Store file ${storeFile} has a malformed records map. Fix or remove the file; it will not be overwritten automatically.`,
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
return records as Record<string, unknown>;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function bodyOf(records: Record<string, unknown>, id: string): Fields {
|
|
254
|
+
const body = records[id];
|
|
255
|
+
if (typeof body !== 'object' || body === null || Array.isArray(body)) {
|
|
256
|
+
fail(
|
|
257
|
+
`Store file ${storeFile} record '${id}' is not an object. Fix or remove the file; it will not be overwritten automatically.`,
|
|
258
|
+
);
|
|
259
|
+
}
|
|
260
|
+
return body as Fields;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
async function loadSingleFile(): Promise<Record<string, unknown>> {
|
|
264
|
+
return loadedRecords(await readJsonIfPresent(storeFile));
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
async function saveSingleFile(records: Record<string, unknown>): Promise<void> {
|
|
268
|
+
await writeJson(storeFile, { version: 1, records });
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function noRecord(id: string, knownIds: string[]): never {
|
|
272
|
+
const where = mode === 'single-file' ? storeFile : root;
|
|
273
|
+
fail(`No record '${id}' in ${where}. Known ids: ${knownIds.join(', ') || '(none)'}`);
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
async function create(): Promise<Fields> {
|
|
277
|
+
const fields = normalizedFields();
|
|
278
|
+
const id = input.id !== undefined ? requireSuppliedId(input.id) : generatedId(fields);
|
|
279
|
+
if (mode === 'folder-per-record') {
|
|
280
|
+
if ((await readJsonIfPresent(recordFile(id))) !== null) {
|
|
281
|
+
fail(`Record '${id}' already exists in ${root}.`);
|
|
282
|
+
}
|
|
283
|
+
await writeJson(recordFile(id), { version: 1, id, ...fields });
|
|
284
|
+
await regenerateFolderIndex();
|
|
285
|
+
} else {
|
|
286
|
+
const records = await loadSingleFile();
|
|
287
|
+
if (Object.hasOwn(records, id)) fail(`Record '${id}' already exists in ${storeFile}.`);
|
|
288
|
+
records[id] = fields;
|
|
289
|
+
await saveSingleFile(records);
|
|
290
|
+
}
|
|
291
|
+
return { ok: true, action: 'create', id, record: { id, ...fields } };
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
async function get(): Promise<Fields> {
|
|
295
|
+
const id = requireSuppliedId(input.id);
|
|
296
|
+
if (mode === 'folder-per-record') {
|
|
297
|
+
const file = await readJsonIfPresent(recordFile(id));
|
|
298
|
+
if (file === null) noRecord(id, await folderIds());
|
|
299
|
+
return { ok: true, action: 'get', id, record: recordFromFile(id, file) };
|
|
300
|
+
}
|
|
301
|
+
const records = await loadSingleFile();
|
|
302
|
+
if (!Object.hasOwn(records, id)) noRecord(id, Object.keys(records).sort());
|
|
303
|
+
return { ok: true, action: 'get', id, record: { id, ...bodyOf(records, id) } };
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
async function update(): Promise<Fields> {
|
|
307
|
+
const id = requireSuppliedId(input.id);
|
|
308
|
+
const patch = normalizedFields();
|
|
309
|
+
if (mode === 'folder-per-record') {
|
|
310
|
+
const file = await readJsonIfPresent(recordFile(id));
|
|
311
|
+
if (file === null) noRecord(id, await folderIds());
|
|
312
|
+
const merged = { ...recordFromFile(id, file), ...patch, id };
|
|
313
|
+
await writeJson(recordFile(id), { version: 1, ...merged });
|
|
314
|
+
await regenerateFolderIndex();
|
|
315
|
+
return { ok: true, action: 'update', id, record: merged };
|
|
316
|
+
}
|
|
317
|
+
const records = await loadSingleFile();
|
|
318
|
+
if (!Object.hasOwn(records, id)) noRecord(id, Object.keys(records).sort());
|
|
319
|
+
const merged = { ...bodyOf(records, id), ...patch };
|
|
320
|
+
records[id] = merged;
|
|
321
|
+
await saveSingleFile(records);
|
|
322
|
+
return { ok: true, action: 'update', id, record: { id, ...merged } };
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
async function remove(): Promise<Fields> {
|
|
326
|
+
const id = requireSuppliedId(input.id);
|
|
327
|
+
if (mode === 'folder-per-record') {
|
|
328
|
+
if ((await readJsonIfPresent(recordFile(id))) === null) noRecord(id, await folderIds());
|
|
329
|
+
const dir = `${root}/${id}`;
|
|
330
|
+
let entries: Array<{ name: string; isDirectory: boolean }> = [];
|
|
331
|
+
try {
|
|
332
|
+
entries = await gezel.fs.list(dir);
|
|
333
|
+
} catch {
|
|
334
|
+
entries = [];
|
|
335
|
+
}
|
|
336
|
+
for (const entry of entries) {
|
|
337
|
+
if (!entry.isDirectory) await gezel.fs.rm(`${dir}/${entry.name}`);
|
|
338
|
+
}
|
|
339
|
+
// The sdk fs surface has no directory removal; record.json going away
|
|
340
|
+
// is what unregisters the record (get/list key off it), so a runtime
|
|
341
|
+
// that refuses to remove the emptied folder is tolerated.
|
|
342
|
+
try {
|
|
343
|
+
await gezel.fs.rm(dir);
|
|
344
|
+
} catch {
|
|
345
|
+
// inert emptied folder left behind
|
|
346
|
+
}
|
|
347
|
+
await regenerateFolderIndex();
|
|
348
|
+
return { ok: true, action: 'delete', id };
|
|
349
|
+
}
|
|
350
|
+
const records = await loadSingleFile();
|
|
351
|
+
if (!Object.hasOwn(records, id)) noRecord(id, Object.keys(records).sort());
|
|
352
|
+
delete records[id];
|
|
353
|
+
await saveSingleFile(records);
|
|
354
|
+
return { ok: true, action: 'delete', id };
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
async function list(): Promise<Fields> {
|
|
358
|
+
if (mode === 'folder-per-record') {
|
|
359
|
+
const records = await folderList();
|
|
360
|
+
return { ok: true, action: 'list', records, total: records.length };
|
|
361
|
+
}
|
|
362
|
+
const records = await loadSingleFile();
|
|
363
|
+
const out = Object.keys(records)
|
|
364
|
+
.sort()
|
|
365
|
+
.map((id) => ({ id, ...bodyOf(records, id) }));
|
|
366
|
+
return { ok: true, action: 'list', records: out, total: out.length };
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
async function run(): Promise<Fields> {
|
|
370
|
+
switch (input.action) {
|
|
371
|
+
case 'create':
|
|
372
|
+
return create();
|
|
373
|
+
case 'get':
|
|
374
|
+
return get();
|
|
375
|
+
case 'update':
|
|
376
|
+
return update();
|
|
377
|
+
case 'delete':
|
|
378
|
+
return remove();
|
|
379
|
+
case 'list':
|
|
380
|
+
return list();
|
|
381
|
+
default:
|
|
382
|
+
return fail(`Unknown action '${String(input.action)}'.`);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
gezel.output(await run());
|