threedog 0.8.0 → 1.0.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.
Files changed (372) hide show
  1. package/CHANGELOG.md +219 -4
  2. package/README.md +6 -6
  3. package/core/assets/Animator.js +2 -0
  4. package/core/assets/Assets.js +44 -13
  5. package/core/assets/assetEntry.js +87 -22
  6. package/core/assets/assetHot.js +2 -1
  7. package/core/assets/assetReport.js +1 -2
  8. package/core/audio/Audio.js +24 -5
  9. package/core/base/I18n.js +6 -3
  10. package/core/base/Random.js +3 -1
  11. package/core/base/Vars.js +14 -4
  12. package/core/base/errorCodes.js +54 -16
  13. package/core/base/errorHints.js +12 -1
  14. package/core/base/errors.js +6 -4
  15. package/core/base/events.generated.js +10 -0
  16. package/core/base/follows.js +26 -0
  17. package/core/base/math.js +15 -8
  18. package/core/base/params.js +2 -2
  19. package/core/{saves → base}/saveValues.js +24 -6
  20. package/core/base/sections.js +97 -0
  21. package/core/base/spelling.js +32 -0
  22. package/core/base/validate.js +8 -29
  23. package/core/engine/Engine.js +61 -18
  24. package/core/engine/Loading.js +30 -3
  25. package/core/engine/copies.js +1 -1
  26. package/core/engine/headlessLoad.js +30 -13
  27. package/core/engine/lifecycle.js +30 -25
  28. package/core/engine/loop.js +22 -4
  29. package/core/engine/moduleSlots.js +91 -15
  30. package/core/engine/moduleTypes.js +13 -0
  31. package/core/engine/modules.js +248 -62
  32. package/core/engine/page.js +25 -8
  33. package/core/engine/plugins.js +15 -3
  34. package/core/engine/services.js +3 -0
  35. package/core/engine/startup.js +46 -36
  36. package/core/input/Input.js +39 -19
  37. package/core/input/inputKeyboard.js +39 -0
  38. package/core/input/inputPad.js +23 -2
  39. package/core/input/inputPointer.js +3 -1
  40. package/core/input/inputSeat.js +66 -0
  41. package/core/input/inputTouch.js +23 -6
  42. package/core/inspect/DebugOverrides.js +13 -2
  43. package/core/inspect/Describe.js +10 -6
  44. package/core/inspect/Inspect.js +31 -4
  45. package/core/inspect/UrlState.js +14 -10
  46. package/core/inspect/catalog.js +12 -5
  47. package/core/inspect/describeRender.js +3 -2
  48. package/core/inspect/describeText.js +6 -2
  49. package/core/inspect/metadata.generated.js +4140 -0
  50. package/core/inspect/pictureWriters.js +117 -33
  51. package/core/inspect/toolDoor.js +21 -0
  52. package/core/inspect/valueHistory.js +35 -0
  53. package/core/ops/Ops.js +32 -7
  54. package/core/ops/control.js +48 -23
  55. package/core/ops/holds.js +4 -3
  56. package/core/ops/opsAtomic.js +18 -6
  57. package/core/ops/opsCheck.js +7 -5
  58. package/core/ops/opsFail.js +5 -7
  59. package/core/ops/opsRun.js +2 -2
  60. package/core/ops/owned.js +20 -3
  61. package/core/ops/sharedPoint.js +7 -10
  62. package/core/ops/stacks.js +22 -1
  63. package/core/saves/SaveStore.js +52 -26
  64. package/core/saves/Saves.js +122 -27
  65. package/core/saves/saveApply.js +159 -61
  66. package/core/saves/saveFiles.js +30 -25
  67. package/core/saves/saveVersions.js +20 -6
  68. package/core/saves/session.js +76 -33
  69. package/core/saves/stateReplace.js +184 -0
  70. package/core/scene/Rays.js +21 -5
  71. package/core/scene/Views.js +6 -6
  72. package/core/scene/adaptive.js +13 -10
  73. package/core/scene/canvasBox.js +2 -0
  74. package/core/scene/compositeGround.js +72 -0
  75. package/core/scene/floor.js +17 -0
  76. package/core/scene/grid.js +2 -0
  77. package/core/scene/ground.contract.js +14 -0
  78. package/core/scene/ground.js +52 -17
  79. package/core/scene/pixel.js +154 -0
  80. package/core/scene/pixelRatio.js +167 -0
  81. package/core/scene/sceneDelta.js +3 -3
  82. package/core/scene/sceneMethods.js +11 -6
  83. package/core/scene/stepPoses.js +6 -1
  84. package/core/scene/thingExplain.js +1 -1
  85. package/core/scene/thingOps.js +22 -14
  86. package/core/scene/things.js +1 -1
  87. package/core/scene/tier.js +10 -0
  88. package/core/scene/view.js +126 -9
  89. package/core/stream/Batching.js +0 -1
  90. package/core/stream/Stream.js +24 -12
  91. package/core/stream/batchGroups.js +1 -0
  92. package/core/stream/scatter.js +5 -2
  93. package/core/stream/streamSources.js +2 -1
  94. package/core/threads/Commits.js +12 -7
  95. package/core/threads/Jobs.js +15 -5
  96. package/core/threads/Threads.js +5 -2
  97. package/core/time/Clock.js +3 -1
  98. package/core/time/skip.js +10 -4
  99. package/core/time/time.js +16 -10
  100. package/docs/AI.md +89 -72
  101. package/docs/API.md +18 -14
  102. package/docs/CODEMAP.md +68 -40
  103. package/docs/COMMANDS.md +22 -23
  104. package/docs/CONVENTIONS.md +120 -17
  105. package/docs/MIGRATING-0.8.md +2 -0
  106. package/docs/MIGRATING-1.0.md +101 -0
  107. package/docs/THREE.md +65 -12
  108. package/docs/api/cameraRig.md +3 -0
  109. package/docs/api/characters.md +13 -7
  110. package/docs/api/collider3d.md +9 -0
  111. package/docs/api/content.md +16 -15
  112. package/docs/api/dialogue.md +2 -1
  113. package/docs/api/engine.md +18 -16
  114. package/docs/api/events.md +14 -4
  115. package/docs/api/ground.md +2 -2
  116. package/docs/api/i18n.md +1 -1
  117. package/docs/api/input.md +2 -1
  118. package/docs/api/interactions.md +1 -1
  119. package/docs/api/inventory.md +1 -1
  120. package/docs/api/level.md +3 -2
  121. package/docs/api/nav.md +4 -2
  122. package/docs/api/particles.md +8 -5
  123. package/docs/api/pickups.md +1 -1
  124. package/docs/api/post.md +3 -4
  125. package/docs/api/quests.md +4 -2
  126. package/docs/api/rays.md +2 -0
  127. package/docs/api/rigid.md +3 -2
  128. package/docs/api/saves.md +8 -7
  129. package/docs/api/stream.md +4 -5
  130. package/docs/api/terrain.md +3 -4
  131. package/docs/api/terrainDraw.md +1 -1
  132. package/docs/api/timeline.md +2 -2
  133. package/docs/api/tools.md +3 -1
  134. package/docs/api/triggers.md +2 -0
  135. package/docs/api/vegetationDraw.md +1 -1
  136. package/docs/api/water.md +6 -2
  137. package/docs/api/weather.md +19 -4
  138. package/docs/api/weatherDraw.md +1 -1
  139. package/docs/api/world.md +1 -1
  140. package/docs/recipes/01-new-game.md +3 -3
  141. package/docs/recipes/02-npc.md +3 -4
  142. package/docs/recipes/03-items-pickups.md +11 -11
  143. package/docs/recipes/04-quests.md +2 -0
  144. package/docs/recipes/05-props-bake.md +9 -9
  145. package/docs/recipes/06-clock-events.md +6 -6
  146. package/docs/recipes/07-flow-scenes-pause.md +18 -15
  147. package/docs/recipes/08-weather-sky.md +5 -5
  148. package/docs/recipes/09-materials-lights-models.md +3 -3
  149. package/docs/recipes/10-blender-level.md +16 -4
  150. package/docs/recipes/11-vehicles.md +18 -6
  151. package/docs/recipes/12-navmesh.md +52 -8
  152. package/docs/recipes/13-animation.md +34 -8
  153. package/docs/recipes/14-custom-module.md +20 -8
  154. package/docs/recipes/15-perf.md +4 -4
  155. package/docs/recipes/16-dev-bridge.md +9 -8
  156. package/docs/recipes/18-world.md +13 -5
  157. package/docs/recipes/19-shooting-picking.md +3 -2
  158. package/docs/recipes/20-content-actions-save.md +26 -6
  159. package/docs/recipes/21-camera.md +17 -23
  160. package/docs/recipes/22-shop-gold.md +21 -12
  161. package/docs/recipes/23-ops.md +19 -15
  162. package/docs/recipes/26-ui-parts.md +3 -2
  163. package/docs/recipes/27-net.md +3 -3
  164. package/docs/recipes/28-terrain.md +3 -3
  165. package/docs/recipes/29-grid.md +1 -1
  166. package/docs/recipes/30-templates.md +10 -13
  167. package/docs/recipes/31-audio.md +2 -2
  168. package/docs/recipes/32-action-game.md +6 -5
  169. package/docs/recipes/33-stream-sources.md +4 -1
  170. package/docs/recipes/34-environment-lighting.md +7 -8
  171. package/docs/recipes/35-picture-from-reference.md +13 -9
  172. package/docs/recipes/36-ground-plants.md +3 -2
  173. package/docs/recipes/40-scene.md +11 -10
  174. package/docs/recipes/43-shader-patches-surfaces.md +7 -7
  175. package/docs/recipes/44-water-weather-hooks.md +9 -8
  176. package/docs/recipes/45-cascaded-shadows.md +3 -4
  177. package/docs/recipes/46-blender-art-route.md +3 -3
  178. package/docs/recipes/49-game-module-contract.md +2 -1
  179. package/docs/recipes/50-own-renderer.md +1 -0
  180. package/docs/recipes/51-capability-catalog.md +14 -8
  181. package/docs/recipes/52-around-the-picture.md +4 -4
  182. package/docs/recipes/55-mods-time-wrap.md +5 -4
  183. package/docs/recipes/56-webgpu-tsl.md +12 -1
  184. package/docs/recipes/57-control.md +30 -10
  185. package/docs/recipes/58-input.md +13 -0
  186. package/docs/recipes/60-judge-the-picture.md +1 -1
  187. package/docs/recipes/62-picture-code.md +106 -48
  188. package/docs/recipes/63-third-person-start.md +2 -1
  189. package/docs/recipes/64-particles.md +53 -4
  190. package/docs/recipes/65-swarm.md +2 -2
  191. package/docs/recipes/66-common-tasks.md +313 -0
  192. package/examples/action/.threedog/content-index.json +1 -1
  193. package/examples/action/GAMEMAP.md +3 -3
  194. package/examples/perf-island/.threedog/content-index.json +1 -1
  195. package/examples/perf-island/GAMEMAP.md +3 -3
  196. package/examples/perf-island/main.js +2 -2
  197. package/examples/plain-picture/GAMEMAP.md +3 -1
  198. package/examples/rc2d/GAMEMAP.md +1 -1
  199. package/examples/rc2d/rc2d.js +1 -1
  200. package/examples/styletest/.threedog/content-index.json +1 -1
  201. package/examples/styletest/GAMEMAP.md +3 -3
  202. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  203. package/examples/world/.threedog/content-index.json +1 -1
  204. package/examples/world/GAMEMAP.md +5 -4
  205. package/examples/world/main.js +3 -3
  206. package/index.d.ts +8 -5
  207. package/index.js +22 -1
  208. package/llms.txt +2 -1
  209. package/modules/ambience/Ambience.js +5 -3
  210. package/modules/calendar/index.js +7 -5
  211. package/modules/camera/FirstPersonCamera.js +3 -3
  212. package/modules/camera/FixedCamera.js +34 -20
  213. package/modules/camera/FollowCamera.js +20 -11
  214. package/modules/camera/RtsCamera.js +1 -0
  215. package/modules/camera/common.js +33 -22
  216. package/modules/camera/pixelSnap.js +62 -0
  217. package/modules/characters/Character.js +136 -43
  218. package/modules/characters/NPC.js +60 -28
  219. package/modules/characters/assetModel.js +2 -2
  220. package/modules/characters/astar.js +47 -28
  221. package/modules/characters/character.contract.js +21 -0
  222. package/modules/characters/contract.js +17 -3
  223. package/modules/characters/index.js +94 -34
  224. package/modules/characters/moveHelpers.js +80 -15
  225. package/modules/characters/mover.contract.js +14 -0
  226. package/modules/characters/movers/common.js +6 -4
  227. package/modules/characters/movers/rapier.js +12 -5
  228. package/modules/characters/movers/simple.js +25 -12
  229. package/modules/characters/movers/support.js +18 -7
  230. package/modules/characters/npcAvoid.js +15 -12
  231. package/modules/characters/npcSim.js +75 -25
  232. package/modules/characters/npcView.js +13 -6
  233. package/modules/characters/pathAsync.js +74 -24
  234. package/modules/characters/pathJob.js +38 -21
  235. package/modules/characters/player.js +59 -47
  236. package/modules/characters/seat.js +56 -0
  237. package/modules/characters/vehicle.contract.js +8 -5
  238. package/modules/characters/walkTo.js +31 -18
  239. package/modules/collision/Collision.js +44 -26
  240. package/modules/collision/contract.js +2 -2
  241. package/modules/collision/grid.js +6 -1
  242. package/modules/content/explain.js +1 -1
  243. package/modules/content/fields.js +3 -3
  244. package/modules/content/ids.js +3 -1
  245. package/modules/content/index.js +83 -27
  246. package/modules/content/loader.js +110 -130
  247. package/modules/content/markers.js +1 -1
  248. package/modules/content/models.js +48 -14
  249. package/modules/content/packs.js +2 -1
  250. package/modules/content/places.js +5 -4
  251. package/modules/content/props.js +8 -6
  252. package/modules/content/rules.js +29 -47
  253. package/modules/content/templates.js +66 -35
  254. package/modules/content/words.js +19 -6
  255. package/modules/debug/DebugPanel.js +4 -2
  256. package/modules/flow/contract.js +1 -0
  257. package/modules/flow/index.js +24 -14
  258. package/modules/gameplay/Container.js +5 -2
  259. package/modules/gameplay/Containers.js +9 -1
  260. package/modules/gameplay/Dialogue.js +82 -25
  261. package/modules/gameplay/Interactions.js +61 -32
  262. package/modules/gameplay/Inventory.js +56 -13
  263. package/modules/gameplay/Quests.js +133 -24
  264. package/modules/gameplay/boxOps.js +7 -0
  265. package/modules/gameplay/dialogueBubbles.js +14 -9
  266. package/modules/gameplay/inventoryOps.js +11 -7
  267. package/modules/gameplay/pickups.js +43 -16
  268. package/modules/gameplay/questLog.js +4 -2
  269. package/modules/gameplay/questSave.js +6 -1
  270. package/modules/gameplay/quests.contract.js +1 -1
  271. package/modules/grid/Grid.js +1 -1
  272. package/modules/grid/Layer.js +8 -4
  273. package/modules/grid/index.js +21 -15
  274. package/modules/grid/ops.js +43 -46
  275. package/modules/grid/tiles.js +1 -1
  276. package/modules/hlod/index.js +6 -3
  277. package/modules/hud/index.js +6 -4
  278. package/modules/hud/parts.js +4 -4
  279. package/modules/level/contract.js +2 -2
  280. package/modules/level/heightfield.js +17 -21
  281. package/modules/level/index.js +83 -26
  282. package/modules/level/load.js +165 -48
  283. package/modules/level/nodes.js +34 -16
  284. package/modules/lights/index.js +6 -3
  285. package/modules/lights/sources.js +3 -1
  286. package/modules/music/Music.js +4 -2
  287. package/modules/nav/contract.js +7 -5
  288. package/modules/nav/index.js +174 -44
  289. package/modules/nav/navPath.js +45 -10
  290. package/modules/net/index.js +1 -1
  291. package/modules/particles/Particles.js +85 -22
  292. package/modules/particles/effect.js +80 -28
  293. package/modules/particles/shaders.js +17 -0
  294. package/modules/photo/Photo.js +12 -10
  295. package/modules/rigid/RigidBodies.js +200 -57
  296. package/modules/rigid/Vehicles.js +15 -5
  297. package/modules/rigid/collider3d.contract.js +26 -0
  298. package/modules/rigid/ragdoll.js +55 -44
  299. package/modules/rigid/ragdollBones.js +83 -33
  300. package/modules/rigid/refresh.js +10 -0
  301. package/modules/rigid/sync.js +46 -15
  302. package/modules/settings/Settings.js +84 -37
  303. package/modules/settings/apply.js +15 -8
  304. package/modules/settings/sections.js +7 -4
  305. package/modules/settings/strings.js +2 -2
  306. package/modules/sky/skyModule.js +3 -1
  307. package/modules/swarm/Swarm.js +16 -6
  308. package/modules/terrain/ChunkManager.js +10 -16
  309. package/modules/terrain/index.js +17 -11
  310. package/modules/terrain/terrainEdit.js +13 -2
  311. package/modules/terrain/terrainGen.js +5 -3
  312. package/modules/terrain/terrainShape.js +1 -1
  313. package/modules/timeline/Timeline.js +58 -26
  314. package/modules/timeline/Tween.js +19 -13
  315. package/modules/timeline/shots.js +19 -10
  316. package/modules/triggers/index.js +87 -20
  317. package/modules/vegetation/Vegetation.js +4 -3
  318. package/modules/vegetation/draw.js +16 -0
  319. package/modules/vegetation/groundChunks.js +10 -7
  320. package/modules/vegetation/index.js +30 -7
  321. package/modules/water/Water.js +6 -2
  322. package/modules/weather/Weather.js +16 -15
  323. package/modules/weather/weatherDraw.js +7 -6
  324. package/modules/world/World.js +20 -7
  325. package/modules/world/explain.js +1 -1
  326. package/modules/world/index.js +13 -6
  327. package/modules/world/persist.js +23 -8
  328. package/modules/world/pos.js +4 -4
  329. package/modules/world/records.js +13 -7
  330. package/modules/world/sim.js +74 -23
  331. package/modules/world/simFar.js +2 -2
  332. package/modules/world/state.js +31 -6
  333. package/modules/world/thingSource.js +16 -3
  334. package/modules/world/views.js +19 -8
  335. package/package.json +7 -1
  336. package/render/PostFX.js +47 -29
  337. package/render/backend.js +5 -1
  338. package/render/fx/particles.tsl.js +8 -6
  339. package/render/fx/postWebGPU.tsl.js +3 -3
  340. package/render/layers.js +1 -1
  341. package/render/lightmap.js +23 -3
  342. package/render/occlusion.js +43 -12
  343. package/render/patches.js +2 -2
  344. package/render/postWebGL.js +4 -3
  345. package/render/probes.js +25 -0
  346. package/render/shadows.js +2 -2
  347. package/types/core.d.ts +142 -55
  348. package/types/gameplay.d.ts +92 -40
  349. package/types/generated/core/base/I18n.d.ts +2 -2
  350. package/types/generated/core/input/Input.d.ts +16 -2
  351. package/types/generated/core/input/inputSeat.d.ts +26 -0
  352. package/types/generated/core/inspect/DebugOverrides.d.ts +15 -1
  353. package/types/generated/core/ops/Ops.d.ts +2 -1
  354. package/types/generated/core/ops/control.d.ts +12 -2
  355. package/types/generated/core/saves/Saves.d.ts +26 -6
  356. package/types/generated/core/saves/session.d.ts +1 -1
  357. package/types/generated/core/scene/Views.d.ts +1 -1
  358. package/types/generated/core/stream/Stream.d.ts +6 -4
  359. package/types/generated/modules/grid/Grid.d.ts +1 -0
  360. package/types/generated/modules/particles/Particles.d.ts +4 -3
  361. package/types/generated/modules/timeline/Timeline.d.ts +5 -4
  362. package/types/generated/modules/weather/Weather.d.ts +1 -7
  363. package/types/generated/modules/world/World.d.ts +6 -4
  364. package/types/generated/render/PostFX.d.ts +6 -14
  365. package/types/nav.d.ts +36 -4
  366. package/types/physics.d.ts +55 -7
  367. package/types/pixel.d.ts +75 -0
  368. package/types/world.d.ts +14 -8
  369. package/ui/Parts.js +9 -2
  370. package/ui/theme.js +2 -2
  371. package/core/scene/engineCamera.js +0 -32
  372. package/modules/camera/projection.js +0 -21
