threedog 0.1.0 → 0.2.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/core/Animator.js +1 -0
- package/core/Assets.js +16 -0
- package/core/DebugOverrides.js +143 -0
- package/core/Describe.js +14 -3
- package/core/Engine.js +32 -69
- package/core/Events.js +59 -1
- package/core/I18n.js +2 -2
- package/core/Inspect.js +12 -32
- package/core/InspectScene.js +7 -3
- package/core/MaterialInfo.js +32 -0
- package/core/Ops.js +43 -59
- package/core/Saves.js +5 -4
- package/core/UrlState.js +3 -2
- package/core/Vars.js +1 -0
- package/core/Views.js +49 -0
- package/core/actor.js +2 -2
- package/core/assetReport.js +83 -0
- package/core/catalog.js +169 -0
- package/core/checks.js +67 -0
- package/core/claims.js +51 -0
- package/core/debugView.js +76 -0
- package/core/describeRender.js +45 -0
- package/core/describeText.js +11 -4
- package/core/errorCodes.js +33 -0
- package/core/errorHints.js +6 -1
- package/core/holds.js +106 -0
- package/core/lifecycle.js +1 -0
- package/core/lightWatch.js +23 -3
- package/core/look/coreParts.js +112 -0
- package/core/look/layers.js +136 -0
- package/core/look/part.js +173 -0
- package/core/look/report.js +79 -0
- package/core/look/write.js +86 -0
- package/core/loop.js +15 -14
- package/core/modules.js +19 -5
- package/core/opsAtomic.js +31 -0
- package/core/opsCheck.js +25 -14
- package/core/opsFail.js +20 -0
- package/core/opsHistory.js +6 -6
- package/core/opsRun.js +77 -0
- package/core/params.js +132 -0
- package/core/renamed.js +21 -0
- package/core/saveApply.js +2 -2
- package/core/sceneMethods.js +9 -34
- package/core/services.js +73 -0
- package/core/startup.js +3 -1
- package/core/styleParts.js +2 -2
- package/core/thingExplain.js +68 -0
- package/core/thingOps.js +35 -24
- package/core/things.js +15 -1
- package/core/util.js +11 -0
- package/core/validate.js +23 -7
- package/docs/AI.md +83 -109
- package/docs/API.md +7 -8
- package/docs/CODEMAP.md +63 -51
- package/docs/COMMANDS.md +17 -5
- package/docs/CONVENTIONS.md +17 -6
- package/docs/THREE.md +3 -3
- package/docs/api/assets.md +2 -0
- package/docs/api/characters.md +2 -0
- package/docs/api/collision.md +4 -0
- package/docs/api/content.md +1 -0
- package/docs/api/engine.md +20 -11
- package/docs/api/events.md +5 -1
- package/docs/api/post.md +5 -4
- package/docs/api/saves.md +2 -1
- package/docs/api/sky.md +3 -3
- package/docs/api/style.md +3 -3
- package/docs/api/tools.md +2 -0
- package/docs/api/weather.md +1 -1
- package/docs/recipes/02-npc.md +16 -0
- package/docs/recipes/03-items-pickups.md +1 -1
- package/docs/recipes/06-clock-events.md +13 -0
- package/docs/recipes/07-flow-scenes-pause.md +4 -0
- package/docs/recipes/08-weather-sky.md +1 -1
- package/docs/recipes/09-style-pack.md +5 -5
- package/docs/recipes/12-navmesh.md +22 -0
- package/docs/recipes/13-animation.md +3 -0
- package/docs/recipes/15-perf.md +1 -1
- package/docs/recipes/16-dev-bridge.md +51 -17
- package/docs/recipes/21-camera.md +51 -2
- package/docs/recipes/23-ops.md +45 -9
- package/docs/recipes/27-net.md +1 -1
- package/docs/recipes/29-grid.md +1 -1
- package/docs/recipes/34-environment-lighting.md +9 -8
- package/docs/recipes/38-environment-look-hooks.md +8 -6
- package/docs/recipes/40-scene.md +29 -0
- package/docs/recipes/41-thing-registry.md +29 -0
- package/docs/recipes/43-shader-patches-surface-looks.md +2 -0
- package/docs/recipes/44-water-weather-look-hooks.md +6 -4
- package/docs/recipes/45-cascaded-shadows.md +1 -1
- package/docs/recipes/46-blender-art-route.md +22 -0
- package/docs/recipes/48-make-material.md +70 -0
- package/docs/recipes/49-game-module-contract.md +71 -0
- package/docs/recipes/50-own-renderer.md +12 -0
- package/docs/recipes/51-capability-catalog.md +63 -0
- package/docs/recipes/52-look.md +108 -0
- package/examples/action/GAMEMAP.md +5 -5
- package/examples/action/content/index.js +2 -1
- package/examples/action/content/views.js +6 -0
- package/examples/sheepisland/GAMEMAP.md +2 -3
- package/examples/styletest/GAMEMAP.md +3 -3
- package/examples/styletest/main.js +1 -1
- package/examples/styletest/panel.js +3 -3
- package/examples/world/GAMEMAP.md +3 -3
- package/index.d.ts +27 -0
- package/index.js +3 -1
- package/llms.txt +5 -0
- package/modules/ambience/Ambience.js +5 -2
- package/modules/camera/FirstPersonCamera.js +3 -5
- package/modules/camera/FixedCamera.js +19 -12
- package/modules/camera/FollowCamera.js +14 -8
- package/modules/camera/RtsCamera.js +3 -5
- package/modules/camera/common.js +40 -10
- package/modules/camera/index.js +1 -1
- package/modules/camera/projection.js +34 -0
- package/modules/characters/Character.js +29 -17
- package/modules/characters/astar.js +14 -7
- package/modules/characters/index.js +6 -3
- package/modules/characters/movers/simple.js +6 -1
- package/modules/characters/npcSim.js +8 -2
- package/modules/characters/pathAsync.js +12 -6
- package/modules/characters/pathJob.js +2 -1
- package/modules/characters/proceduralRig.js +5 -1
- package/modules/characters/useModel.js +22 -0
- package/modules/characters/walkTo.js +58 -0
- package/modules/collision/Collision.js +102 -4
- package/modules/content/explain.js +13 -0
- package/modules/content/index.js +2 -0
- package/modules/content/loader.js +3 -0
- package/modules/content/rules.js +1 -0
- package/modules/debug/DebugPanel.js +11 -5
- package/modules/entities/Entities.js +6 -2
- package/modules/flow/index.js +5 -2
- package/modules/gameplay/Dialogue.js +5 -2
- package/modules/gameplay/Interactions.js +12 -2
- package/modules/gameplay/Inventory.js +21 -11
- package/modules/gameplay/Quests.js +13 -3
- package/modules/gameplay/pickups.js +5 -3
- package/modules/grid/Layer.js +1 -1
- package/modules/grid/index.js +1 -1
- package/modules/grid/tiles.js +9 -5
- package/modules/hlod/index.js +5 -2
- package/modules/hud/index.js +5 -2
- package/modules/level/index.js +5 -3
- package/modules/lights/index.js +5 -2
- package/modules/music/Music.js +6 -2
- package/modules/nav/index.js +5 -3
- package/modules/net/Client.js +4 -3
- package/modules/net/Host.js +2 -2
- package/modules/net/index.js +5 -3
- package/modules/particles/Particles.js +1 -1
- package/modules/photo/Photo.js +10 -7
- package/modules/rigid/RigidBodies.js +5 -2
- package/modules/settings/Settings.js +6 -3
- package/modules/settings/apply.js +2 -1
- package/modules/sky/Sky.js +21 -19
- package/modules/sky/cascades.js +6 -6
- package/modules/sky/domeLayers.js +1 -1
- package/modules/sky/environment.js +39 -13
- package/modules/sky/fog.js +9 -6
- package/modules/sky/frame.js +4 -3
- package/modules/sky/look.js +3 -2
- package/modules/sky/lookFog.js +80 -0
- package/modules/sky/lookShadow.js +50 -0
- package/modules/sky/lookSky.js +108 -0
- package/modules/sky/shader.js +2 -2
- package/modules/sky/shadow.js +4 -10
- package/modules/sky/skyModule.js +4 -3
- package/modules/terrain/ChunkManager.js +2 -33
- package/modules/terrain/chunkLevels.js +40 -0
- package/modules/terrain/index.js +10 -2
- package/modules/terrain/lookGround.js +61 -0
- package/modules/timeline/Timeline.js +7 -3
- package/modules/timeline/Tween.js +3 -7
- package/modules/timeline/shots.js +6 -4
- package/modules/triggers/index.js +9 -2
- package/modules/vegetation/Vegetation.js +2 -1
- package/modules/vegetation/index.js +6 -3
- package/modules/vegetation/lookWind.js +37 -0
- package/modules/water/Water.js +19 -3
- package/modules/water/look.js +80 -0
- package/modules/weather/Weather.js +22 -31
- package/modules/weather/look.js +75 -0
- package/modules/weather/particles.js +1 -1
- package/modules/weather/strings.js +15 -0
- package/modules/world/explain.js +11 -0
- package/modules/world/index.js +11 -4
- package/modules/world/thingSource.js +44 -0
- package/package.json +1 -1
- package/render/PostFX.js +48 -51
- package/render/effects.js +4 -2
- package/render/fuse.js +12 -0
- package/render/lights.js +4 -2
- package/render/lookSurface.js +161 -0
- package/render/materials.js +27 -10
- package/render/postLook.js +86 -0
- package/render/surface.js +3 -1
- package/types/core.d.ts +216 -24
- package/types/gameplay.d.ts +10 -0
- package/types/generated/core/DebugOverrides.d.ts +52 -0
- package/types/generated/core/Events.d.ts +43 -0
- package/types/generated/core/Ops.d.ts +62 -21
- package/types/generated/core/Saves.d.ts +1 -0
- package/types/generated/core/Views.d.ts +33 -0
- package/types/generated/modules/debug/DebugPanel.d.ts +2 -2
- package/types/generated/modules/grid/Layer.d.ts +1 -0
- package/types/generated/modules/sky/Sky.d.ts +10 -17
- package/types/generated/modules/weather/Weather.d.ts +5 -15
- package/types/generated/render/PostFX.d.ts +20 -23
- package/types/generated/render/materials.d.ts +10 -0
- package/types/physics.d.ts +8 -0
- package/types/style.d.ts +16 -6
- package/ui/Parts.js +6 -2
- package/ui/UI.js +1 -1
- package/ui/defaults.js +1 -1
- package/docs/api/debug.md +0 -10
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// describe().look, catalog('look.*').
|
|
2
|
+
// Both read the same layer records (part.js), so "who set this"
|
|
3
|
+
// in describe and "what can I set" in the catalog cannot disagree. Values set straight on the three.js object (renderer.toneMappingExposure = 2)
|
|
4
|
+
// show up as by: 'three': the part's read() returns the live value and it no longer matches what the layers say.
|
|
5
|
+
import { schemaInfo } from '../params.js';
|
|
6
|
+
import { r1 } from '../math.js';
|
|
7
|
+
|
|
8
|
+
const shown = v => (typeof v === 'number' ? r1(v) : typeof v === 'function' ? '<function>' : Array.isArray(v) && v.length > 4 ? `<array of ${v.length}>` : v?.isObject3D || v?.isTexture || v?.isMaterial ? `<${v.type}>` : v);
|
|
9
|
+
/**
|
|
10
|
+
* Same value for the 'three' check: numbers within a small tolerance, arrays / Colors / vectors element by element. Why: the live read
|
|
11
|
+
* (a Color, a Vector2) is a different object from the layer value ([0.012, 0.006], '#fff'), and !== tagged it 'three' (review L5)
|
|
12
|
+
*/
|
|
13
|
+
function same(a, b) {
|
|
14
|
+
if (a === b) return true;
|
|
15
|
+
if (typeof a === 'number' && typeof b === 'number') return Math.abs(a - b) <= 1e-6 * Math.max(1, Math.abs(a), Math.abs(b));
|
|
16
|
+
const arr = v => (Array.isArray(v) ? v : v?.isColor ? [v.r, v.g, v.b] : typeof v?.toArray === 'function' ? v.toArray() : null);
|
|
17
|
+
const x = arr(a), y = arr(b);
|
|
18
|
+
if (x && y) return x.length === y.length && x.every((v, i) => same(v, y[i]));
|
|
19
|
+
const c = a?.isColor ? a : b?.isColor ? b : null, other = c === a ? b : a;
|
|
20
|
+
if (c && (typeof other === 'number' || /^(#|rgb|hsl)/i.test(other ?? ''))) // 'horizon' and the like are not colors: three would warn return c.clone().set(other).equals(c);
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
/** by: 'game' | 'style' | 'engine' | '<layer>:<owner>' (layer game or debug, owner as given to set / debug.override), or 'three' */
|
|
24
|
+
const tag = (s) => (s.layer === 'game' && s.owner === 'game') || s.layer === 'style' || s.layer === 'engine' ? s.layer : `${s.layer}:${s.owner}`;
|
|
25
|
+
|
|
26
|
+
/** One part's keys: { key: { value, by, at?, under? } }; under lists the layers this value covers (top first) */
|
|
27
|
+
function partInfo(p) {
|
|
28
|
+
const live = p._spec.read?.() ?? {}, out = {};
|
|
29
|
+
for (const k of p._keys()) {
|
|
30
|
+
const s = p._source(k);
|
|
31
|
+
if (!s) continue;
|
|
32
|
+
const o = { value: shown(s.value), by: tag(s) };
|
|
33
|
+
if (s.driven) Object.assign(o, { value: shown(live[k]), driver: s.owner }); // written every frame from the style: the live value is the value
|
|
34
|
+
else if (k in live && live[k] !== undefined && !same(live[k], s.value)) Object.assign(o, { value: shown(live[k]), by: 'three', layers: tag(s) });
|
|
35
|
+
if (s.at) o.at = s.at;
|
|
36
|
+
if (s.under.length && s.layer !== 'engine') o.under = s.under.map(tag);
|
|
37
|
+
out[k] = o;
|
|
38
|
+
}
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** describe().look: { <part>: { key: { value, by } }, text } (undefined when no part is registered) @param {any} e */
|
|
43
|
+
export function describeLook(e) {
|
|
44
|
+
const parts = Object.values(e.look ?? {});
|
|
45
|
+
if (!parts.length) return undefined;
|
|
46
|
+
const out = {}, lines = [];
|
|
47
|
+
for (const p of parts) {
|
|
48
|
+
const info = out[p._spec.id] = partInfo(p);
|
|
49
|
+
lines.push(`${p._spec.id}${p._spec.appliesTo ? ` (applies to ${p._spec.appliesTo})` : ''}:${Object.entries(info).map(([k, v]) => `${k}=${typeof v.value === 'object' && v.value ? JSON.stringify(v.value) : v.value} (${v.by})`).join(' ')}`);
|
|
50
|
+
}
|
|
51
|
+
return { ...out, text: lines.join('\n') };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** One part as catalog data: params (schema + why / off / cost + value in use and its source), hooks, replace contract, verbs */
|
|
55
|
+
function lookEntry(e, p) {
|
|
56
|
+
const s = p._spec, schema = schemaInfo(p._params), info = partInfo(p);
|
|
57
|
+
for (const k in schema) {
|
|
58
|
+
const m = p._meta[k];
|
|
59
|
+
for (const f of ['why', 'off', 'cost']) if (m[f] !== undefined) schema[k][f] = m[f];
|
|
60
|
+
if (m.neutral) schema[k].neutral = true;
|
|
61
|
+
if (info[k]) Object.assign(schema[k], { value: info[k].value, by: info[k].by });
|
|
62
|
+
}
|
|
63
|
+
return { id: p.id, kind: 'look', group: s.group ?? null, module: s.module ?? 'core', verbs: verbsOf(p), signatures: p.signatures, params: schema,
|
|
64
|
+
...(s.appliesTo ? { appliesTo: s.appliesTo } : {}),
|
|
65
|
+
hooks: s.hooks ?? null, replace: s.replace ?? null, ...(s.docs ? { docs: s.docs } : {}), problems: [] };
|
|
66
|
+
}
|
|
67
|
+
const verbsOf = p => ['set', ...(p._spec.hooks ? ['patch'] : []), ...(p._spec.replace ? ['replace'] : [])];
|
|
68
|
+
|
|
69
|
+
/** Short list rows for engine.catalog() (same row shape as modules: ops / saves stay empty) @param {any} e */
|
|
70
|
+
export function lookSummaries(e) {
|
|
71
|
+
return Object.values(e.look ?? {}).map(p => ({ id: p.id, kind: 'look', group: p._spec.group ?? null, module: p._spec.module ?? 'core', verbs: verbsOf(p), ops: [], saves: [] }));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** engine.catalog('look') -> every part expanded; 'look.<part>' -> that part; else null @param {any} e @param {string} id */
|
|
75
|
+
export function lookCatalog(e, id) {
|
|
76
|
+
if (id === 'look') return Object.values(e.look ?? {}).map(p => lookEntry(e, p));
|
|
77
|
+
const p = e.look?.[id.slice(5)];
|
|
78
|
+
return p ? lookEntry(e, p) : null;
|
|
79
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// How a value gets into a LookPart: normalize, flatten, check, then write one owner's layer (part.js has the verbs a game and a part author call).
|
|
2
|
+
// Why a file of its own: this is the one path set(), engine.debug.override and a style swap share, and it is the part that grows with every new
|
|
3
|
+
// kind of check; the verbs in part.js stay short and the file-size cap holds. Functions take the part as `p`; LookPart methods delegate here.
|
|
4
|
+
import { closest, warnOnce } from '../validate.js';
|
|
5
|
+
import { whyBad } from '../params.js';
|
|
6
|
+
import { codedError, coded } from '../errorHints.js';
|
|
7
|
+
import { isPlainObject } from '../util.js';
|
|
8
|
+
import { REPLACE, HOOK, callerAt, commit } from './layers.js';
|
|
9
|
+
|
|
10
|
+
/** A sample call for error texts: { <first key>: <its default> } */
|
|
11
|
+
export function example(p) { const k = Object.keys(p._params)[0]; return k ? `{ ${k}: ${JSON.stringify(p._params[k].default)} }` : '{...}'; }
|
|
12
|
+
|
|
13
|
+
/** { sun: { intensity } } -> { 'sun.intensity' } for keys the part declares dotted */
|
|
14
|
+
export function flat(p, params) {
|
|
15
|
+
const out = {}, keys = Object.keys(p._params);
|
|
16
|
+
for (const [k, v] of Object.entries(params)) {
|
|
17
|
+
if (!(k in p._params) && isPlainObject(v) && keys.some(q => q.startsWith(k + '.'))) for (const [s, sv] of Object.entries(v)) out[`${k}.${s}`] = sv;
|
|
18
|
+
else out[k] = v;
|
|
19
|
+
}
|
|
20
|
+
return out;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Unknown keys and wrong values throw with the fix (same schema and wording as module params, params.js) */
|
|
24
|
+
export function check(p, values) {
|
|
25
|
+
const keys = Object.keys(p._params);
|
|
26
|
+
for (const [k, v] of Object.entries(values)) {
|
|
27
|
+
if (!(k in p._params)) { const c = closest(k, keys); throw codedError('look-param', `${p.id}.set(): unknown key ${k}${c ? ` (did you mean ${c}?)` : ''}; keys: ${keys.join(', ')}`); }
|
|
28
|
+
if (v === null) continue;
|
|
29
|
+
const why = whyBad(p._params[k], v) ?? p._meta[k].check?.(v);
|
|
30
|
+
if (why) throw codedError('look-param', `${p.id}.set(): ${k} ${why}`);
|
|
31
|
+
}
|
|
32
|
+
return values;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** set() and engine.debug.override share this, so both normalize, flatten and check the same way (review M8) */
|
|
36
|
+
export function setOn(p, layer, owner, params) {
|
|
37
|
+
if (!isPlainObject(params)) throw codedError('look-param', `${p.id}.set(params): params is an object of keys to change, e.g. ${example(p)}; got ${JSON.stringify(params)}`);
|
|
38
|
+
const values = check(p, flat(p, p._spec.normalize?.(params) ?? params)); // normalize: a part's shorthand (post: { bloom: false })
|
|
39
|
+
const to = p._spec.appliesTo;
|
|
40
|
+
if (layer === 'debug' && to) warnOnce(coded('look-param', `${p.id}: a debug override changes only ${to}; what was made before keeps its look`));
|
|
41
|
+
return writeLayer(p, layer, owner, values);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Replace the style layer (start, or a style swap); game and debug layers stay */
|
|
45
|
+
export function setStyle(p, values) {
|
|
46
|
+
const given = Object.fromEntries(Object.entries(flat(p, values ?? {})).filter(([, v]) => v != null));
|
|
47
|
+
const params = Object.fromEntries(Object.entries(given).filter(([k]) => k !== REPLACE && !k.startsWith(HOOK))); // a style may also fill the replace slot / hooks
|
|
48
|
+
check(p, params); // a style pack value of the wrong type throws at start, with the key
|
|
49
|
+
const old = p._style;
|
|
50
|
+
p._style = new Map(Object.entries(given));
|
|
51
|
+
commit(p, () => { p._style = old; });
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Where spec.validate's answer is quoted: the verb that carried the bad value, so the fix reads as a call */
|
|
55
|
+
const quoteVerb = (p, k) => k === REPLACE ? `${p.id}.replace(impl): impl` : k.startsWith(HOOK) ? `${p.id}.patch('${k.slice(HOOK.length)}', glsl):` : `${p.id}: ${k}`;
|
|
56
|
+
|
|
57
|
+
/** Write one owner's keys on the game or debug layer. All or nothing: if apply throws, the layer and the picture go back (review H1) */
|
|
58
|
+
export function writeLayer(p, layer, owner, values) {
|
|
59
|
+
if (!owner || typeof owner !== 'string') throw codedError('look-param', `${p.id}: owner is a non-empty string naming who changes it, e.g. { owner: 'cave' }`);
|
|
60
|
+
for (const [k, v] of Object.entries(values)) { // spec.validate stops a bad hook / replace value (or any key) before anything is written
|
|
61
|
+
const why = v === null ? null : p._spec.validate?.(k, v);
|
|
62
|
+
if (why) throw codedError(k === REPLACE || k.startsWith(HOOK) ? 'look-verb' : 'look-param', `${quoteVerb(p, k)} ${why}`);
|
|
63
|
+
}
|
|
64
|
+
const map = p._owners[layer], old = map.get(owner);
|
|
65
|
+
// `at` = the owner's first write: one stack capture per owner, not per set (#14)
|
|
66
|
+
const rec = { values: new Map(old?.values), seq: ++p._seq, at: old ? old.at : callerAt() };
|
|
67
|
+
for (const [k, v] of Object.entries(values)) v === null ? rec.values.delete(k) : rec.values.set(k, v);
|
|
68
|
+
map.delete(owner); if (rec.values.size) map.set(owner, rec);
|
|
69
|
+
commit(p, () => { map.delete(owner); if (old) map.set(owner, old); });
|
|
70
|
+
return { remove: () => dropLayer(p, layer, owner) };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function dropLayer(p, layer, owner) {
|
|
74
|
+
const map = p._owners[layer], old = map.get(owner);
|
|
75
|
+
if (!old) return false;
|
|
76
|
+
map.delete(owner);
|
|
77
|
+
commit(p, () => map.set(owner, old));
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** A verb with its own call shape (spec.verbs[verb].take): take(bad, ...args) -> [values, owner]; bad(msg) throws quoting the signature */
|
|
82
|
+
export function takeVerb(p, verb, args) {
|
|
83
|
+
const sig = p.signatures[verb], bad = msg => { throw codedError('look-verb', `${p.id}.${verb}: ${msg}. Call it as ${p.id.slice(5)}.${sig}`); };
|
|
84
|
+
const [values, owner = 'game'] = p._spec.verbs[verb].take(bad, ...args);
|
|
85
|
+
return p.write(owner, values);
|
|
86
|
+
}
|
package/core/loop.js
CHANGED
|
@@ -94,20 +94,21 @@ export const loopMethods = {
|
|
|
94
94
|
return r;
|
|
95
95
|
},
|
|
96
96
|
|
|
97
|
-
// ---------- pause
|
|
98
|
-
/**
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
97
|
+
// ---------- nextFixed (pause / freeze / runState live in holds.js; step() below is the deterministic way to advance) ----------
|
|
98
|
+
/**
|
|
99
|
+
* Run fn at the start of the next fixed step (before that step's fixed hooks), from any callback (UI click, promise, worker result): gameplay state is safe to write there.
|
|
100
|
+
* Returns a Promise of fn's value (rejects if fn throws). Waits while frozen or loading. Built on engine.commits: applies in request order and survives save loads.
|
|
101
|
+
* @template T
|
|
102
|
+
* @param {() => T} fn
|
|
103
|
+
* @returns {Promise<T>}
|
|
104
|
+
* @example engine.nextFixed(() => engine.ops.run('door.open', { id: 'gate' }));
|
|
105
|
+
*/
|
|
106
|
+
nextFixed(fn) {
|
|
107
|
+
return new Promise((resolve, reject) => {
|
|
108
|
+
const t = this.commits.request({ lag: 1, valid: () => true, fallback: () => undefined, apply: () => { try { resolve(fn()); } catch (err) { reject(err); } } });
|
|
109
|
+
t.resolve(undefined); // nothing to wait for: otherwise the fallback would count as late
|
|
110
|
+
});
|
|
111
|
+
},
|
|
111
112
|
|
|
112
113
|
_loop() {
|
|
113
114
|
if (this._looping) return;
|
package/core/modules.js
CHANGED
|
@@ -22,6 +22,9 @@
|
|
|
22
22
|
import { requiresText, warnOnce, DEV, fmt } from './validate.js';
|
|
23
23
|
import { codedError, coded } from './errorHints.js';
|
|
24
24
|
import { reportError } from './errors.js';
|
|
25
|
+
import { catalog, catalogSnap, catalogClaim } from './catalog.js';
|
|
26
|
+
import { readParams } from './params.js';
|
|
27
|
+
import { disposeLooksOf } from './look/part.js';
|
|
25
28
|
|
|
26
29
|
/** Stage -> sort position */
|
|
27
30
|
const STAGES = { control: 100, world: 200, environment: 300, gameplay: 400, presentation: 450, late: 500, audio: 510 };
|
|
@@ -91,18 +94,20 @@ export const moduleMethods = {
|
|
|
91
94
|
const plan = this._planUse(mods.flat()), done = [];
|
|
92
95
|
try {
|
|
93
96
|
for (const m of plan) {
|
|
94
|
-
const had = Object.hasOwn(this, m.name), api = m.install?.(this) ?? m;
|
|
97
|
+
const had = Object.hasOwn(this, m.name), prev = this[m.name], snap = catalogSnap(this), api = m.install?.(this) ?? m;
|
|
98
|
+
catalogClaim(this, m.name, snap); // ops / save parts / describe names it registered show under it in engine.catalog()
|
|
95
99
|
this.modules.set(m.name, m);
|
|
96
100
|
if (m.name) this[m.name] = api;
|
|
97
|
-
done.push({ m, had });
|
|
101
|
+
done.push({ m, had, prev });
|
|
98
102
|
this._modState.set(m.name, m.init ? (this._started ? 'initializing' : 'registered') : 'running');
|
|
99
103
|
}
|
|
100
104
|
} catch (err) {
|
|
101
|
-
for (const { m, had } of done.reverse()) { // undo in reverse install order, like dispose
|
|
105
|
+
for (const { m, had, prev } of done.reverse()) { // undo in reverse install order, like dispose
|
|
102
106
|
this.modules.delete(m.name); this._modState.delete(m.name);
|
|
103
|
-
if (had) this[m.name] =
|
|
107
|
+
if (had) this[m.name] = prev; else delete this[m.name]; // put back what was there (an undefined slot stays undefined), never blank it
|
|
104
108
|
try { m.dispose?.(this); } catch { /* the install error below is the one to report */ }
|
|
105
109
|
}
|
|
110
|
+
for (const m of plan) disposeLooksOf(this, m.name); // look parts and driven keys of every module in the batch, the one that threw too (review M9)
|
|
106
111
|
this._sortHooks();
|
|
107
112
|
throw err;
|
|
108
113
|
}
|
|
@@ -124,6 +129,7 @@ export const moduleMethods = {
|
|
|
124
129
|
throw codedError('module-stage', fmt(STRINGS.stage, { name: m.name, stage: m.stage, list: Object.keys(STAGES).join(', ') }));
|
|
125
130
|
for (const dep of m.requires || []) if (!names.has(dep))
|
|
126
131
|
throw codedError('module-requires', requiresText(m.name, dep, [...names]) ?? fmt(STRINGS.needs, { name: m.name, dep }));
|
|
132
|
+
if (DEV && m.params && m.options) readParams(m.name, m.params, m.options); // a definition built by hand still gets its options checked
|
|
127
133
|
if (m.name in this && this[m.name] !== undefined) throw codedError('module-name', fmt(STRINGS.clash, { name: m.name }));
|
|
128
134
|
names.add(m.name); plan.push(m);
|
|
129
135
|
}
|
|
@@ -135,8 +141,9 @@ export const moduleMethods = {
|
|
|
135
141
|
_lateInit(m) {
|
|
136
142
|
const L = this.loading, task = L._begin(m.name, 'module');
|
|
137
143
|
task.phase('build');
|
|
144
|
+
const snap = catalogSnap(this);
|
|
138
145
|
L._track(Promise.resolve().then(() => m.init(this)).then(
|
|
139
|
-
() => { L._done(task); this._setModState(m, 'running'); },
|
|
146
|
+
() => { catalogClaim(this, m.name, snap); L._done(task); this._setModState(m, 'running'); },
|
|
140
147
|
e => { L._fail(task, e); this._setModState(m, 'failed'); reportError(this, e, fmt(STRINGS.lateInit, { name: m.name }), { module: m }); }));
|
|
141
148
|
},
|
|
142
149
|
/** @internal move a module to a new state and refresh the hooks (initializing / failed modules run none) */
|
|
@@ -151,6 +158,13 @@ export const moduleMethods = {
|
|
|
151
158
|
* @example engine.use(shop()); await engine.loading.settled(); engine.moduleStates.shop // 'running'
|
|
152
159
|
*/
|
|
153
160
|
get moduleStates() { return Object.fromEntries(this._modState); },
|
|
161
|
+
/**
|
|
162
|
+
* What this game can do, read from the registrations (see core/catalog.js): no argument = short list, a module id or op name = that entry expanded.
|
|
163
|
+
* @param {string | { find?: string }} [id]
|
|
164
|
+
* @returns {any}
|
|
165
|
+
* @example engine.catalog(); engine.catalog('sky'); engine.catalog('shop.buy'); engine.catalog({ find: 'buy' })
|
|
166
|
+
*/
|
|
167
|
+
catalog(id) { return catalog(this, id); },
|
|
154
168
|
/** Is this module installed? */
|
|
155
169
|
has(name) { return this.modules.has(name); },
|
|
156
170
|
/** Run order of module hooks (module names, first to last), for debugging "who runs first". */
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Atomic ops (op definition atomic: true): world records, inventory / containers and vars written during run are kept or all undone.
|
|
2
|
+
// How: the save parts declared atomic are copied before run and loaded back (as an op write) if run fails or throws. Honest limits, also in recipe 23:
|
|
3
|
+
// - it costs one save of those parts per atomic run: fine for a shop / craft op, not for a per-frame op in a huge world;
|
|
4
|
+
// - events already emitted, and anything outside the atomic parts (sound, animation, DOM, other modules' saves), are NOT undone: put such side effects in the op's `after`;
|
|
5
|
+
// - ops called from an atomic run join it: their `after` hooks wait for the outermost commit.
|
|
6
|
+
// Which parts: the ones whose module declared saves.register(key, { atomic: true }) (core names no module; a game's own part can opt in the same way).
|
|
7
|
+
// Rollback does not run afterLoad hooks (no model rebuild): atomic state must be plain data a load restores by itself. Events the load would emit are muted
|
|
8
|
+
// (the run's own events already went out and cannot be recalled), and the trace gets one 'ops:rollback' note.
|
|
9
|
+
|
|
10
|
+
/** Copy the atomic parts that exist now: [[provider, plain copy]] @internal */
|
|
11
|
+
export function snapshot(e) {
|
|
12
|
+
const out = [];
|
|
13
|
+
for (const p of e.saves.providers.values()) if (p.atomic) out.push([p, JSON.parse(JSON.stringify(p.save() ?? null))]);
|
|
14
|
+
return out;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Put a snapshot back (guarded writes allowed, change events muted) @internal */
|
|
18
|
+
export function rollback(e, snap) {
|
|
19
|
+
const ev = e.events;
|
|
20
|
+
ev.muted = (ev.muted || 0) + 1;
|
|
21
|
+
try { e.ops.allow(() => { for (const [p, d] of snap) p.load(JSON.parse(JSON.stringify(d))); }); } finally { ev.muted--; }
|
|
22
|
+
if (ev.traceSize > 0) ev.note('ops:rollback', { data: { parts: snap.length } });
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Mark the history entries a rolled-back run left behind (committed nested ops deeper than it) as failed with code 'rolledBack' @internal */
|
|
26
|
+
export function markRolledBack(ops, seq, depth) {
|
|
27
|
+
for (const h of ops._ring) if (h.seq > seq && h.depth > depth && h.ok) { h.ok = false; h.code = 'rolledBack'; }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Which state an op definition covers, for list / explain / the catalog: honest about what atomic means */
|
|
31
|
+
export const atomicNote = d => d.atomic ? 'atomic: the parts declared atomic (world, inventory, containers, vars, quests, grids, random, scene) roll back if run fails; events, sound and other state do not (use after)' : null;
|
package/core/opsCheck.js
CHANGED
|
@@ -2,11 +2,11 @@
|
|
|
2
2
|
// Each message says what is wrong and how to write it, because the reader is usually an AI that will fix the call from the text alone.
|
|
3
3
|
import { closest, fmt } from './validate.js';
|
|
4
4
|
import { codedError } from './errorHints.js';
|
|
5
|
+
import { parseSchema, whyBad, CHECK, OP_TYPES as TYPES } from './params.js'; // one type check for op args and module params
|
|
5
6
|
|
|
6
7
|
export const SOURCES = ['player', 'game', 'bridge', 'test', 'replay', 'net'];
|
|
7
|
-
const TYPES = ['string', 'number', 'int', 'bool', 'position', 'id', 'any'];
|
|
8
8
|
const NAME = /^[a-z][a-zA-Z0-9]*(\.[a-z][a-zA-Z0-9]*)+$/;
|
|
9
|
-
const DEF_KEYS = ['desc', 'args', 'can', 'run', 'offers', 'reasons', 'undo', 'net', 'owner'];
|
|
9
|
+
const DEF_KEYS = ['desc', 'args', 'can', 'run', 'offers', 'reasons', 'undo', 'net', 'owner', 'targets', 'atomic', 'after'];
|
|
10
10
|
export { fmt };
|
|
11
11
|
const STRINGS = {
|
|
12
12
|
badName: "ops.define('{name}'): name an op noun.verb, e.g. 'shop.buy' (lowercase start, camelCase)",
|
|
@@ -14,12 +14,15 @@ const STRINGS = {
|
|
|
14
14
|
badKey: "ops.define('{name}'): unknown field '{key}'{hint}. Fields: " + DEF_KEYS.join(', '),
|
|
15
15
|
badType: "ops.define('{name}'): args.{key} has type '{type}'; use one of " + TYPES.join(' ') + " (add ? for optional, e.g. 'int?')",
|
|
16
16
|
badNet: "ops.define('{name}'): net is 'peer' (remote players may request it) or 'local' (runs on each machine, e.g. UI settings); leave it out to let only the host run it",
|
|
17
|
+
badTargets: "ops.define('{name}'): targets is a thing id, kind or template name (or a list of them, or '*'), the things this op is meant for, e.g. targets: 'chest'",
|
|
17
18
|
badOwner: "ops.define('{name}'): owner is a function of the args returning the world record id the actor must own, e.g. owner: a => a.id",
|
|
18
19
|
notPlain: "ops.run('{name}'): argument {key} is {what}; pass plain data: {fix}",
|
|
19
20
|
argsObj: "ops.run('{name}'): args must be a plain object like { item: 'bread' }, got {what}",
|
|
20
21
|
missing: "ops.run('{name}') is missing {key} (args: {shape})",
|
|
21
22
|
extra: "ops.run('{name}'): unknown argument {key}{hint} (args: {shape})",
|
|
22
23
|
wrong: "ops.run('{name}'): {key} should be {type}, got {got} (args: {shape})",
|
|
24
|
+
badAtomic: "ops.define('{name}'): atomic is true/false and after is a function (e, args, value, ctx) for sound / animation; it runs only when the op committed",
|
|
25
|
+
range: "ops.run('{name}'): {key} {why} (args: {shape})",
|
|
23
26
|
noRecord: "ops.run('{name}'): {key} '{id}' is not a world record id",
|
|
24
27
|
};
|
|
25
28
|
const what = v => typeof v === 'function' ? 'a function' : v?.isVector3 ? 'a Vector3' : v?.isObject3D ? 'a three.js object' : (v?.constructor?.name ? 'a ' + v.constructor.name : typeof v);
|
|
@@ -35,11 +38,6 @@ function notPlain(v, depth = 0) {
|
|
|
35
38
|
for (const k in v) { const b = notPlain(v[k], depth + 1); if (b) return b; }
|
|
36
39
|
return null;
|
|
37
40
|
}
|
|
38
|
-
const isPos = v => Array.isArray(v) && (v.length === 2 || v.length === 3) && v.every(Number.isFinite);
|
|
39
|
-
const CHECK = {
|
|
40
|
-
string: v => typeof v === 'string', number: v => Number.isFinite(v), int: v => Number.isInteger(v), bool: v => typeof v === 'boolean',
|
|
41
|
-
position: isPos, id: v => typeof v === 'string', any: () => true,
|
|
42
|
-
};
|
|
43
41
|
|
|
44
42
|
/** Dev mistakes (wrong name, args, can result) are thrown straight to the caller, not treated as gameplay errors */
|
|
45
43
|
export function devError(msg) { const err = codedError('op-misuse', msg); err.opsDevError = true; return err; }
|
|
@@ -54,14 +52,13 @@ export function checkDef(name, def) {
|
|
|
54
52
|
throw devError(fmt(STRINGS.badKey, { name, key, hint: c ? ` (did you mean ${c}?)` : '' }));
|
|
55
53
|
}
|
|
56
54
|
if (def.net !== undefined && def.net !== 'peer' && def.net !== 'local') throw devError(fmt(STRINGS.badNet, { name }));
|
|
55
|
+
if (def.targets !== undefined && ![def.targets].flat().every(t => typeof t === 'string' && t)) throw devError(fmt(STRINGS.badTargets, { name }));
|
|
57
56
|
if (def.owner !== undefined && typeof def.owner !== 'function') throw devError(fmt(STRINGS.badOwner, { name }));
|
|
57
|
+
if ((def.atomic !== undefined && typeof def.atomic !== 'boolean') || (def.after !== undefined && typeof def.after !== 'function')) throw devError(fmt(STRINGS.badAtomic, { name }));
|
|
58
58
|
if (!def.args) return null;
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
if (!TYPES.includes(type)) throw devError(fmt(STRINGS.badType, { name, key, type: t }));
|
|
63
|
-
shape[key] = { type, optional: t.endsWith('?') };
|
|
64
|
-
}
|
|
59
|
+
// the same schema form as module params (params.js): 'int?' or { type, default, min, max, values, desc }
|
|
60
|
+
const shape = parseSchema(`ops.define('${name}') args`, def.args, devError);
|
|
61
|
+
for (const key in shape) if (!TYPES.includes(shape[key].type)) throw devError(fmt(STRINGS.badType, { name, key, type: shape[key].type }));
|
|
65
62
|
return shape;
|
|
66
63
|
}
|
|
67
64
|
|
|
@@ -81,6 +78,20 @@ export function checkArgs(e, d, args) {
|
|
|
81
78
|
const s = d.shape[key], v = args[key];
|
|
82
79
|
if (v === undefined) { if (!s.optional) throw devError(fmt(STRINGS.missing, { name, key, shape: shapeText })); continue; }
|
|
83
80
|
if (!CHECK[s.type](v)) throw devError(fmt(STRINGS.wrong, { name, key, type: s.type === 'position' ? '[x, y, z]' : s.type, got: JSON.stringify(v), shape: shapeText }));
|
|
84
|
-
|
|
81
|
+
const range = whyBad(s, v); // min / max / values of the full schema form
|
|
82
|
+
if (range) throw devError(fmt(STRINGS.range, { name, key, why: range, shape: shapeText }));
|
|
83
|
+
if (s.type === 'id' && e._things.sources.length && !e._things.source(v)) throw devError(fmt(STRINGS.noRecord, { name, key, id: v }));
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Release builds: the range part of the schema (min / max / values) is still checked, because a bad number from a UI or a net peer must not reach run. Returns a failure spec or null */
|
|
88
|
+
export function argRange(d, args) {
|
|
89
|
+
if (!d.shape || !args) return null;
|
|
90
|
+
for (const key in d.shape) {
|
|
91
|
+
const s = d.shape[key], v = args[key];
|
|
92
|
+
if (v === undefined || !CHECK[s.type](v)) { if (v !== undefined) return { code: 'badArgs', facts: [{ id: d.name, field: key, actual: v, expected: s.type }] }; continue; }
|
|
93
|
+
const why = whyBad(s, v);
|
|
94
|
+
if (why) return { code: 'badArgs', facts: [{ id: d.name, field: key, actual: v, expected: why }] };
|
|
85
95
|
}
|
|
96
|
+
return null;
|
|
86
97
|
}
|
package/core/opsFail.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Structured op failures. can may return a reason string (kept working) or { code, facts?, nextActions? }:
|
|
2
|
+
// can: () => cond ? true : { code: 'noMoney', facts: { need: 5, have: 2 }, nextActions: [{ op: 'job.work', args: {} }] }
|
|
3
|
+
// facts: an object ({ need: 5, have: 2 }) or a list [{ id, field, actual, expected? }] (which record / field was wrong, and what it should have been). nextActions are declared by the game here, never guessed by the engine.
|
|
4
|
+
// run may fail the same way: return or throw { ok: false, code, facts?, nextActions? } (the op then counts as failed; an atomic op is rolled back).
|
|
5
|
+
// Every failed result from run / can / undo is normalized to { ok: false, code, facts, nextActions }; `code` is the name to read. The old field `reason`
|
|
6
|
+
// is a hidden (non-enumerable) trap: reading it throws renamed-api and names result.code, in every build.
|
|
7
|
+
import { renamed } from './errorHints.js';
|
|
8
|
+
const NONE = Object.freeze([]), NO_FACTS = Object.freeze({});
|
|
9
|
+
const TRAP = { get() { return renamed('reason'); }, enumerable: false, configurable: true };
|
|
10
|
+
|
|
11
|
+
/** @param {string | { code: string, facts?: object, nextActions?: any[] }} r a code string or a structured failure @returns {{ ok: false, code: string, facts: object, nextActions: any[], reason?: never }} */
|
|
12
|
+
export function failure(r) {
|
|
13
|
+
const out = typeof r === 'string' ? { ok: false, code: r, facts: NO_FACTS, nextActions: NONE }
|
|
14
|
+
: { ok: false, code: r.code, facts: r.facts ?? NO_FACTS, nextActions: r.nextActions ?? NONE };
|
|
15
|
+
return Object.defineProperty(out, 'reason', TRAP);
|
|
16
|
+
}
|
|
17
|
+
/** True when can returned a usable structured failure */
|
|
18
|
+
export const isStructured = r => r !== null && typeof r === 'object' && typeof r.code === 'string' && r.code.length > 0;
|
|
19
|
+
/** True when run returned or threw a structured failure: { ok: false, code, ... } (plain values with a code field are not failures) */
|
|
20
|
+
export const isRunFailure = r => r !== null && typeof r === 'object' && r.ok === false && typeof r.code === 'string' && r.code.length > 0;
|
package/core/opsHistory.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
// The history of engine.ops (split out of Ops.js): a ring of entries allocated once, so logging a run allocates nothing.
|
|
2
|
-
// Entry: { seq, tick, phase, name, args, source, actor, ok,
|
|
2
|
+
// Entry: { seq, tick, phase, name, args, source, actor, ok, code, depth, count }. Ops keeps the ring fields (_ring, _head, _len, _seq); these functions work on them.
|
|
3
3
|
|
|
4
4
|
/** A fresh ring of n empty entries @param {number} n */
|
|
5
|
-
export const newRing = n => Array.from({ length: Math.max(1, n | 0) }, () => ({ seq: 0, tick: 0, phase: 'between', name: '', args: null, source: '', actor: '', ok: false,
|
|
5
|
+
export const newRing = n => Array.from({ length: Math.max(1, n | 0) }, () => ({ seq: 0, tick: 0, phase: 'between', name: '', args: null, source: '', actor: '', ok: false, code: null, depth: 0, count: 1 }));
|
|
6
6
|
|
|
7
|
-
/** Write a history entry in place (no allocation); consecutive identical failures (same actor, op,
|
|
8
|
-
export function logEntry(ops, name, args, ctx, ok,
|
|
7
|
+
/** Write a history entry in place (no allocation); consecutive identical failures (same actor, op, code) merge into one with count */
|
|
8
|
+
export function logEntry(ops, name, args, ctx, ok, code, depth) {
|
|
9
9
|
const n = ops._ring.length, last = ops._len ? ops._ring[(ops._head - 1 + n) % n] : null;
|
|
10
|
-
if (!ok && last && !last.ok && last.name === name && last.
|
|
10
|
+
if (!ok && last && !last.ok && last.name === name && last.code === code && last.actor === ctx.actor) { last.count++; return last; }
|
|
11
11
|
const h = ops._ring[ops._head];
|
|
12
12
|
h.seq = ++ops._seq; h.tick = ctx.tick; h.phase = ops.engine._inFixed ? 'fixed' : 'between'; h.name = name; h.args = args;
|
|
13
|
-
h.source = ctx.source; h.actor = ctx.actor; h.ok = ok; h.
|
|
13
|
+
h.source = ctx.source; h.actor = ctx.actor; h.ok = ok; h.code = code; h.depth = depth; h.count = 1;
|
|
14
14
|
ops._head = (ops._head + 1) % n;
|
|
15
15
|
if (ops._len < n) ops._len++;
|
|
16
16
|
return h;
|
package/core/opsRun.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// ops.run itself (split out of Ops.js). Order: can -> log -> [snapshot if atomic] -> run -> commit (revision + 1, after hook) or fail (rollback if atomic).
|
|
2
|
+
// A run that returns or throws a structured failure { ok: false, code, facts?, nextActions? } counts as failed, like a can that said no (see opsFail.js).
|
|
3
|
+
import { DEV } from './validate.js';
|
|
4
|
+
import { devError, fmt, argRange } from './opsCheck.js';
|
|
5
|
+
import { reportError } from './errors.js';
|
|
6
|
+
import { failure, isRunFailure } from './opsFail.js';
|
|
7
|
+
import { snapshot, rollback, markRolledBack } from './opsAtomic.js';
|
|
8
|
+
import { withDefaults } from './params.js';
|
|
9
|
+
|
|
10
|
+
const MAX_DEPTH = 16;
|
|
11
|
+
export const RUN_STRINGS = {
|
|
12
|
+
canRun: "{name}'s can called ops.run('{inner}'). can is read-only; call other ops from run",
|
|
13
|
+
loop: 'ops call each other in a loop (deeper than ' + MAX_DEPTH + '): {chain}',
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/** Undo an atomic run's writes; a failing rollback is reported, never thrown over the original failure */
|
|
17
|
+
function undoWrites(ops, e, snap, where, seq, depth) {
|
|
18
|
+
ops.revision++; // the revision only goes up: a rollback is a new state, never "the old number again"
|
|
19
|
+
markRolledBack(ops, seq, depth);
|
|
20
|
+
try { rollback(e, snap); } catch (err) { reportError(e, err, where + ' rollback'); }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** @internal Called by Ops.run */
|
|
24
|
+
export function runOp(ops, name, args, opts) {
|
|
25
|
+
const e = ops.engine, d = ops._def(name);
|
|
26
|
+
if (!d) return ops._res(failure('unknownOp'));
|
|
27
|
+
args = withDefaults(d.defaults, args);
|
|
28
|
+
if (ops._inCan) throw devError(fmt(RUN_STRINGS.canRun, { name: ops._inCan, inner: name }));
|
|
29
|
+
if (ops._stack.length >= MAX_DEPTH) throw devError(fmt(RUN_STRINGS.loop, { chain: ops._stack.concat(name).join(' -> ') }));
|
|
30
|
+
if (ops._route) { const r = ops._route(d, args, opts); if (r) return r; } // net client: requests go to the host (also from inside a net: 'local' op)
|
|
31
|
+
const parent = ops._stack.length ? ops._last : null;
|
|
32
|
+
const ctx = ops._ctx(name, args, opts, parent);
|
|
33
|
+
const depth = ops._stack.length, ev = e.events, where = `ops.run('${name}')`;
|
|
34
|
+
if (e._freezers.has('error')) { ops._log(name, args, ctx, false, 'halted', depth); return ops._res(failure('halted')); }
|
|
35
|
+
if (DEV && args && typeof args === 'object') Object.freeze(args);
|
|
36
|
+
const failed = (f, h) => { // a failed run: log it, trace it with its code
|
|
37
|
+
if (h) { h.ok = false; h.code = f.code; } else ops._log(name, args, ctx, false, f.code, depth);
|
|
38
|
+
if (ev.traceSize > 0) ev.note('op:' + name, { code: f.code, obj: args?.id });
|
|
39
|
+
return ops._res(f);
|
|
40
|
+
};
|
|
41
|
+
if (!DEV) { const bad = argRange(d, args); if (bad) return failed(failure(bad), null); } // release: min / max / values still hold (dev throws earlier, in _ctx)
|
|
42
|
+
ops._stack.push(name);
|
|
43
|
+
const prevCtx = ops._last; ops._last = ctx;
|
|
44
|
+
const prevCause = ev._cur, atomic = d.atomic === true, mark = ops._txAfter.length; // events emitted by this op's run name it as their cause (Events.trace)
|
|
45
|
+
let h = null, seq = 0, snap = null;
|
|
46
|
+
if (atomic) ops._txDepth++;
|
|
47
|
+
try {
|
|
48
|
+
const res = ops._can(d, args, ctx);
|
|
49
|
+
if (res !== true) return failed(failure(res), null);
|
|
50
|
+
h = ops._log(name, args, ctx, true, null, depth); seq = h.seq; // logged before run so nested ops follow their parent in the history
|
|
51
|
+
if (ev.traceSize > 0) ev._cur = `op:${name}#${seq}`;
|
|
52
|
+
if (atomic) snap = snapshot(e);
|
|
53
|
+
let value;
|
|
54
|
+
try { value = d.run(e, args, ctx); } catch (err) { if (!isRunFailure(err)) throw err; value = err; }
|
|
55
|
+
if (isRunFailure(value)) {
|
|
56
|
+
if (snap) { undoWrites(ops, e, snap, where, seq, depth); ops._txAfter.length = mark; }
|
|
57
|
+
return failed(failure(value), h.seq === seq ? h : null);
|
|
58
|
+
}
|
|
59
|
+
ops.revision++;
|
|
60
|
+
if (d.after) {
|
|
61
|
+
const hook = () => { try { d.after(e, args, value, ctx); } catch (err) { reportError(e, err, where + ' after'); } };
|
|
62
|
+
if (ops._txDepth > 0) ops._txAfter.push(hook); else hook(); // in or inside an atomic run: queue, so hooks run in commit order (nested first) when the outermost one ends
|
|
63
|
+
}
|
|
64
|
+
return { ok: true, value, revision: ops.revision };
|
|
65
|
+
} catch (err) {
|
|
66
|
+
if (snap) { undoWrites(ops, e, snap, where, seq, depth); ops._txAfter.length = mark; }
|
|
67
|
+
if (err?.opsDevError) throw err;
|
|
68
|
+
if (h?.seq === seq) { h.ok = false; h.code = 'error'; } else ops._log(name, args, ctx, false, 'error', depth);
|
|
69
|
+
reportError(e, err, where);
|
|
70
|
+
if (e.error?.where === where && !e.error.ops) e.error.ops = ops.recent().slice(-5).map(r => `${r.name}${r.ok ? '' : ' x ' + r.code}`);
|
|
71
|
+
if (ev.traceSize > 0) ev.note('op:' + name, { code: 'error' });
|
|
72
|
+
return ops._res(failure('error'));
|
|
73
|
+
} finally {
|
|
74
|
+
ops._stack.pop(); ops._last = prevCtx; ev._cur = prevCause;
|
|
75
|
+
if (atomic && --ops._txDepth === 0) { const q = ops._txAfter.splice(0); for (const f of q) f(); } // outermost atomic op ended: its queued after hooks run now (empty after a rollback)
|
|
76
|
+
}
|
|
77
|
+
}
|