@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/dist/delta.js ADDED
@@ -0,0 +1,114 @@
1
+ import { n as e, s as t } from "./prefab-DeWmT5ey.js";
2
+ //#region src/delta.ts
3
+ var n = (e) => typeof e == "object" && !!e && !Array.isArray(e);
4
+ function r(e, t) {
5
+ if (e === t) return !0;
6
+ if (Array.isArray(e)) return Array.isArray(t) && e.length === t.length && e.every((e, n) => r(e, t[n]));
7
+ if (n(e)) {
8
+ if (!n(t)) return !1;
9
+ let i = Object.keys(e);
10
+ return i.length === Object.keys(t).length && i.every((n) => n in t && r(e[n], t[n]));
11
+ }
12
+ return !1;
13
+ }
14
+ function i(e, t) {
15
+ if (e === null) throw TypeError(`${t} is null, which a merge patch cannot store; use a missing key or another value for "none"`);
16
+ if (Array.isArray(e)) e.forEach((e, n) => i(e, `${t}[${n}]`));
17
+ else if (n(e)) for (let [n, r] of Object.entries(e)) i(r, `${t}.${n}`);
18
+ }
19
+ function a(e, t, o) {
20
+ if (!r(e, t)) {
21
+ if (t === void 0) return null;
22
+ if (n(e) && n(t)) {
23
+ let n = {};
24
+ for (let r of Object.keys(t)) {
25
+ let i = a(e[r], t[r], `${o}.${r}`);
26
+ i !== void 0 && (n[r] = i);
27
+ }
28
+ for (let r of Object.keys(e)) r in t || (n[r] = null);
29
+ return n;
30
+ }
31
+ return i(t, o), t;
32
+ }
33
+ }
34
+ var o = (e) => e, s = (e) => Object.fromEntries(Object.entries(o(e)).filter(([e]) => e !== "id"));
35
+ function c(e, t) {
36
+ let n = (e, t) => {
37
+ let n = /* @__PURE__ */ new Map();
38
+ for (let r of e.entities) {
39
+ if (n.has(r.id)) throw TypeError(`${t} has two entities with id "${r.id}"; ids must be unique`);
40
+ n.set(r.id, r);
41
+ }
42
+ return n;
43
+ }, r = n(e, "the base document"), c = n(t, "the edited document"), l = {
44
+ format: "margo-save-delta",
45
+ version: 1,
46
+ baseVersion: e.version,
47
+ added: [],
48
+ removed: [],
49
+ changed: {}
50
+ };
51
+ for (let [e, t] of c) {
52
+ let n = r.get(e);
53
+ if (!n) {
54
+ i(o(t), `entity "${e}"`), l.added.push(structuredClone(t));
55
+ continue;
56
+ }
57
+ let c = a(s(n), s(t), `entity "${e}"`);
58
+ c !== void 0 && (l.changed[e] = c);
59
+ }
60
+ for (let e of r.keys()) c.has(e) || l.removed.push(e);
61
+ let u = a(e.meta ?? {}, t.meta ?? {}, "meta");
62
+ return u !== void 0 && (l.meta = u), l;
63
+ }
64
+ var l = (e) => !e.added.length && !e.removed.length && !Object.keys(e.changed).length && e.meta === void 0;
65
+ function u(r, i, a = {}) {
66
+ if (!n(i) || i.format !== "margo-save-delta" || i.version !== 1) throw TypeError("applyDelta needs a delta made by diffSave: {format: 'margo-save-delta', version: 1, ...}");
67
+ if (i.baseVersion !== r.version) throw TypeError(`the delta was made for document version ${i.baseVersion}, not ${r.version}; migrate the base first`);
68
+ let o = new Map(r.entities.map((e) => [e.id, structuredClone(e)]));
69
+ for (let e of i.removed) if (!o.delete(e)) throw TypeError(`the delta removes "${e}", which the base does not have; it was made from another document`);
70
+ for (let [t, n] of Object.entries(i.changed)) {
71
+ let r = o.get(t);
72
+ if (!r) throw TypeError(`the delta changes "${t}", which the base does not have; it was made from another document`);
73
+ let i = e(s(r), n);
74
+ o.set(t, {
75
+ id: t,
76
+ ...i
77
+ });
78
+ }
79
+ for (let e of i.added) {
80
+ if (o.has(e.id)) throw TypeError(`the delta adds "${e.id}", which the base already has; it was made from another document`);
81
+ o.set(e.id, structuredClone(e));
82
+ }
83
+ let c = {
84
+ ...structuredClone({
85
+ ...r,
86
+ entities: []
87
+ }),
88
+ entities: [...o.values()]
89
+ };
90
+ if (i.meta !== void 0) {
91
+ let t = e(r.meta ?? {}, i.meta);
92
+ n(t) && Object.keys(t).length ? c.meta = t : delete c.meta;
93
+ }
94
+ return a.validate === !1 ? c : t(c, a);
95
+ }
96
+ var d = class {
97
+ constructor(e) {
98
+ this.snapshot = structuredClone(e);
99
+ }
100
+ get base() {
101
+ return this.snapshot;
102
+ }
103
+ changes(e) {
104
+ return c(this.snapshot, e);
105
+ }
106
+ commit(e) {
107
+ return this.snapshot = structuredClone(e), this;
108
+ }
109
+ apply(e, t) {
110
+ return u(this.snapshot, e, t);
111
+ }
112
+ };
113
+ //#endregion
114
+ export { d as SaveRecorder, u as applyDelta, c as diffSave, l as isEmptyDelta };
@@ -0,0 +1,90 @@
1
+ import type { Quat, Vec3 } from '@margoengine/math';
2
+ export type { Quat, Vec3 };
3
+ /** Any JSON value. */
4
+ export type Json = null | boolean | number | string | Json[] | {
5
+ [key: string]: Json;
6
+ };
7
+ /** A reference to another entity by its stable id, anywhere inside a component value. */
8
+ export interface EntityRef {
9
+ $ref: string;
10
+ }
11
+ /** Local transform of an entity, relative to its parent. Every field is optional (identity). */
12
+ export interface SavedTransform {
13
+ position?: Vec3;
14
+ /** Unit quaternion `[x, y, z, w]`. */
15
+ rotation?: Quat;
16
+ scale?: Vec3;
17
+ }
18
+ /** One entity. `id` is stable: references, parents and prefab overrides use it. */
19
+ export interface SavedEntity {
20
+ /** Stable id, unique in its list. Expanded prefab entities get `instance/local` ids; a clash with one is an error. */
21
+ id: string;
22
+ name?: string;
23
+ /** Id of the parent entity. */
24
+ parent?: string;
25
+ transform?: SavedTransform;
26
+ /** Component data by component name; values are JSON and may hold `{"$ref": id}` references. */
27
+ components?: Record<string, Json>;
28
+ /** Make this entity an instance of the prefab with this key. Its own fields override the prefab root's. */
29
+ prefab?: string;
30
+ /**
31
+ * Changes to the prefab's entities by their prefab-local id, as JSON Merge Patches of an entity (objects merge,
32
+ * other values replace, `null` removes; `null` for a whole entity removes it and its children).
33
+ */
34
+ overrides?: Record<string, Json>;
35
+ }
36
+ /** A reusable group of entities. Ids are local to the prefab; `root` (default the first entity) is the instance. */
37
+ export interface PrefabDefinition {
38
+ root?: string;
39
+ entities: SavedEntity[];
40
+ }
41
+ /** A saved scene or world. `version` is your schema version, raised with {@link Migrations}. */
42
+ export interface SaveDocument {
43
+ format: 'margo-save';
44
+ /** Your schema version, a whole number of 1 or more. */
45
+ version: number;
46
+ entities: SavedEntity[];
47
+ /** Prefab definitions by key. */
48
+ prefabs?: Record<string, PrefabDefinition>;
49
+ /** Anything else to keep with the save (a title, a play time, a thumbnail URL); JSON. */
50
+ meta?: Record<string, Json>;
51
+ }
52
+ /** One problem found by {@link validateSave}: where (`entities[3].parent`) and what to change. */
53
+ export interface SaveIssue {
54
+ path: string;
55
+ message: string;
56
+ }
57
+ /** Checks one component value: return a message naming the fix, or nothing when it is valid. */
58
+ export type ComponentCheck = (value: Json) => string | undefined | null | void;
59
+ /** Options of {@link validateSave} and {@link parseSave}. */
60
+ export interface ValidateOptions {
61
+ /** Checks by component name. Components without a check accept any JSON. */
62
+ components?: Readonly<Record<string, ComponentCheck>>;
63
+ /** Reject components that have no check (default false). */
64
+ strictComponents?: boolean;
65
+ }
66
+ /** Deepest prefab nesting accepted. */
67
+ export declare const MAX_PREFAB_DEPTH = 32;
68
+ /** Most entities a document may expand to. */
69
+ export declare const MAX_ENTITIES = 1000000;
70
+ /** Deepest JSON nesting accepted in a component value. */
71
+ export declare const MAX_JSON_DEPTH = 64;
72
+ /** Every `{"$ref": id}` inside a JSON value, with its path. */
73
+ export declare function findRefs(value: Json, path?: string, out?: {
74
+ path: string;
75
+ id: string;
76
+ }[]): {
77
+ path: string;
78
+ id: string;
79
+ }[];
80
+ /**
81
+ * Check a save document without loading it: shape, ids, parents (and parent cycles), references, prefabs (unknown,
82
+ * cyclic or too deep), overrides naming prefab entities that do not exist, and component checks. Returns every
83
+ * problem with its path and the fix; empty means valid. Never throws, whatever the input.
84
+ */
85
+ export declare function validateSave(input: unknown, options?: ValidateOptions): SaveIssue[];
86
+ /**
87
+ * Read a save document (JSON text or an object), checked with {@link validateSave}. Returns a fresh copy.
88
+ * @throws TypeError naming the first problem's path and fix, or for text that is not JSON.
89
+ */
90
+ export declare function parseSave(input: string | unknown, options?: ValidateOptions): SaveDocument;
@@ -0,0 +1,113 @@
1
+ // @ts-ignore optional peer: its types apply when it is installed
2
+ import { type EngineKernel, type EnginePlugin, type Mesh, type Scene } from '@margoengine/core';
3
+ import { type Json, type SaveDocument, type ValidateOptions } from './document.js';
4
+ import type { Migrations } from './migrations.js';
5
+ import { type ResolvedEntity } from './prefab.js';
6
+ /** The part of a glTF model the binding reads; `PBRModel` of `@margoengine/gltf/pbr` is one. */
7
+ export interface ModelLike extends EnginePlugin {
8
+ readonly root: Mesh;
9
+ readonly nodes: readonly Mesh[];
10
+ /** Every mesh the model owns, when it makes more than `root` and `nodes`. */
11
+ readonly ownedMeshes?: readonly Mesh[];
12
+ readonly asset: {
13
+ readonly baseURL?: string;
14
+ readonly doc?: {
15
+ nodes?: readonly unknown[];
16
+ };
17
+ };
18
+ readonly selectedVariant?: number;
19
+ selectVariant?(variant?: number): void;
20
+ dispose(): void;
21
+ }
22
+ /**
23
+ * How one plugin is saved, for a plugin that needs more than the default. By default a plugin's own `saveState()` and
24
+ * `loadState(state)` are used, else its JSON `options` and every property with both a getter and a setter.
25
+ */
26
+ export interface PluginBinding<P extends EnginePlugin = EnginePlugin> {
27
+ /** The class, to attach the plugin with its saved `options` when a restored scene does not have it. */
28
+ type?: {
29
+ attach(engine: EngineKernel, options?: never): EnginePlugin;
30
+ };
31
+ /** Properties to save, in place of the getter and setter pairs. Public fields such as `time` go here. */
32
+ properties?: readonly string[];
33
+ /** Returns the plugin's state as JSON, in place of `properties`. */
34
+ save?(plugin: P): Json;
35
+ /** Applies what `save` returned. A throw undoes the whole restore. */
36
+ load?(plugin: P, state: Json): void;
37
+ }
38
+ /** Bindings by plugin name; `null` leaves a plugin out. */
39
+ export type PluginBindings = Readonly<Record<string, PluginBinding<never> | null>>;
40
+ /** Options of {@link captureScene}. */
41
+ export interface CaptureOptions {
42
+ /** The scene to save. Default `engine.scene`. */
43
+ scene?: Scene;
44
+ /** Your schema version, for `Migrations`. Default 1. */
45
+ version?: number;
46
+ /** Anything else to keep with the save: a title, a play time. The key `engine` is the binding's. */
47
+ meta?: Record<string, Json>;
48
+ /** Save the camera. Default true. */
49
+ camera?: boolean;
50
+ /** Bindings for plugins the default does not fit. Default none. */
51
+ plugins?: PluginBindings;
52
+ /** False leaves a mesh out, and everything under it. Default every mesh. */
53
+ filter?(mesh: Mesh): boolean;
54
+ /** Components of your own for a mesh or model root. Default none. */
55
+ components?(mesh: Mesh): Record<string, Json> | undefined;
56
+ /** The address of a model that was not loaded from a URL. Default `model.asset.baseURL`. */
57
+ modelURL?(model: ModelLike): string | undefined;
58
+ /** Called for each plugin left out because nothing in it could be read. Default none. */
59
+ onSkip?(plugin: EnginePlugin): void;
60
+ }
61
+ /** Options of {@link restoreScene}. */
62
+ export interface RestoreOptions extends ValidateOptions {
63
+ /** The scene to restore into. Default `engine.scene`. */
64
+ scene?: Scene;
65
+ /** Brings an older save to the current schema version first. Default none. */
66
+ migrations?: Migrations;
67
+ /** Remove what the scene holds once the new one is in: meshes that `filter` keeps, and models. Default true. */
68
+ clear?: boolean;
69
+ /** Restore the camera. Default true. */
70
+ camera?: boolean;
71
+ /** Bindings by plugin name, as for {@link captureScene}. Default none. */
72
+ plugins?: PluginBindings;
73
+ /** The meshes `clear` removes: false keeps a mesh and everything under it. Default every mesh. */
74
+ filter?(mesh: Mesh): boolean;
75
+ /** Called once per entity after all exist, for your own components. A throw undoes the whole restore. */
76
+ onEntity?(mesh: Mesh, entity: ResolvedEntity, get: (id: string) => Mesh): void;
77
+ /** Loads a model. Default `loadGLTF` of `@margoengine/gltf/pbr`. */
78
+ load?(url: string, options: {
79
+ signal?: AbortSignal;
80
+ }): Promise<ModelLike>;
81
+ /** Makes another copy of a loaded model, for a URL used twice. Default `cloneModel` of `@margoengine/animation`. */
82
+ clone?(model: ModelLike): Promise<ModelLike>;
83
+ /** Stops the restore before the swap; nothing stays built. */
84
+ signal?: AbortSignal;
85
+ }
86
+ /** What {@link restoreScene} returns. */
87
+ export interface RestoredScene {
88
+ /** One mesh per entity, by entity id; a model's is its `root`. */
89
+ readonly meshes: ReadonlyMap<string, Mesh>;
90
+ /** The models, by entity id. */
91
+ readonly models: ReadonlyMap<string, ModelLike>;
92
+ /** The document's `meta`, without the binding's own key. */
93
+ readonly meta: Readonly<Record<string, Json>>;
94
+ }
95
+ /** The id `mesh` has in saves, once a capture or a restore has given it one. It stays the same across saves. */
96
+ export declare function meshId(mesh: Mesh): string | undefined;
97
+ /**
98
+ * The scene as a save document, with no mapping to write: every mesh with its transform, parent, geometry and
99
+ * material; every glTF model as its URL, material variant and the nodes that moved; the camera, lighting and
100
+ * background; and each plugin's state. Write it with `saveGame`, load it with {@link restoreScene}.
101
+ * @throws TypeError when a model has no URL (pass `modelURL`), or a `components` key is one the binding uses.
102
+ * @example await saveGame(storage, 'slot-1', captureScene(engine));
103
+ */
104
+ export declare function captureScene(engine: EngineKernel, options?: CaptureOptions): SaveDocument;
105
+ /**
106
+ * Loads a save into the running scene, all or nothing: validates and migrates it, loads its models out of sight, builds
107
+ * every mesh, and only then applies plugin state, camera and lighting and removes what the scene held. Any failure
108
+ * before that point leaves the scene as it was. A plugin the scene lacks is attached through its binding's `type`.
109
+ * @throws TypeError for an invalid document or a plugin with no `type`; MargoError `'failed'` with the `cause` when a
110
+ * step fails; the signal's reason when it aborts.
111
+ * @example await restoreScene(engine, await loadGame(storage, 'slot-1'));
112
+ */
113
+ export declare function restoreScene(engine: EngineKernel, document: SaveDocument | unknown, options?: RestoreOptions): Promise<RestoredScene>;