package/core/ops/holds.js CHANGED
@@ -8,6 +8,7 @@
8
8
  import { warnOnce } from '../base/validate.js';
9
9
  import { coded } from '../base/errorHints.js';
10
10
  import { ownerArgs } from './sharedPoint.js';
11
+ import { viewHold } from '../scene/view.js';
11
12
 
12
13
  // The halt / freeze handle is { owner, remove() } only: no chaining, so each is ended in exactly one way.
13
14
  function handle(owner, remove) { return { owner, remove }; }
@@ -26,7 +27,7 @@ export function defineHoldStacks(engine) {
26
27
  else if (!engine.disposed) { engine.halted = false; engine._loop(); }
27
28
  engine.page._sync(); // a page hold is about the real-time loop: there is none while the loop is stopped (core/engine/page.js)
28
29
  } });
29
- engine.stacks.define('camera', { kind: 'top', save: false }); // who holds the camera; the latest is in charge (cameraOverride)
30
+ engine.stacks.define('camera', { kind: 'top', save: false, onChange: () => viewHold(engine) }); // who holds the camera; the latest is in charge (cameraOverride)
30
31
  }
31
32
 
32
33
  export const holdMethods = {
@@ -41,8 +42,8 @@ export const holdMethods = {
41
42
  haltLoop(owner) {
42
43
  const a = ownerArgs(owner);
43
44
  const P = this.stacks.get('halt');
44
- P.take({ owner: a.owner, value: true }); // the stack's onChange sets this.halted (defineHoldStacks), same as engine.mod('halt')
45
- return handle(a.owner, () => { if (P.has(a.owner)) this._unhalt(a.owner); });
45
+ const held = P.take({ owner: a.owner, value: true }); // the stack's onChange sets this.halted (defineHoldStacks), same as engine.mod('halt')
46
+ return handle(a.owner, () => held.remove()); // this hold, not the name: a handle kept from an earlier one must not end a later one
46
47
  },
47
48
  /**
48
49
  * @internal The dev bridge and tests: end owner's halt (the handle's remove() calls this); with no halt held (a headless engine) it starts live running.
@@ -3,23 +3,35 @@
3
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
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
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).
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). An engine part that does
7
+ // not says why in notAtomic: a part nobody asked stays changed while the rest rolls back (rule R66).
7
8
  // 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
9
  // (the run's own events already went out and cannot be recalled), and the trace gets one 'ops:rollback' note.
9
10
 
10
- /** Copy the atomic parts that exist now: [[provider, plain copy]] @internal */
11
+ import { reportError } from '../base/errors.js';
12
+ import { codedError } from '../base/errorHints.js';
13
+
14
+ /** Copy the atomic parts: [[key, provider, plain copy or null]] @internal */
11
15
  export function snapshot(e) {
12
16
  const out = [];
13
- // a part with nothing to save is left out, as in a save: load() is never handed null
14
- for (const p of e.saves.providers.values()) if (p.atomic) { const d = p.save(); if (d != null) out.push([p, JSON.parse(JSON.stringify(d))]); }
17
+ // an exact copy, as a load's rollback point takes: through JSON a NaN came back as null
18
+ for (const [k, p] of e.saves.providers) if (p.atomic) { const d = p.save(); out.push([k, p, d == null ? null : structuredClone(d)]); }
15
19
  return out;
16
20
  }
17
21
 
22
+ /** What a part goes back to. load() is never handed null, so a part that had nothing and has something now takes its new-game data, as in a load's rollback (saveApply.js); with none it cannot go back, and says so */
23
+ function restored(e, k, p, d) {
24
+ if (d != null || p.save() == null) return d;
25
+ const S = e.session, parts = S._base ? S._baseData().parts : {}, base = Object.hasOwn(parts, k) ? parts[k] : null;
26
+ if (base == null) reportError(e, codedError('save-load-threw', `atomic op rollback: save part '${k}' keeps what the op wrote: its save() gave nothing before the op and it has no new-game state to go back to`), 'ops rollback', { soft: true });
27
+ return base ?? null;
28
+ }
29
+
18
30
  /** Put a snapshot back (guarded writes allowed, change events muted) @internal */
19
31
  export function rollback(e, snap) {
20
32
  const ev = e.events;
21
33
  ev.muted = (ev.muted || 0) + 1;
22
- try { e.ops.allow(() => { for (const [p, d] of snap) p.load(JSON.parse(JSON.stringify(d))); }); } finally { ev.muted--; }
34
+ try { e.ops.allow(() => { for (const [k, p, d] of snap) { const back = restored(e, k, p, d); if (back != null) p.load(structuredClone(back)); } }); } finally { ev.muted--; }
23
35
  if (ev.traceSize > 0) ev.note('ops:rollback', { data: { parts: snap.length } });
24
36
  }
25
37
 
@@ -29,4 +41,4 @@ export function markRolledBack(ops, seq, depth) {
29
41
  }
30
42
 
31
43
  /** Which state an op definition covers, for list / explain / the catalog: honest about what atomic means */
32
- 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;
44
+ export const atomicNote = d => d.atomic ? 'atomic: the parts declared atomic (world, inventory, containers, vars, quests, interactions, content, grids, random, scene) roll back if run fails; events, sound and other state do not (use after)' : null;
@@ -6,7 +6,7 @@ import { parseSchema, whyBad, checkOf, OP_TYPES as TYPES } from '../base/params.
6
6
 
7
7
  export const SOURCES = ['player', 'game', 'bridge', 'test', 'replay', 'net', 'editor'];
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', 'targets', 'atomic', 'after'];
9
+ const DEF_KEYS = ['desc', 'args', 'can', 'run', 'offers', 'reasons', 'undo', 'canUndo', 'net', 'owner', 'targets', 'atomic', 'after'];
10
10
  const STRINGS = {
11
11
  badName: "ops.define('{name}'): name an op noun.verb, e.g. 'shop.buy' (lowercase start, camelCase)",
12
12
  noRun: "ops.define('{name}'): run(e, args, ctx) is required; it changes state. Put the \"may I\" checks in can(e, args, ctx)",
@@ -83,14 +83,16 @@ export function checkArgs(e, d, args) {
83
83
  }
84
84
  }
85
85
 
86
- /** 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 */
87
- export function argRange(d, args) {
86
+ /** Release builds: what data can get wrong is still checked (a required arg, type, min / max / values, an id with no record), because a bad value from a UI or a net peer must not reach run. Returns a failure spec or null */
87
+ export function argRange(e, d, args) {
88
88
  if (!d.shape || !args) return null;
89
+ const bad = (field, actual, expected) => ({ code: 'badArgs', facts: [{ id: d.name, field, actual, expected }] });
89
90
  for (const key in d.shape) {
90
91
  const s = d.shape[key], v = args[key];
91
- if (v === undefined || !checkOf(s.type)(v)) { if (v !== undefined) return { code: 'badArgs', facts: [{ id: d.name, field: key, actual: v, expected: s.type }] }; continue; }
92
+ if (v === undefined) { if (!s.optional) return bad(key, v, s.type); continue; }
92
93
  const why = whyBad(s, v);
93
- if (why) return { code: 'badArgs', facts: [{ id: d.name, field: key, actual: v, expected: why }] };
94
+ if (why) return bad(key, v, why);
95
+ if (s.type === 'id' && e._things.sources.length && !e._things.source(v)) return bad(key, v, 'a world record id');
94
96
  }
95
97
  return null;
96
98
  }
@@ -12,16 +12,14 @@ export function failure(r) {
12
12
  return out;
13
13
  }
14
14
  /**
15
- * Freeze owner held while a save's parts load (saveApply.js). A part's load() may return a Promise (an async terrain, a streamed world): until the
16
- * last part is applied the game is half old, half new, so fixed steps stop (freeze) and ops refuse with code 'loading' (a click or a net message
17
- * arriving in that gap would change the old state and be wiped, or act on a mix). Shared here so ops and the loader name the same owner.
15
+ * Why ops refuse right now, or null. 'loading': the state is being replaced (saves.replacing, stateReplace.js). While a save reads, loads, rebuilds in
16
+ * afterLoad or rolls back the game is half old, half new, so a click or a net message arriving in that gap would change the old state and be wiped,
17
+ * or act on a mix. It comes first: a load that failed in dev also froze on the error, and the rollback under way is still the reason to wait.
18
+ * 'halted': a gameplay error froze the game. Any other freeze (a menu, a cutscene) does not stop ops.
18
19
  * @internal
19
20
  */
20
- export const PARTS_LOADING = 'threedog:load-parts';
21
- /** Why ops refuse right now: 'halted' (a gameplay error froze the game), 'loading' (save parts still loading), or null @internal */
22
21
  export function opsBlocked(e) {
23
- const f = e.stacks.get('freeze');
24
- return f.has('error') ? 'halted' : f.has(PARTS_LOADING) ? 'loading' : null;
22
+ return e.saves.replacing ? 'loading' : e.stacks.get('freeze').has('error') ? 'halted' : null;
25
23
  }
26
24
  /** True when can returned a usable structured failure */
27
25
  export const isStructured = r => r !== null && typeof r === 'object' && typeof r.code === 'string' && r.code.length > 0;
@@ -39,7 +39,7 @@ export function runOp(ops, name, args, opts) {
39
39
  if (ev.traceSize > 0) ev.note('op:' + name, { code: f.code, obj: args?.id });
40
40
  return ops._res(f);
41
41
  };
42
- 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
+ if (!DEV) { const bad = argRange(e, d, args); if (bad) return failed(failure(bad), null); } // release: the data checks still hold (dev throws earlier, in _ctx)
43
43
  ops._stack.push(name);
44
44
  const prevCtx = ops._last; ops._last = ctx;
45
45
  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)
@@ -60,7 +60,7 @@ export function runOp(ops, name, args, opts) {
60
60
  ops.revision++;
61
61
  if (d.after) {
62
62
  const hook = () => { try { d.after(e, args, value, ctx); } catch (err) { reportError(e, err, where + ' after'); } };
63
- 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
+ if (ops._txDepth > 0) ops._txAfter.push(() => ops._as(name, ctx, hook)); else hook(); // in or inside an atomic run: queue, so hooks run in commit order (nested first) when the outermost one ends; off the stack by then, so with its ctx
64
64
  }
65
65
  return { ok: true, value, revision: ops.revision };
66
66
  } catch (err) {
package/core/ops/owned.js CHANGED
@@ -16,7 +16,8 @@ import { codedError, coded } from '../base/errorHints.js';
16
16
 
17
17
  const STRINGS = { // yielded: the prefix up to "stopped writing it" is matched by tests (the owned-prop tag carries the fix); the rest leads with the next calls
18
18
  yielded: '{id} was changed outside the engine, so the engine stopped writing it (your value stays). Next: {manual} to own it on purpose (no warning);{set} ' +
19
- '{back} to give it back to the engine',
19
+ '{back} to give it back to the engine{from}',
20
+ from: '. Written at {at}',
20
21
  set: ' {set} to let the engine drive it and only adjust it;',
21
22
  };
22
23
 
@@ -56,6 +57,7 @@ class Owned {
56
57
  /** objects this property lives on (allowOwned matches them) */ this.objects = spec.objects ?? [];
57
58
  /** 'engine' | 'manual' | 'yielded' */ this.mode = 'engine';
58
59
  /** who took it: 'game' (manual()), or 'three' for a direct write */ this.by = 'engine';
60
+ /** @type {string | null} the line that made the engine yield, when the dev server saw it */ this.writtenAt = null;
59
61
  this._snap = null;
60
62
  this._onChange = spec.onChange;
61
63
  // once: the engine never writes it, it only keeps the value read here (renderer.toneMapping). So a direct write is the documented way to change it (yielding warns
@@ -70,9 +72,10 @@ class Owned {
70
72
  const v = flat(this._read());
71
73
  if (!differs(v, this._snap) || isExempt(this)) return;
72
74
  this._set('yielded', 'three');
75
+ if (DEV) this.writtenAt = this._e._picture?.outside(this.id) ?? null; // dev server only: who took it, as the writers tool saw it (core/inspect/pictureWriters.js)
73
76
  if (DEV && this._e.validate && !this._once) {
74
77
  const L = this.levels, back = L.back ?? L.manual.replace(/\(([^()]*)\)\s*$/, (_, a) => `(${a ? a + ', ' : ''}false)`);
75
- warnOnce(coded('owned-prop', fmt(STRINGS.yielded, { id: this.id, manual: L.manual, set: L.set ? fmt(STRINGS.set, { set: L.set }) : '', back })));
78
+ warnOnce(coded('owned-prop', fmt(STRINGS.yielded, { id: this.id, manual: L.manual, set: L.set ? fmt(STRINGS.set, { set: L.set }) : '', back, from: this.writtenAt ? fmt(STRINGS.from, { at: this.writtenAt }) : '' })));
76
79
  }
77
80
  }
78
81
  /**
@@ -96,7 +99,7 @@ class Owned {
96
99
  }
97
100
  /** describe().owned row: writer = who writes it now ('engine' | 'manual:<who>' | 'three (engine yielded)') */
98
101
  info() {
99
- return ({ part: this.part, key: this.key, writer: this.mode === 'engine' ? 'engine' : this.mode === 'yielded' ? 'three (engine yielded)' : `manual:${this.by}`, ...(this.levels.manual ? { manual: this.levels.manual } : {}) });
102
+ return ({ part: this.part, key: this.key, writer: this.mode === 'engine' ? 'engine' : this.mode === 'yielded' ? 'three (engine yielded)' : `manual:${this.by}`, ...(this.mode === 'yielded' && this.writtenAt ? { writtenAt: this.writtenAt } : {}), ...(this.levels.manual ? { manual: this.levels.manual } : {}) });
100
103
  }
101
104
  }
102
105
 
@@ -126,8 +129,22 @@ export function defineOwned(engine, spec) {
126
129
  const o = new Owned(engine, spec);
127
130
  const old = reg.get(spec.id); if (old) live.delete(old);
128
131
  reg.set(spec.id, o); live.add(o);
132
+ engine._picture?.owned(o); // dev server only: who writes it (core/inspect/pictureWriters.js)
129
133
  return o;
130
134
  }
135
+ /**
136
+ * An object a property lives on was replaced (start() fell back to another renderer, a game assigned engine.camera): each row follows it, the writers tool watches the new one, and
137
+ * what is there now is the new reference, because a replacement is not an outside write. The mode stays: a value the game took stays the game's.
138
+ * @param {any} engine @param {Map<any, any>} moved old object -> new object
139
+ */
140
+ export function movedOwned(engine, moved) {
141
+ for (const o of engine._owned?.values() ?? []) {
142
+ if (!o.objects.some(x => moved.has(x))) continue;
143
+ o.objects = o.objects.map(x => moved.get(x) ?? x);
144
+ engine._picture?.owned(o);
145
+ if (o._snap) o.mark();
146
+ }
147
+ }
131
148
  /** Remove registrations (a module disposed) @param {any} engine @param {Iterable<{ id: string }>} list */
132
149
  export function dropOwned(engine, list) { for (const o of list) { live.delete(o); if (engine._owned?.get(o.id) === o) engine._owned.delete(o.id); } }
133
150
 
@@ -12,8 +12,7 @@
12
12
  // taking again every frame would work too, but through ctx.mod it adds a cleanup entry per frame
13
13
  // - ONE layer table (LAYERS below), lowest first; inside a layer: set, then every add summed, then every mul, then every clamp.
14
14
  // A higher layer's set hides everything below. A number point is clamped to its own min / max last.
15
- // - two DIFFERENT owners `set` one point on one layer: development builds throw shared-conflict naming both (and their code lines); release
16
- // builds let the later write win. add / mul / clamp never conflict: they are meant to stack.
15
+ // - two DIFFERENT owners `set` one point on one layer: every build throws shared-conflict naming both (and their code lines), the first value stays. add / mul / clamp never conflict: they are meant to stack.
17
16
  // - the settings layer only restricts: clamp { max } or mul 0..1 on a number, set false on a value point; it can never raise a number or
18
17
  // switch something on (one exception a point opts into with settingsSet: key bindings, where the player's rebinding is a replacement).
19
18
  // It sits above system: a cutscene or menu cannot turn back on what the player turned off; only debug overrides the player
@@ -21,8 +20,8 @@
21
20
  // | 'top' (the latest holder is in charge: the camera) | 'one' (an exclusive slot: a second holder is shared-taken; module `provides`)
22
21
  // Plain JS stays first-class: a game's own fields and onFixed logic never need this; it is for things several owners write.
23
22
  // The registry (engine.stacks: define / get / mod, save, timers, describe().shared) is core/ops/stacks.js.
24
- import { codedError, coded } from '../base/errorHints.js';
25
- import { DEV, warnOnce, note } from '../base/validate.js';
23
+ import { codedError } from '../base/errorHints.js';
24
+ import { DEV, note } from '../base/validate.js';
26
25
  import { callerAt } from './stackFrames.js';
27
26
 
28
27
  /** The one layer table, lowest first. Who uses which: engine = the engine's own defaults and drivers, game = game code and
@@ -117,6 +116,7 @@ export class Stack {
117
116
  // where: the code line of the first take (dev only). Kept on rewrites, so a weather module re-taking every frame costs no stack walk
118
117
  const ent = { owner, id: o.id ?? null, since: this.all._at(), where: old ? old.where : callerAt(), op, value, layer, clock, until: o.for != null ? this.all._nowOf(clock) + o.for : null };
119
118
  m.set(owner, ent);
119
+ this.all.engine._picture?.sharedTook(this.name, ent); // dev server only: the point's history for explain({ value })
120
120
  if (ent.until != null) this.all._timedDirty = true;
121
121
  this._changed(o.id);
122
122
  return { owner, remove: () => { this._drop(owner, o.id, ent); }, change: v => this._rewrite(ent, v, at) };
@@ -152,8 +152,7 @@ export class Stack {
152
152
  return true;
153
153
  }
154
154
  /** @internal the conflict rule: another owner's set on the same layer, or another holder of an exclusive slot. The engine never picks silently:
155
- * dev builds throw naming both sides with copyable fixes; release builds let the later write win and warn once (an exclusive slot then drops
156
- * the earlier holder, so exactly one holds it). */
155
+ * every build (development and release alike) throws naming both sides with copyable fixes; the earlier entry stays. */
157
156
  _clash(m, owner, op, layer, at) {
158
157
  const slot = this.kind === 'one';
159
158
  if (!slot && op !== 'set') return;
@@ -169,9 +168,7 @@ export class Stack {
169
168
  + `(2) decide on another layer: engine.mod('${this.name}', { owner: '${owner}', set: ..., layer: '${layer === 'game' ? 'effect' : 'game'}' }); `
170
169
  + `(3) take it over on purpose: ${this.manual ?? `engine.mod('${this.name}', { owner: '${owner}', set: ..., layer: 'system' }) (hides every layer below)`}`;
171
170
  const code = slot ? 'shared-taken' : 'shared-conflict';
172
- if (DEV) throw codedError(code, msg);
173
- warnOnce(coded(code, `${msg}. In this build the later write wins`), `${code}:${this.name}:${e.owner}:${owner}`);
174
- if (slot) this._drop(e.owner, e.id ?? undefined, e);
171
+ throw codedError(code, msg);
175
172
  }
176
173
  }
177
174
  /** @internal remove owner's entry (only `ent` when given: a stale handle removes nothing) */
@@ -283,7 +280,7 @@ export class Stack {
283
280
  }
284
281
  /** @internal how the value was combined, in the order it was: "cave 180 × storm 0.6" (layer order, then set / add / mul / clamp) */
285
282
  _how(list, lead, from) {
286
- const show = v => (typeof v === 'number' ? String(+v.toFixed(4)) : JSON.stringify(v));
283
+ const show = v => (typeof v === 'number' ? String(+v.toFixed(4)) : typeof v === 'function' ? 'function' : JSON.stringify(v)); // a rule's value may be a function
287
284
  const parts = lead ? [] : [`default ${show(this.base)}`];
288
285
  for (const L of Object.values(LAYERS)) {
289
286
  if (L < from) continue;
@@ -26,7 +26,7 @@ export class Stacks {
26
26
  * createServices calls this once saves and events exist */
27
27
  _hook() {
28
28
  const e = this.engine;
29
- e.saves.register('stacks', { save: () => this._save(), load: d => this._load(d) });
29
+ e.saves.register('stacks', { notAtomic: 'a mod is ended through the handle its owner keeps, which a load cannot put back', save: () => this._save(), load: d => this._load(d) });
30
30
  // input.keys and input.gate key their entries by action name, not record id: a removed record 'fire' must not unbind the action 'fire'
31
31
  e.events.on('world:remove', ({ id }) => { for (const s of this._all.values()) if (s.per && !s.name.startsWith('input.')) s.dropId(id); });
32
32
  }
@@ -47,6 +47,27 @@ export class Stacks {
47
47
  if (this._pending[name]) { this._loadOne(s, this._pending[name]); delete this._pending[name]; }
48
48
  return s;
49
49
  }
50
+ /**
51
+ * @internal The reader behind ctx.rule: a replaceable rule is a plain shared point (kind 'value', per: 'optional', save: false), so owners, conflict
52
+ * errors, layers, cleanup with the module and describe().shared are the ones every other point has; nothing here is a second registry.
53
+ * Why the default lives in the reader and not in the point: two systems may share one rule ('fall' covers bodies and characters) and a module can be
54
+ * replaced and installed again, so asking for a rule that exists is normal, and each reader keeps its own default.
55
+ * Not saved because a function cannot be; whoever set one still holds it after a load, like a control hold.
56
+ * @param {string} name @param {any} def @param {string[] | null} [names] the built-in names a decision may be; default just def when def is a name
57
+ * @returns {{ name: string, value(id?: string): any, decide(id: string | undefined | null, facts: any): any }}
58
+ */
59
+ rule(name, def, names = typeof def === 'string' ? [def] : null) {
60
+ const s = this.has(name) ? this.get(name) : this.define(name, { kind: 'value', per: 'optional', save: false });
61
+ if (s.kind !== 'value' || s.per !== 'optional') throw codedError('engine-misuse', `ctx.rule('${name}'): '${name}' is already a shared point of another shape (kind ${s.kind}), not a rule; pick another name`);
62
+ const value = id => s.value(id ?? undefined, def);
63
+ return { name, value,
64
+ // the check runs at the decision, not at engine.mod: the point is plain and takes any value, and a function's answer can only be checked here anyway
65
+ decide: (id, facts) => {
66
+ const v = value(id), d = typeof v === 'function' ? v(facts, this.engine) : v;
67
+ if (typeof d === 'string' && names && !names.includes(d)) throw codedError('unknown-name', `rule '${name}'${id == null ? '' : ` for '${id}'`}: '${d}' is not one of its built-in names (${names.join(', ')}). Fix: engine.mod('${name}', { owner, set: ${names.map(n => `'${n}'`).join(' | ')} | false | (facts, engine) => decision })`);
68
+ return d;
69
+ } };
70
+ }
50
71
  /** @param {string} name @returns {Stack} */
51
72
  get(name) {
52
73
  const s = this._all.get(name);
@@ -4,7 +4,8 @@ import { codedError } from '../base/errorHints.js';
4
4
  // Two stores in the database:
5
5
  // slots key slot, value { slot, savedAt, json, rev } world saves (json is JSON text, with no localStorage 5MB cap); rev names the write
6
6
  // (`<tab id>:<n>`), so a tab can tell "the save I last saw" from "a newer one another tab wrote" (cross-tab safety, Saves._put)
7
- // blobs key [group, id], value { group, id, at, blob, meta } binary attachments (group tells the purpose, e.g. photos are 'photo'), stored separately and kept out of the world save
7
+ // blobs key [group, id], value { group, id, at, blob, meta, rev } binary attachments (group tells the purpose, e.g. photos are 'photo'), stored separately and kept out of the world save;
8
+ // rev as for slots. A row without one (an older build, a file import, the store used directly) claims nothing, so anyone may change it
8
9
  // On the localStorage fallback: only world saves are stored (key prefix + slot); attachments are not persisted (blobs reads return empty, writes are ignored).
9
10
  // Every method returns a Promise; a failed write (quota, IndexedDB error) rejects and Saves reports it in one place.
10
11
 
@@ -12,9 +13,14 @@ const STORES = { slots: { keyPath: 'slot' }, blobs: { keyPath: ['group', 'id'] }
12
13
 
13
14
  /** Turn an IDBRequest / IDBTransaction into a Promise */
14
15
  const req = r => new Promise((res, rej) => { r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error); });
15
- const tx = t => new Promise((res, rej) => { t.oncomplete = () => res(); t.onerror = t.onabort = () => rej(t.error); });
16
+ const tx = t => new Promise((res, rej) => { t.oncomplete = () => res(); t.onabort = () => rej(t.error); }); // abort, not error: a failed request fires error first, with t.error still null, and aborts after
16
17
  /** rev of a stored record: null = no record; '' = a record written before revs existed */
17
18
  const revOf = r => r == null ? null : r.rev ?? '';
19
+ /** The stored record is not the one the caller expected: nothing was written. stale holds that record */
20
+ const staleError = (key, cur) => Object.assign(new Error(`'${key}' was written by another tab`), { stale: cur });
21
+ /** Does a stored attachment belong to someone this tab has not seen? */
22
+ const claimed = (cur, expect) => cur?.rev != null && cur.rev !== expect;
23
+ const checkBlob = b => { if (!(b.blob instanceof Blob)) throw codedError('save-write', `attachment '${b.group}/${b.id}' must be a Blob, got ${String(b.blob)}`); };
18
24
 
19
25
  export class SaveStore {
20
26
  /** @param {string} name Database name (each game's saveKey differs, so they do not interfere) @param {string} prefix Key prefix for the localStorage fallback */
@@ -45,10 +51,7 @@ export class SaveStore {
45
51
  const out = [];
46
52
  for (let i = 0; i < localStorage.length; i++) {
47
53
  const k = localStorage.key(i);
48
- if (!k.startsWith(this.prefix)) continue;
49
- const json = localStorage.getItem(k);
50
- const slot = k.slice(this.prefix.length);
51
- try { out.push({ slot, savedAt: JSON.parse(json).savedAt, json, rev: localStorage.getItem(this._revKey(slot)) ?? '' }); } catch { /* skip corrupt saves */ }
54
+ if (k.startsWith(this.prefix)) out.push(this._lsGet(k.slice(this.prefix.length))); // a damaged save is listed too: check says corrupt, and a save may replace it
52
55
  }
53
56
  return out;
54
57
  }
@@ -60,7 +63,7 @@ export class SaveStore {
60
63
  _lsGet(slot) {
61
64
  const json = localStorage.getItem(this.prefix + slot);
62
65
  if (json == null) return null;
63
- let savedAt = 0; try { savedAt = JSON.parse(json).savedAt; } catch { /* corrupt: readSave refuses it later */ }
66
+ let savedAt = 0; try { savedAt = JSON.parse(json).savedAt ?? 0; } catch { /* corrupt: readSave refuses it later */ }
64
67
  return { slot, savedAt, json, rev: localStorage.getItem(this._revKey(slot)) ?? '' };
65
68
  }
66
69
  /** One world save, { slot, savedAt, json, rev } or null */
@@ -74,24 +77,34 @@ export class SaveStore {
74
77
  * { stale: stored record } and writes nothing. localStorage: get and set run in one synchronous turn, which is as atomic as it gets there.
75
78
  */
76
79
  async putSlot(slot, savedAt, json, rev, expect) {
77
- const stale = cur => Object.assign(new Error(`slot '${slot}' was written by another tab`), { stale: cur });
78
80
  if (this.mode === 'localStorage') {
79
- if (expect !== undefined) { const cur = this._lsGet(slot); if (revOf(cur) !== expect) throw stale(cur); }
80
- localStorage.setItem(this.prefix + slot, json); localStorage.setItem(this._revKey(slot), rev ?? ''); return;
81
+ if (expect !== undefined) { const cur = this._lsGet(slot); if (revOf(cur) !== expect) throw staleError(slot, cur); }
82
+ // the rev first: the small write cannot then fail after the save was already replaced
83
+ const revKey = this._revKey(slot), old = localStorage.getItem(revKey);
84
+ localStorage.setItem(revKey, rev ?? '');
85
+ try { localStorage.setItem(this.prefix + slot, json); }
86
+ catch (e) { if (old == null) localStorage.removeItem(revKey); else localStorage.setItem(revKey, old); throw e; }
87
+ return;
81
88
  }
82
- const t = this._tx('slots', 'readwrite'), st = t.objectStore('slots');
83
- let cur = null;
84
- if (expect !== undefined) {
85
- const g = st.get(slot);
86
- g.onsuccess = () => { cur = g.result ?? null; if (revOf(cur) !== expect) t.abort(); else st.put({ slot, savedAt, json, rev }); };
87
- } else st.put({ slot, savedAt, json, rev });
88
- try { await tx(t); } catch (e) { if (expect !== undefined && revOf(cur) !== expect) throw stale(cur); throw e; }
89
+ return this._change('slots', slot, cur => expect !== undefined && revOf(cur) !== expect, st => st.put({ slot, savedAt, json, rev }));
89
90
  }
90
- async deleteSlot(slot) {
91
- if (this.mode === 'localStorage') { localStorage.removeItem(this.prefix + slot); localStorage.removeItem(this._revKey(slot)); return; }
92
- const t = this._tx('slots', 'readwrite');
93
- t.objectStore('slots').delete(slot);
94
- await tx(t);
91
+ /** @internal Read the record, ask clash(record), and change it in ONE readwrite transaction: the compare every guarded write goes through */
92
+ async _change(store, key, clash, write) {
93
+ const t = this._tx(store, 'readwrite'), st = t.objectStore(store), g = st.get(key);
94
+ let lost = false, cur = null;
95
+ g.onsuccess = () => { cur = g.result ?? null; if ((lost = clash(cur))) t.abort(); else write(st); };
96
+ try { await tx(t); } catch (e) { if (lost) throw staleError(key, cur); throw e; }
97
+ }
98
+ /** Delete a save, with expect: only while the stored record is that one, as putSlot. A record already gone is no conflict: there is no newer progress to keep */
99
+ async deleteSlot(slot, expect) {
100
+ const clash = cur => expect !== undefined && cur != null && revOf(cur) !== expect;
101
+ if (this.mode === 'localStorage') {
102
+ const cur = this._lsGet(slot);
103
+ if (clash(cur)) throw staleError(slot, cur);
104
+ localStorage.removeItem(this.prefix + slot); localStorage.removeItem(this._revKey(slot));
105
+ return;
106
+ }
107
+ return this._change('slots', slot, clash, st => st.delete(slot));
95
108
  }
96
109
 
97
110
  /** One group of attachments, newest first: [{ group, id, at, blob, meta }]; omit group for all */
@@ -100,10 +113,13 @@ export class SaveStore {
100
113
  const all = await req(this._tx('blobs').objectStore('blobs').getAll());
101
114
  return all.filter(b => group == null || b.group === group).sort((a, b) => b.at - a.at);
102
115
  }
103
- async putBlob(group, id, blob, meta = null, at = Date.now()) { // wall-clock: when the attachment was stored, used for ordering
104
- if (this.mode === 'localStorage') return;
105
- const t = this._tx('blobs', 'readwrite');
106
- t.objectStore('blobs').put({ group, id, at, blob, meta });
116
+ async putBlob(group, id, blob, meta = null, at = Date.now()) { return this.putBlobs([{ group, id, blob, meta, at }]); } // wall-clock: when the attachment was stored, used for ordering
117
+ /** Several attachments in one transaction: all stored or none (a restore must not leave half of them) */
118
+ async putBlobs(list) {
119
+ list.forEach(checkBlob);
120
+ if (this.mode === 'localStorage' || !list.length) return;
121
+ const t = this._tx('blobs', 'readwrite'), st = t.objectStore('blobs');
122
+ try { for (const b of list) st.put(b); } catch (e) { t.abort(); throw e; }
107
123
  await tx(t);
108
124
  }
109
125
  async deleteBlob(group, id) {
@@ -113,5 +129,15 @@ export class SaveStore {
113
129
  await tx(t);
114
130
  }
115
131
 
132
+ /** @internal One attachment, only if no other tab claimed the row since the rev this tab saw (putSlot's compare). row: as stored, with its own rev */
133
+ async putBlobIf(row, expect) {
134
+ checkBlob(row);
135
+ if (this.mode !== 'localStorage') return this._change('blobs', [row.group, row.id], cur => claimed(cur, expect), st => st.put(row));
136
+ }
137
+ /** @internal deleteBlob with the same compare */
138
+ async deleteBlobIf(group, id, expect) {
139
+ if (this.mode !== 'localStorage') return this._change('blobs', [group, id], cur => claimed(cur, expect), st => st.delete([group, id]));
140
+ }
141
+
116
142
  close() { this.db?.close(); this.db = null; }
117
143
  }