@margoengine/save 0.0.0-stage → 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/README.md CHANGED
@@ -1,3 +1,513 @@
1
- # Temporary Holding Version
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.
1
+ # @margoengine/save
2
+
3
+ Import `margoengine/save` from the `margoengine` package, or `@margoengine/save` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
+
5
+ Save games, scene files and prefabs: a versioned JSON document of entities with stable ids, components and
6
+ references; prefab definitions with instances, overrides and nesting; a tested migration registry for schema
7
+ changes; validation that names every problem and its fix; loading into your world that is all or nothing; optional
8
+ gzip; and storage adapters for memory, localStorage, IndexedDB and files behind one promise-based interface with
9
+ AbortSignal.
10
+
11
+ ```ts
12
+ import { Migrations, loadGame, memoryStorage, saveGame, type SaveDocument } from 'margoengine/save';
13
+
14
+ const level: SaveDocument = {
15
+ format: 'margo-save',
16
+ version: 2,
17
+ meta: { title: 'Chapter 1', playTime: 754 },
18
+ prefabs: {
19
+ door: {
20
+ entities: [
21
+ { id: 'frame', components: { mesh: 'door.glb', locked: false } },
22
+ { id: 'handle', parent: 'frame', components: { opens: { $ref: 'frame' } } },
23
+ ],
24
+ },
25
+ },
26
+ entities: [
27
+ { id: 'player', transform: { position: [0, 0, 0] }, components: { health: { hp: 80, max: 100 }, target: { $ref: 'gate' } } },
28
+ { id: 'gate', prefab: 'door', transform: { position: [0, 0, -8] }, components: { locked: true } },
29
+ ],
30
+ };
31
+
32
+ const storage = memoryStorage(); // or webStorage(), indexedDBStorage(), fileStorage('./saves') from margoengine/save/node
33
+ await saveGame(storage, 'slot-1', level); // validated, gzipped where CompressionStream exists, written in one step
34
+
35
+ const migrations = new Migrations(2).register(1, (old) => ({ ...old, version: 2 }));
36
+ const loaded = await loadGame(storage, 'slot-1', { migrations }); // decoded, migrated, validated; null when empty
37
+ ```
38
+
39
+ `indexedDBStorage()` keeps one database connection open while the storage is in use. Call `await storage.close()` (or declare it with `using`) when you are done with saving; it is safe to call twice, and the next call opens the database again.
40
+
41
+ ## The document
42
+
43
+ `{format: 'margo-save', version, entities, prefabs?, meta?}`. `version` is your schema version. Each entity has a
44
+ stable `id`, and optionally a `name`, a `parent` (an id), a local `transform` (`position`, unit-quaternion
45
+ `rotation`, `scale`) and `components`: any JSON by component name. A reference to another entity is
46
+ `{"$ref": "id"}` anywhere inside a component; references, parents and prefab overrides all use ids, so a save
47
+ survives reordering and stays diffable.
48
+
49
+ ## Prefabs
50
+
51
+ A prefab is a list of entities with ids local to it; its `root` (default the first) becomes the instance. An entity
52
+ with `prefab: 'door'` expands to the prefab's entities: the root merged into the instance (the instance's own
53
+ components, name, transform and parent win), and the others as `gate/handle`, `gate/...`, with their parents and
54
+ local references re-pointed at the copies. `overrides` change the copies by prefab-local id as JSON Merge Patches
55
+ (RFC 7386: objects merge, other values replace, `null` removes a key), and a `parent` or `$ref` inside an override
56
+ names a prefab-local id, like the override's key; `null` for a whole entity removes it and its children. Prefabs may contain instances of other prefabs (ids like `cart/load/lid`), without cycles, up to 32
57
+ deep.
58
+
59
+ ```ts
60
+ import { expandSave, parseSave } from 'margoengine/save';
61
+
62
+ const flat = expandSave(parseSave({
63
+ format: 'margo-save',
64
+ version: 1,
65
+ prefabs: { crate: { entities: [{ id: 'box', components: { mass: 2 } }, { id: 'lid', parent: 'box', components: {} }] } },
66
+ entities: [{ id: 'c1', prefab: 'crate', overrides: { lid: { components: { colour: 'red' } } } }],
67
+ }));
68
+ // [{ id: 'c1', components: { mass: 2 }, ... }, { id: 'c1/lid', parent: 'c1', components: { colour: 'red' }, ... }]
69
+ ```
70
+
71
+ ## Loading into a world, all or nothing
72
+
73
+ ```ts
74
+ import { loadWorld, type WorldAdapter } from 'margoengine/save';
75
+
76
+ const scene = new Map<string, { id: string; components: Record<string, unknown> }>();
77
+ const adapter: WorldAdapter<{ id: string; components: Record<string, unknown> }> = {
78
+ create: (entity) => ({ id: entity.id, components: entity.components }), // build off-screen
79
+ commit: (handles) => {
80
+ scene.clear();
81
+ for (const [id, object] of handles) scene.set(id, object); // swap the new world in
82
+ },
83
+ destroy: () => {}, // undo one create
84
+ };
85
+ loadWorld({ format: 'margo-save', version: 1, entities: [{ id: 'a' }, { id: 'b', parent: 'a' }] }, adapter);
86
+ ```
87
+
88
+ `loadWorld(document, adapter, {migrations, components, signal})` validates, migrates and expands everything before
89
+ building anything, then calls `create` for every entity (parents first), `link` for every entity once all exist
90
+ (with `resolve(id)` for references) and `commit` once. If any step throws or the signal aborts, it calls `destroy` for
91
+ everything built, latest first, and throws `MargoError` `'failed'` with the cause: a bad file never leaves a
92
+ half-loaded world.
93
+
94
+ For an `@margoengine/ecs` World, `saveEcs(world, components)` writes the entities that hold the named components and
95
+ `ecsAdapter(world, components)` loads them back; a value that does not fit a field (a fraction in an `Int32Array`
96
+ field) undoes the whole load.
97
+
98
+ ```ts
99
+ import { World } from 'margoengine/ecs';
100
+ import { ecsAdapter, loadWorld, saveEcs } from 'margoengine/save';
101
+
102
+ const world = new World(1024);
103
+ const position = world.component({ x: Float32Array, y: Float32Array });
104
+ position.add(world.create(), { x: 3, y: 4 });
105
+ const snapshot = saveEcs(world, { position });
106
+ const copy = new World(1024);
107
+ const copyPosition = copy.component({ x: Float32Array, y: Float32Array });
108
+ loadWorld(snapshot, ecsAdapter(copy, { position: copyPosition }));
109
+ ```
110
+
111
+ ## Saving a running scene
112
+
113
+ `@margoengine/save/engine` needs no mapping. `captureScene(engine)` reads the scene as it stands and gives a save
114
+ document; `restoreScene(engine, document)` puts it back.
115
+
116
+ ```ts
117
+ import { Engine, box } from 'margoengine/core';
118
+ import { loadGame, memoryStorage, saveGame } from 'margoengine/save';
119
+ import { captureScene, restoreScene } from 'margoengine/save/engine';
120
+
121
+ const engine = await Engine.create(document.createElement('canvas'));
122
+ const crate = engine.createMesh().setGeometry(box()).setPosition([0, 1, 0]);
123
+ crate.name = 'crate';
124
+
125
+ const storage = memoryStorage();
126
+ await saveGame(storage, 'slot-1', captureScene(engine, { meta: { title: 'Chapter 1' } }));
127
+
128
+ crate.setPosition([5, 0, 0]);
129
+ const { meshes, meta } = await restoreScene(engine, await loadGame(storage, 'slot-1'));
130
+ console.log(meshes.get('crate')?.position.y, meta.title); // 1 'Chapter 1'
131
+ ```
132
+
133
+ What it saves:
134
+
135
+ | Part | Saved as |
136
+ | --- | --- |
137
+ | A mesh | Its name, parent, local transform, geometry, material, `visible` and `receiveShadow`. Meshes that share a geometry or a material share one again. |
138
+ | A glTF model | Its URL (`model.asset.baseURL`), the material variant, and only the nodes that differ from the file. A mesh hanging from a node stays on that node. A URL used twice loads once, and the rest are `cloneModel` copies. |
139
+ | The view | The camera, the scene's lighting and its background. `camera: false` leaves the camera alone. |
140
+ | A plugin | Its own `saveState()` and `loadState(state)` when it has them, else its JSON `options` and every property with both a getter and a setter. |
141
+
142
+ A mesh's id is its name, or its name with a number when two share one, and it stays the same across saves (`meshId`).
143
+
144
+ Plugins keep much of their state in public fields, which the default cannot tell from private ones, so name those,
145
+ or write the two functions:
146
+
147
+ ```ts
148
+ import { Engine } from 'margoengine/core';
149
+ import { captureScene, restoreScene } from 'margoengine/save/engine';
150
+
151
+ const engine = await Engine.create(document.createElement('canvas'));
152
+ const weather = { name: 'weather', rain: 0.5, setup() {} };
153
+ const score = { name: 'score', points: 12, setup() {} };
154
+ engine.use(weather).use(score);
155
+
156
+ const plugins = {
157
+ weather: { properties: ['rain'] }, // these fields, in place of the default
158
+ score: { save: (p: typeof score) => p.points, load: (p: typeof score, state: unknown) => void (p.points = state as number) },
159
+ debugOverlay: null, // leave this one out
160
+ };
161
+ const saved = captureScene(engine, { plugins, onSkip: (plugin) => console.warn('nothing saved for', plugin.name) });
162
+ weather.rain = 0;
163
+ await restoreScene(engine, saved, { plugins });
164
+ console.log(weather.rain); // 0.5
165
+ ```
166
+
167
+ A plugin in the save and not in the scene needs `type` in its binding (`{ type: Sky }`), which attaches it with the
168
+ saved options; without one the save is refused before anything changes. So is a damaged `meta.engine`: a camera the
169
+ engine would refuse each frame (fov outside 0 to 180, near at 0 or below, far not past near, position at the target,
170
+ up along the view), lighting arrays of another length than the scene's, or a background that is not a string or null.
171
+
172
+ With `scene`, factories receive the real engine inside that scene's setup scope, so `use`, `createMesh`, lighting
173
+ and passes belong to the target scene. State callbacks and rollback run in the same scope. A factory that throws
174
+ after attaching plugins has those registrations removed in reverse order. Rollback checks instance identity and
175
+ preserves a later replacement. Factories must dispose their own resources; binding callbacks must undo their own
176
+ effects beyond the saved plugin state.
177
+
178
+ ```ts
179
+ import { Engine, type EngineKernel } from 'margoengine/core';
180
+ import { captureScene, restoreScene } from 'margoengine/save/engine';
181
+
182
+ const engine = await Engine.create(document.createElement('canvas'));
183
+ const scene = engine.createScene('restored');
184
+ const type = {
185
+ attach(host: EngineKernel) {
186
+ const plugin = { name: 'score', points: 0, setup() {} };
187
+ host.use(plugin);
188
+ return plugin;
189
+ },
190
+ };
191
+ type.attach(engine).points = 12;
192
+ const plugins = { score: { type, properties: ['points'] } };
193
+ const saved = captureScene(engine, { plugins });
194
+ await restoreScene(engine, saved, { scene, plugins });
195
+ console.log(engine.sceneOf(scene.plugins.get('score')!) === scene); // true
196
+ engine.dispose();
197
+ ```
198
+
199
+ `restoreScene` is all or nothing. It checks the whole save, loads the models out of sight and builds every mesh, and
200
+ only then applies plugin state, camera and lighting and removes what the scene held. A model that fails to load, a
201
+ throw from `onEntity` or a plugin, or an abort leaves the running scene as it was, and `signal` stops it. `filter`
202
+ keeps a mesh and all under it out of a capture and out of what a restore removes, such as your UI; `clear: false` adds
203
+ to the scene. `components(mesh)` adds your own data, and `onEntity(mesh, entity, get)` reads it back. Other options:
204
+ `scene`, `version`, `meta`, `migrations`, `modelURL` for a model not loaded from a URL, `load` and `clone`.
205
+
206
+ Geometry is written into the save, so a large static mesh is better as a glTF model, which saves as a URL.
207
+
208
+ ## Change recorder (`@margoengine/save/delta`)
209
+
210
+ `diffSave(base, edited)` is what a user changed in a loaded scene, as a small JSON delta; `applyDelta(base, delta)` puts it back on the base. Changed entities are JSON Merge Patches (RFC 7386, as prefab overrides already are), added entities are whole, removed ones are ids, and `meta` is patched too. Keep the delta instead of the whole document: it stays valid while the shipped base changes elsewhere, and it is a few lines of JSON.
211
+
212
+ ```ts
213
+ import {diffSave, applyDelta, SaveRecorder} from 'margoengine/save/delta';
214
+
215
+ const door = {id: 'door', transform: {position: [1, 0, 0] as const}, components: {hinge: {angle: 0}}};
216
+ const base = {format: 'margo-save' as const, version: 1, entities: [door, {id: 'crate'}]};
217
+ // The player opened the door and smashed the crate.
218
+ const edited = {...base, entities: [{...door, components: {hinge: {angle: 90}}}]};
219
+
220
+ const delta = diffSave(base, edited);
221
+ console.log(JSON.stringify(delta.changed), delta.removed); // {"door":{"components":{"hinge":{"angle":90}}}} ["crate"]
222
+ console.log(applyDelta(base, JSON.parse(JSON.stringify(delta))).entities.length); // 1
223
+
224
+ const recorder = new SaveRecorder(base); // measures from its base; commit(current) moves the base forward
225
+ console.log(recorder.changes(edited).removed);
226
+ ```
227
+
228
+ - `diffSave(base, edited)`: entities are matched by id; reordering the list is not recorded. A merge patch cannot store `null` (it means remove), so a changed value holding `null` throws a `TypeError` naming its path. Duplicate ids throw.
229
+ - `applyDelta(base, delta, {validate = true, components, strictComponents})`: pure; throws a `TypeError` when the delta removes or changes an id the base lacks, adds one it has, was made for another `version`, or (with `validate`) leaves an invalid document, which `parseSave` names.
230
+ - `SaveRecorder(base)`: `changes(current)`, `commit(current)`, `apply(delta)` and `base`. `isEmptyDelta(delta)` tells a no-op.
231
+ - A delta is made from the document shape (`captureScene(engine)` of `@margoengine/save/engine` makes it), not by watching the running scene: take the current document with the engine's save functions, then diff it.
232
+
233
+ ## Save slots
234
+
235
+ `@margoengine/save/slots` puts a load screen over any storage. A slot holds a save, a small record of what it is and a
236
+ thumbnail, and `list()` reads the records alone, so a load screen opens without reading one save.
237
+
238
+ ```ts
239
+ import { memoryStorage, type SaveDocument } from 'margoengine/save';
240
+ import { SaveSlots } from 'margoengine/save/slots';
241
+
242
+ const game = (title: string): SaveDocument => ({ format: 'margo-save', version: 1, meta: { title }, entities: [] });
243
+
244
+ const slots = new SaveSlots(memoryStorage()); // or indexedDBStorage(), fileStorage('./saves')
245
+ await slots.save('slot-1', game('Chapter 2'), { playTime: 754, meta: { level: 3 } });
246
+ for (let i = 0; i < 5; i++) await slots.autosave(game(`Autosave ${i}`)); // a ring of 3, oldest first
247
+
248
+ for (const slot of await slots.list()) console.log(slot.id, slot.title, new Date(slot.savedAt), slot.meta);
249
+
250
+ const newest = await slots.latest(); // what a Continue button loads, autosaves included
251
+ const loaded = newest && (await slots.load(newest.id)); // as loadGame: pass migrations here
252
+ console.log(loaded?.meta?.title); // Autosave 4
253
+ ```
254
+
255
+ For a thumbnail, take the canvas right after a frame, in the same task: a WebGPU canvas keeps its picture only until the
256
+ frame is shown. `slots.thumbnail(id)` gives it back as a Blob.
257
+
258
+ ```ts
259
+ import { Engine, box } from 'margoengine/core';
260
+ import { memoryStorage } from 'margoengine/save';
261
+ import { captureScene } from 'margoengine/save/engine';
262
+ import { SaveSlots, captureThumbnail } from 'margoengine/save/slots';
263
+
264
+ const engine = await Engine.create(document.createElement('canvas'));
265
+ engine.createMesh().setGeometry(box());
266
+ const slots = new SaveSlots(memoryStorage());
267
+
268
+ engine.render();
269
+ const thumbnail = await captureThumbnail(engine.canvas, { width: 320 }); // WebP where the browser has it, else PNG
270
+ await slots.save('slot-1', captureScene(engine, { meta: { title: 'Chapter 2' } }), { thumbnail });
271
+
272
+ const picture = await slots.thumbnail('slot-1');
273
+ if (picture) document.body.append(Object.assign(new Image(), { src: URL.createObjectURL(picture) }));
274
+ ```
275
+
276
+ `autosaveEvery(milliseconds, capture, { onError })` runs the ring on a timer: `capture` returns the document, or null
277
+ to skip a turn in a menu or a cutscene, and the result has `stop()` and works with `using`. An autosave never touches a
278
+ player's slot, and `auto-` ids are refused in `save` and as the target of `copy`.
279
+
280
+ | Option | Default | What it does |
281
+ | --- | --- | --- |
282
+ | `namespace` | `'slot'` | Keeps profiles apart in one storage. |
283
+ | `autosaves` | `3` | How many autosaves take turns. |
284
+ | `now` | `Date.now` | The clock for `savedAt`. |
285
+ | `compress`, `validate` | as `saveGame` | Passed to each save. |
286
+
287
+ Also `info(id)`, `copy(from, to)` and `delete(id)`. Writes run one at a time, in call order, and every call takes
288
+ `signal`.
289
+
290
+ A slot's files carry a generation in their keys, and writing its record is the one step that switches to them. A failed
291
+ write or a crash before that leaves the old slot whole, with some unused files that the next save clears. A record that
292
+ cannot be read shows in `list()` with `damaged: true`, and `save` or `delete` replaces it.
293
+
294
+ ## Safe writes
295
+
296
+ `safeStorage` from `@margoengine/save/safe` wraps any storage so a failed or torn write never loses the last good save,
297
+ and damage is found on read. Each key keeps two copies, `key~a` and `key~b`, each with a generation and a CRC-32. A write
298
+ only ever goes over the copy that is not the newest good one, and is read back to check it. A read gives the newest good
299
+ copy. Generations are 64-bit: a write at the last one, 2^64 - 1, rejects with MargoError `'failed'` before any copy
300
+ changes, and `check` rejects a generation above 2^53 - 1 that a number cannot hold exactly (`read` still loads it).
301
+
302
+ ```ts
303
+ import { loadGame, memoryStorage, saveGame, type SaveDocument } from 'margoengine/save';
304
+ import { safeStorage } from 'margoengine/save/safe';
305
+
306
+ const disk = memoryStorage(); // or indexedDBStorage(), fileStorage('./saves')
307
+ const storage = safeStorage(disk, { onRecover: ({ key, reason }) => console.warn(key, 'fell back:', reason) });
308
+ const game = (title: string): SaveDocument => ({ format: 'margo-save', version: 1, meta: { title }, entities: [] });
309
+
310
+ await saveGame(storage, 'slot-1', game('older'));
311
+ await saveGame(storage, 'slot-1', game('newer'));
312
+
313
+ await disk.write('slot-1~b', new Uint8Array(10)); // what a torn write leaves
314
+ const save = await loadGame(storage, 'slot-1');
315
+ console.log(save?.meta?.title); // older
316
+ console.log(await storage.check('slot-1')); // { ok: true, good: 1, bad: 1, generation: 1 }
317
+ ```
318
+
319
+ The result is a storage like any other, so `SaveSlots` runs over it. With both copies bad a read rejects with `MargoError`
320
+ `'failed'`; `check(key)` reports without changing anything, and the next write goes over the bad copy.
321
+
322
+ | Option | Default | What it does |
323
+ | --- | --- | --- |
324
+ | `verify` | `true` | Reads each write back and compares it; a mismatch rejects, and the last good save stands. |
325
+ | `legacy` | `false` | Reads a save from before this wrapper, stored plainly under `key`, unchecked. The next write moves it over. Off, such a save is refused. |
326
+ | `onRecover` | none | Called with `{key, copy, reason}` when a read passes over a bad copy. |
327
+
328
+ A write costs two reads, a write and a read back, and a key takes twice the room. The CRC finds accidents; it is no
329
+ signature, and someone editing a save can make a matching one.
330
+
331
+ ## Signed saves
332
+
333
+ `signedStorage` from `@margoengine/save/signed` is `safeStorage` with an HMAC-SHA-256 tag on every copy, so an edited save
334
+ is refused instead of read. The tag covers the copy, its physical key and its generation. Pass a secret key of at least 32 random
335
+ bytes, or an HMAC-SHA-256 `CryptoKey` of 256 bits or more with `sign` and `verify` usages; the key is never saved. A forged or torn
336
+ newest copy goes to `onRecover` and the older signed copy is read. With no signed copy left a read rejects with `MargoError`
337
+ `'failed'`. WebCrypto is `crypto.subtle` unless you pass `options.subtle`; without it the call throws `'unsupported'`. Unsigned
338
+ legacy data is never accepted.
339
+
340
+ ```ts
341
+ import { loadGame, memoryStorage, saveGame, type SaveDocument } from 'margoengine/save';
342
+ import { signedStorage } from 'margoengine/save/signed';
343
+
344
+ const disk = memoryStorage();
345
+ const key = crypto.getRandomValues(new Uint8Array(32)); // keep this secret outside the save, and the same between runs
346
+ const storage = signedStorage(disk, key, { onRecover: ({ key, reason }) => console.warn(key, 'fell back:', reason) });
347
+ const game = (title: string): SaveDocument => ({ format: 'margo-save', version: 1, meta: { title }, entities: [] });
348
+
349
+ await saveGame(storage, 'slot-1', game('older'));
350
+ await saveGame(storage, 'slot-1', game('newer'));
351
+
352
+ const copy = (await disk.read('slot-1~a')) ?? (await disk.read('slot-1~b'));
353
+ console.log(copy !== null); // true: the signed frame is on disk
354
+ await disk.write('slot-1~b', new Uint8Array(40)); // someone's edit, with no valid tag
355
+ const save = await loadGame(storage, 'slot-1');
356
+ console.log(save?.meta?.title); // older: the edited copy fails its tag
357
+ ```
358
+
359
+ Signing proves a save was written with your key; it does not encrypt it, and it cannot tell a copy from an older one
360
+ written under the same key and slot (a player can put back an old signed file). Anyone with the key in the page can sign.
361
+
362
+ ## Browser file storage
363
+
364
+ `opfsStorage` from `@margoengine/save/opfs` keeps each save as one file in the origin private file system, with no size
365
+ limit of Web Storage and no database to open. A write goes to a temporary stream whose close swaps it into place, so a
366
+ failed or aborted write keeps the previous file. Operations on one key run in call order for one adapter; two tabs or
367
+ adapters on one key are last-close-wins. An abort is checked after each step and before the close, the point of no
368
+ return. Pass `namespace` to pick the directory (default `'margo-saves'`) or `directory` to give a handle you opened, as a
369
+ worker does. A browser without OPFS throws `MargoError` `'unsupported'`; a file with a damaged frame throws `'failed'`;
370
+ a key over 175 UTF-8 bytes is a `RangeError`.
371
+
372
+ ```ts
373
+ import { loadGame, saveGame, type SaveDocument } from 'margoengine/save';
374
+ import { opfsStorage } from 'margoengine/save/opfs';
375
+
376
+ const storage = opfsStorage({ namespace: 'readme-saves' });
377
+ const game: SaveDocument = { format: 'margo-save', version: 1, meta: { title: 'OPFS' }, entities: [] };
378
+ await saveGame(storage, 'slot-1', game);
379
+ console.log((await loadGame(storage, 'slot-1'))?.meta?.title); // OPFS
380
+ console.log(await storage.keys()); // ['slot-1']
381
+ await storage.delete('slot-1');
382
+ ```
383
+
384
+ Wrap it in `safeStorage` or `signedStorage` for two copies and tamper checks.
385
+
386
+
387
+ ## Cloud saves
388
+
389
+ `remoteStorage` from `@margoengine/save/remote` keeps saves on an HTTP server: GET, PUT and DELETE on
390
+ `${url}/${encodeURIComponent(key)}`, and GET on `url` for a JSON array of keys. A read remembers the key's ETag and a
391
+ write sends it as `If-Match`, so the server finds a save another device made in between, and `conflict` says what happens
392
+ then. `remoteHandler` is the other half: a server over any storage, as a function from a `Request` to a `Response`.
393
+
394
+ ```ts
395
+ import { memoryStorage } from 'margoengine/save';
396
+ import { remoteHandler, remoteStorage } from 'margoengine/save/remote';
397
+
398
+ const server = remoteHandler(memoryStorage(), { base: '/saves' });
399
+ const fetch = async (input: RequestInfo | URL, init?: RequestInit) => server(new Request(input, init)); // or the network
400
+ const url = 'https://game.example/saves';
401
+ const bytes = (text: string) => new TextEncoder().encode(text);
402
+
403
+ const phone = remoteStorage({ url, fetch });
404
+ const laptop = remoteStorage({ url, fetch });
405
+ await phone.write('slot-1', bytes('level 1'));
406
+ await laptop.read('slot-1');
407
+ await phone.write('slot-1', bytes('level 2'));
408
+
409
+ await laptop.write('slot-1', bytes('level 1, with a side quest')).catch((error) => console.log(error.code)); // 'state'
410
+
411
+ const merging = remoteStorage({
412
+ url,
413
+ fetch,
414
+ conflict: ({ local, remote }) => (remote && remote.length > (local?.length ?? 0) ? remote : local), // keeps the longer
415
+ });
416
+ await merging.write('slot-1', bytes('level 2 and more'));
417
+ console.log(new TextDecoder().decode((await phone.read('slot-1'))!)); // level 2 and more
418
+ ```
419
+
420
+ | `conflict` | When the server's save is not the one this client last saw |
421
+ | --- | --- |
422
+ | `'error'` (default) | The write rejects with `MargoError` `'state'` and nothing changes. Read the key, then save again. |
423
+ | `'local'` | This write goes over it. |
424
+ | `'remote'` | The server's stays, and this write is dropped. |
425
+ | a function | Gets `{key, local, remote}` and returns the bytes to keep, or null for none. `local` is null for a delete and `remote` for a save deleted elsewhere. |
426
+
427
+ | Option | Default | What it does |
428
+ | --- | --- | --- |
429
+ | `url` | none | The folder of saves. |
430
+ | `fetch` | `globalThis.fetch` | How requests go out. |
431
+ | `headers` | none | Sent with each request. A function runs for each attempt, for a token that expires. |
432
+ | `timeout` | `30000` | Milliseconds for one attempt. |
433
+ | `retries` | `3` | Further attempts after a network failure, a timeout, a 408, a 429 or a 5xx, waiting as `Retry-After` says, up to a minute; longer, the call fails. |
434
+
435
+ A write that lost its answer and tried again gets a 412 from its own earlier write; the bytes on the server are then the
436
+ same, and it counts as done. A device that has never read a key cannot write over it: read first on a new device.
437
+
438
+ On Node, the handler needs a few lines around it:
439
+
440
+ ```ts
441
+ import { createServer } from 'node:http';
442
+ import { Readable } from 'node:stream';
443
+ import { fileStorage } from 'margoengine/save/node';
444
+ import { remoteHandler, remoteStorage } from 'margoengine/save/remote';
445
+
446
+ const handle = remoteHandler(fileStorage('./cloud-saves'), {
447
+ base: '/saves',
448
+ origin: 'https://game.example', // the page's origin, for CORS; leave it out for the same origin
449
+ authorize: (request) => request.headers.get('authorization') === 'Bearer secret', // yours to write
450
+ });
451
+ const server = createServer(async (request, response) => {
452
+ const body = request.method === 'PUT' ? { body: Readable.toWeb(request) as ReadableStream, duplex: 'half' } : {};
453
+ const answer = await handle(new Request(`http://${request.headers.host}${request.url}`, { method: request.method, headers: request.headers as HeadersInit, ...body } as RequestInit));
454
+ response.writeHead(answer.status, Object.fromEntries(answer.headers));
455
+ response.end(Buffer.from(await answer.arrayBuffer()));
456
+ });
457
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
458
+
459
+ const { port } = server.address() as { port: number };
460
+ const storage = remoteStorage({ url: `http://127.0.0.1:${port}/saves`, headers: { authorization: 'Bearer secret' } });
461
+ await storage.write('slot-1', new Uint8Array([1, 2, 3]));
462
+ console.log(await storage.keys()); // ['slot-1']
463
+ await storage.delete('slot-1');
464
+ server.close();
465
+ ```
466
+
467
+ With no `authorize`, anyone who reaches the handler can read and write every save, so a public server needs it. Other
468
+ options: `allowHeaders` for CORS and `maxBytes`, default 64 MiB, which a body is read only up to, sent with a length or
469
+ without one. Any other server works when it sends strong ETags and
470
+ honours `If-Match` and `If-None-Match`, and `keys()` needs its JSON list. Apache with mod_dav was tested: it sends no ETag
471
+ with a PUT, so a GET follows, and for about a second after a change it gives a weak tag, so a second write inside that
472
+ second is refused.
473
+
474
+ `safeStorage(remoteStorage(...))` and `SaveSlots` run over it.
475
+
476
+ ## Validation and migrations
477
+
478
+ `validateSave(document, {components, strictComponents})` never throws and lists every problem with its path and fix
479
+ (`entities[3].parent: 'door' is not an entity of this document`): shape, duplicate ids, parent cycles, references,
480
+ unknown or cyclic prefabs, overrides of entities a prefab does not have, non-JSON values, and your component checks
481
+ (`components: {health: (v) => typeof v === 'object' ? null : 'must be {hp, max}'}`). `parseSave` returns a fresh
482
+ copy or throws a `TypeError` naming the first problem.
483
+
484
+ `new Migrations(latest).register(from, step)` holds one step per version; `migrate(document)` runs them in order on
485
+ a deep copy and checks each step returns the next version. A missing step, a step that throws or returns the wrong
486
+ version is `MargoError` `'failed'` naming it; a save newer than the game is a `RangeError`.
487
+
488
+ ## Bytes and storage
489
+
490
+ `encodeSave(document, {compress, signal})` gives UTF-8 JSON, gzipped with `compress: true` (CompressionStream, in
491
+ browsers and Node 18+); `decodeSave(bytes, {signal, maxBytes})` reads either, and stops gzip data that decompresses past
492
+ `maxBytes` (default 268435456, 256 MiB) with a RangeError, so a small hostile file cannot fill memory. Storage adapters
493
+ share one interface, `read`, `write`,
494
+ `delete` and `keys`, each async with `{signal}`:
495
+
496
+ | Adapter | Where | Atomic write |
497
+ | --- | --- | --- |
498
+ | `memoryStorage()` | a Map (tests, servers, undo snapshots) | yes |
499
+ | `webStorage(storage = localStorage, prefix = 'margo-save:')` | Web Storage, base64; about 5 MB per origin | one `setItem` |
500
+ | `indexedDBStorage({database, store, factory})` | IndexedDB, binary, large; several stores in one database each get theirs (the database is opened one version up to add a store, and a connection closes when another needs a newer version) | one transaction |
501
+ | `opfsStorage({namespace, directory})` from `margoengine/save/opfs` | the origin private file system, one file per key | temporary stream swapped in on close |
502
+ | `fileStorage(directory, {maxBytes})` from `margoengine/save/node` | one file per key | temporary file, made exclusively, renamed into place; a read refuses a file past `maxBytes` (default 256 MiB) from its size, before reading it; one writer per folder; `keys()` lists only file names it writes; on Windows a save another program has open cannot be replaced, so the write rejects and the old save stands |
503
+
504
+ A full Web Storage or a failed transaction throws `MargoError` `'failed'` and keeps the previous save; a missing
505
+ API throws `'unsupported'`. `saveGame` never writes an invalid document.
506
+
507
+ Apache-2.0. Optional, tree-shakable package. Only `/engine` uses core, as an optional peer (`/slots`, `/safe` and `/remote` need none of them), with `@margoengine/gltf/pbr` and `@margoengine/animation` loaded when a save holds a model.
508
+
509
+ Build and unit tests: npm test --workspace @margoengine/save. Real GPU, models, thumbnails, IndexedDB and cross-origin fetch: npm run test:gpu --workspace @margoengine/save
510
+
511
+ ### Scene of the result
512
+
513
+ `restoreScene`'s default model loader loads each model into the `scene` being restored, not into whichever scene is active when the load finishes. An abort or a failure leaves nothing in either scene.
@@ -0,0 +1,25 @@
1
+ /** Options of {@link encodeSave}. */
2
+ export interface EncodeOptions {
3
+ /** Gzip the JSON (default false). Saves of repetitive worlds shrink several times. */
4
+ compress?: boolean;
5
+ /** Stops the work; the promise rejects with the signal's reason. */
6
+ signal?: AbortSignal;
7
+ }
8
+ /** A save document (or any JSON value) as bytes: UTF-8 JSON, gzipped with `compress: true`. */
9
+ export declare function encodeSave(document: unknown, options?: EncodeOptions): Promise<Uint8Array>;
10
+ /** Options of {@link decodeSave}. */
11
+ export interface DecodeOptions {
12
+ /** Stops the work; the promise rejects with the signal's reason. */
13
+ signal?: AbortSignal;
14
+ /**
15
+ * Largest decompressed size accepted, in bytes. Default 268435456 (256 MiB). A gzip member can expand about a
16
+ * thousand times, so a small hostile file would otherwise fill memory before the JSON is ever read.
17
+ */
18
+ maxBytes?: number;
19
+ }
20
+ /**
21
+ * Bytes written by {@link encodeSave} (gzipped or not) back to a JSON value. Validate it with `parseSave` before use.
22
+ * @throws TypeError when the bytes are not a save (damaged gzip, not UTF-8 JSON), naming the fix.
23
+ * @throws RangeError when gzip data decompresses past `maxBytes`.
24
+ */
25
+ export declare function decodeSave(bytes: Uint8Array, options?: DecodeOptions): Promise<unknown>;
@@ -0,0 +1,51 @@
1
+ import { type Json, type SavedEntity, type SaveDocument, type ValidateOptions } from './document.js';
2
+ /** The changes from a base document to an edited one. Plain JSON: `JSON.stringify` it to keep it. */
3
+ export interface SaveDelta {
4
+ format: 'margo-save-delta';
5
+ /** Delta schema version, 1. */
6
+ version: 1;
7
+ /** The base document's `version`, so a delta is not applied to a document of another schema. */
8
+ baseVersion: number;
9
+ /** Entities that did not exist in the base, in the edited document's order. */
10
+ added: SavedEntity[];
11
+ /** Ids of base entities the edit deleted. */
12
+ removed: string[];
13
+ /** Merge patches by entity id: `name`, `parent`, `transform`, `components`, `prefab`, `overrides`; `null` removes a field. */
14
+ changed: Record<string, Json>;
15
+ /** A merge patch of the document's `meta`, when it changed. */
16
+ meta?: Json;
17
+ }
18
+ /** Options of {@link applyDelta}. */
19
+ export interface ApplyDeltaOptions extends ValidateOptions {
20
+ /** Validate the result with `parseSave`, which throws a TypeError naming the first problem. Default true. */
21
+ validate?: boolean;
22
+ }
23
+ /**
24
+ * What a user did to a loaded document, as a delta. Entities are matched by id. Reordering the list is not recorded.
25
+ * @throws TypeError for a duplicate id, or a changed value that holds `null` (see `SaveDelta`).
26
+ */
27
+ export declare function diffSave(base: SaveDocument, edited: SaveDocument): SaveDelta;
28
+ /** True when the delta changes nothing. */
29
+ export declare const isEmptyDelta: (delta: SaveDelta) => boolean;
30
+ /**
31
+ * Applies a delta to a document and returns the result; `base` is not changed. A delta made from another base fails
32
+ * loudly: an id it removes or changes must exist, an id it adds must not, and `baseVersion` must match.
33
+ * @throws TypeError naming the id or the validation problem.
34
+ */
35
+ export declare function applyDelta(base: SaveDocument, delta: SaveDelta, options?: ApplyDeltaOptions): SaveDocument;
36
+ /**
37
+ * Remembers a base document and turns the scene's current document into a delta on demand. `changes(current)` is the
38
+ * delta since the base (or since the last `commit`); `apply(delta)` re-applies a saved delta to the base.
39
+ */
40
+ export declare class SaveRecorder {
41
+ private snapshot;
42
+ constructor(base: SaveDocument);
43
+ /** The document the delta is measured from. */
44
+ get base(): SaveDocument;
45
+ /** What changed from the base to `current`. */
46
+ changes(current: SaveDocument): SaveDelta;
47
+ /** Makes `current` the new base, after its changes were saved: the next `changes` is measured from here. */
48
+ commit(current: SaveDocument): this;
49
+ /** Applies a delta (for example one loaded from storage) to the base. */
50
+ apply(delta: SaveDelta, options?: ApplyDeltaOptions): SaveDocument;
51
+ }