@ancientpantheon/khronoton-core 0.2.0 → 0.4.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/CHANGELOG.md +19 -0
- package/README.md +15 -1
- package/dist/PactCodeMirror-HQTGE2K3.js +64 -0
- package/dist/blockchain/stoachain.d.ts +48 -0
- package/dist/blockchain/stoachain.js +27 -0
- package/dist/chunk-DK4CDPXH.js +379 -0
- package/dist/chunk-U3F5HEHO.js +1639 -0
- package/dist/context-BKtdrA2B.d.ts +363 -0
- package/dist/handlers/batch.d.ts +21 -0
- package/dist/handlers/batch.js +57 -0
- package/dist/handlers/context.d.ts +94 -0
- package/dist/handlers/context.js +75 -0
- package/dist/handlers/cronoton.d.ts +70 -0
- package/dist/handlers/cronoton.js +165 -0
- package/dist/handlers/execute.d.ts +30 -0
- package/dist/handlers/execute.js +227 -0
- package/dist/handlers/http.d.ts +85 -0
- package/dist/handlers/http.js +84 -0
- package/dist/handlers/index.d.ts +27 -0
- package/dist/handlers/index.js +34 -0
- package/dist/handlers/read.d.ts +29 -0
- package/dist/handlers/read.js +94 -0
- package/dist/hooks/index.d.ts +143 -0
- package/dist/hooks/index.js +2 -0
- package/dist/provider/index.d.ts +220 -0
- package/dist/provider/index.js +675 -0
- package/dist/seams-BvPnTSmg.d.ts +203 -0
- package/dist/types-u_nUX1Bg.d.ts +222 -0
- package/dist/ui/index.d.ts +235 -0
- package/dist/ui/index.js +3646 -0
- package/dist/ui.css +35 -0
- package/package.json +72 -4
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,25 @@ All notable changes to `@ancientpantheon/khronoton-core`.
|
|
|
4
4
|
|
|
5
5
|
The engine's pre-extraction history lives in the AncientHoldings hub, whose inline scheduler ("Cronoton") this package extracts and generalises.
|
|
6
6
|
|
|
7
|
+
## 0.4.0 — 2026-07-13
|
|
8
|
+
|
|
9
|
+
Made khronoton **chain-polyglot**: the package now ships the chain adapters it needs to talk to each supported chain, as a `/blockchain/<chain>` subpath family — rather than a separate npm package per chain. This keeps khronoton a single drop-in for every automaton while it speaks each chain's language natively. Root `.`/`/server`/`/handlers` outputs are unchanged.
|
|
10
|
+
|
|
11
|
+
- **`/blockchain/stoachain`** — `createStoachainRuntime(config?) → Promise<ChainRuntime>` wraps the `@stoachain/*` runtime (client, signing, gas, constants) into the core `ChainRuntime` seam, so a StoaChain automaton (Mnemosyne, Caduceus, Aletheia, …) injects one object instead of reaching for `@stoachain/*` directly. Loads the SDK via SEQUENTIAL `await import()` (concurrent `Promise.all` crashes Node 24 with `ERR_INTERNAL_ASSERTION`); an optional `nodeBaseUrl` routes `getPactUrl`. Future chains land as sibling `/blockchain/<chain>` subpaths.
|
|
12
|
+
- **Optional-peer model.** Each chain's SDK is an **optional peer dependency** (`@stoachain/*@^4.3.6` for `/blockchain/stoachain`) and is imported LAZILY inside the factory. So `npm install @ancientpantheon/khronoton-core` pulls zero chain SDKs, importing the subpath costs nothing, and only calling the factory needs the SDK — a consumer carries only the chain(s) it actually uses. `react` remains an optional peer for the `/provider`/`/hooks`/`/ui` subpaths.
|
|
13
|
+
- **Consolidation.** This folds in the previously-separate `@ancientpantheon/khronoton-stoachain` package (built + tested but never published to npm); that package is removed. Its tests move into core under `src/blockchain/`: 8 mocked adapter tests run in the normal gate, while the 2 real-`@stoachain` integration tests (`*.real.test.ts`) run via `npm run test:integration` — kept OUT of the publish/CI gate so a release never depends on the external chain SDK's behaviour in the CI environment.
|
|
14
|
+
- **Packaging.** `/blockchain/stoachain` carries dual `{ types, import, require }` conditions and is dist-smoked under both; it builds via tsup with `@stoachain/*` external, so the byte-stable `tsc` core (`.`/`/server`/`/handlers`) is untouched.
|
|
15
|
+
|
|
16
|
+
## 0.3.0 — 2026-07-13
|
|
17
|
+
|
|
18
|
+
Added the complete drop-in **codex-cronoton experience layer** — the UI, API handlers, and React data layer a consumer needs to reproduce the AncientHoldings Hub's cronoton UX end to end. The root `.` schedule engine and the `/server` automaton engine are **byte-unchanged** from 0.2.0 (verified by SHA-256 over the `dist/index.*` + `dist/server/**` outputs); this release is purely additive on new subpaths.
|
|
19
|
+
|
|
20
|
+
- **`/handlers` — framework-agnostic HTTP route handlers.** The full route surface over the `/server` store + executor — list / get / fires / signers / commit / edit / pause / resume / delete / simulate / execute-now / trigger / start-batch / get-batch / cancel-batch / recover — driven by a tiny `HandlerRequest`/`HandlerResponse` + `AuthSeam` contract so any router (Next.js route handlers, Express, …) mounts them without adaptation. Confirm-gated mutations raise a `NeedsConfirmError` the client layer re-prompts on.
|
|
21
|
+
- **`/provider` + `/hooks` — the React data layer.** `<KhronotonProvider adapter={…}>`, the 16-method `KhronotonAdapter` seam, two reference adapters (`createFetchAdapter` over HTTP, `createMemoryAdapter` over an in-process handler context), the shared `runGated` confirm→retry-once helper, and the data + action hooks (`useCronotons` / `useCronoton` / `useCronotonFires` [50/page + fires-while-running poller] / `useManualBatch` [batch poller] / `useCronotonActions` / the execute tier). Reference adapters keep their error contract via a shared status→seam map.
|
|
22
|
+
- **`/ui` + `/ui.css` — the React UI at full Hub parity.** Four screens: **List** (three access tiers, resolver pill, confirm-gated row actions), **Detail/Observe** (header actions with shared disable predicates, two-column metadata, the fire-history card with a 50/page pager, definition-drift flag, result tooltip, pluggable multi-tx renderer, and the wired recover affordance, plus the manual-batch and runtime-arg-trigger cards), **Builder** (two-pane Pact editor + Config/Payload/Gas Payer/Signatures/Execute tabs, create and edit, Simulate→AUTO-gas calibrate, commit gate), and a **Public** read-only transparency view. Styled entirely through `--khr-*` CSS variables scoped to `<KhronotonUiRoot>` — no Tailwind, no bundled assets.
|
|
23
|
+
- **Chain edge stays separate.** The `@stoachain/*` `ChainRuntime` implementation ships as the standalone `@ancientpantheon/khronoton-stoachain` adapter (peer-depending `@stoachain/*`), so `@ancientpantheon/khronoton-core` remains zero-runtime-dependency and chain-agnostic. `react` is an **optional peer** used only by the `/provider`, `/hooks`, and `/ui` subpaths.
|
|
24
|
+
- **Packaging.** All 6 JS subpaths carry dual `{ types, import, require }` conditions (dist-smoked under both `require` and `import`); `/ui.css` is a plain stylesheet export. `.tsx`/CSS entries build via tsup; `.`/`/server`/`/handlers` stay on plain `tsc` so the pre-existing outputs never move.
|
|
25
|
+
|
|
7
26
|
## 0.2.0 — 2026-07-12
|
|
8
27
|
|
|
9
28
|
Added the **server/automaton engine** on a new `@ancientpantheon/khronoton-core/server` subpath — the stand-alone layer a consuming Automaton (e.g. Mnemosyne) needs to run scheduled, signed, on-chain firing. The root `.` schedule engine (7-mode math + `tickOnce`) is byte-unchanged; this is purely additive.
|
package/README.md
CHANGED
|
@@ -6,7 +6,17 @@ Khronoton is the "When do I act?" Constructor of the Pantheon architecture — t
|
|
|
6
6
|
|
|
7
7
|
## Status
|
|
8
8
|
|
|
9
|
-
**`0.
|
|
9
|
+
**`0.4.0` on public npmjs** — the complete drop-in codex-cronoton experience, matching the AncientHoldings Hub, now **chain-polyglot**. On top of the byte-unchanged root `.` schedule engine and `/server` automaton engine (both from 0.2.0), the package ships the whole experience layer as subpaths so a consumer wires the Hub's cronoton UX end to end without re-implementing it:
|
|
10
|
+
|
|
11
|
+
- **`/handlers`** — framework-agnostic HTTP route handlers over the `/server` store + executor (list/get/fires/signers/commit/edit/pause/resume/delete/simulate/execute-now/trigger/batch/recover), driven by a tiny `HandlerRequest`/`HandlerResponse` seam so any router (Next.js, Express, …) can mount them.
|
|
12
|
+
- **`/provider` + `/hooks`** — the React data layer: `<KhronotonProvider adapter={…}>`, the 16-method `KhronotonAdapter` seam with two reference adapters (`createFetchAdapter` over HTTP, `createMemoryAdapter` over in-process handlers), the shared `runGated` confirm-retry, and the data + action hooks (`useCronotons`/`useCronoton`/`useCronotonFires`/`useManualBatch` + the lifecycle/execute action hooks).
|
|
13
|
+
- **`/ui` + `/ui.css`** — the React UI at full Hub parity: the four screens **List**, **Detail/Observe** (fire history with 50/page pager, definition-drift flag, result tooltip, pluggable multi-tx renderer, wired recover), **Builder** (two-pane create + edit, Config/Payload/Gas Payer/Signatures/Execute tabs, Simulate→AUTO-gas calibrate), and a **Public** read-only transparency view — themed entirely through `--khr-*` CSS variables inside `<KhronotonUiRoot>`.
|
|
14
|
+
|
|
15
|
+
Khronoton isn't chain-*agnostic* — it's chain-*polyglot*: the root schedule/tick engine orchestrates, and the **`/blockchain/<chain>`** subpath family teaches it to speak each supported chain's language natively (0.4.0):
|
|
16
|
+
|
|
17
|
+
- **`/blockchain/stoachain`** — `createStoachainRuntime(config?)` wraps the `@stoachain/*` runtime into the core `ChainRuntime` seam, so a StoaChain automaton injects one object instead of reaching for `@stoachain/*` directly. Future chains land as sibling subpaths (`/blockchain/<chain>`).
|
|
18
|
+
|
|
19
|
+
Each chain's SDK is an **optional peer dependency** (`@stoachain/*` for `/blockchain/stoachain`), and the adapter imports it lazily — so `npm install @ancientpantheon/khronoton-core` pulls **zero** chain SDKs, and you carry only the SDK(s) for the chain(s) you actually import. It's one package, one version, one drop-in for every automaton. Likewise React is an optional peer for the `/provider`, `/hooks`, and `/ui` subpaths only. Every JS subpath resolves under both import conditions (ESM `import` + CJS `require`); the root `.`, `/server`, and `/handlers` outputs are byte-identical to 0.3.0/0.2.0.
|
|
10
20
|
|
|
11
21
|
## Schedule engine
|
|
12
22
|
|
|
@@ -218,6 +228,10 @@ npm install @ancientpantheon/khronoton-core
|
|
|
218
228
|
|
|
219
229
|
## Version history
|
|
220
230
|
|
|
231
|
+
**v0.4.0** — Made khronoton **chain-polyglot**: added the `/blockchain/<chain>` subpath family, starting with `/blockchain/stoachain` (`createStoachainRuntime(config?)` → the core `ChainRuntime` seam, wrapping `@stoachain/*`). Each chain's SDK is an **optional peer dependency** imported lazily, so the package stays zero-SDK on install and a consumer carries only the chains it imports — one package, one drop-in for every automaton, rather than a separate npm package per chain. (This folds in the previously-separate `@ancientpantheon/khronoton-stoachain`, which is removed and was never published.) Root `.`/`/server`/`/handlers` outputs unchanged. React and `@stoachain/*` are optional peers for their respective subpaths only.
|
|
232
|
+
|
|
233
|
+
**v0.3.0** — Added the complete drop-in **experience layer** on new subpaths, byte-preserving the root `.` and `/server` outputs from 0.2.0: `/handlers` (framework-agnostic HTTP route handlers over the store + executor, behind a tiny request/response seam), `/provider` + `/hooks` (the React data layer — `<KhronotonProvider>`, the 16-method `KhronotonAdapter` seam with `createFetchAdapter`/`createMemoryAdapter` reference adapters, the shared `runGated` confirm-retry, and the data + action hooks), and `/ui` + `/ui.css` (the React UI at full Hub parity — the four screens List, Detail/Observe with the 50/page fire-history pager + definition-drift + result tooltip + pluggable multi-tx renderer + wired recover, the two-pane create/edit Builder with Simulate→AUTO-gas calibrate, and a Public read-only view — themed via `--khr-*` inside `<KhronotonUiRoot>`). Chain specifics stay out of core as the separate `@ancientpantheon/khronoton-stoachain` `ChainRuntime` adapter; core stays zero-runtime-dependency with React an optional peer for the three React subpaths. Every JS subpath resolves under both ESM `import` and CJS `require`.
|
|
234
|
+
|
|
221
235
|
**v0.2.0** — Added the server/automaton engine on the new `@ancientpantheon/khronoton-core/server` subpath (dual ESM `import` + CJS `require`), behind six injection seams (`KeyResolver`, `ChainRuntime`, `Database`, `onAudit`, `resolveFireMode`, `Config`): the store + atomic claim-before-fire (exactly-once, proven end-to-end), the headless single-transaction executor (never-throws-on-fire, dirty-read pre-flight, AUTO-gas calibrate, 504/derived-key recovery), the server tick + `startKhronotonLoop`, the server-resolver registry/dispatcher, and `installSchema` for the three tables — lifted faithfully from the AncientHoldings hub's inline `codex-cronoton` system and generalised. The root `.` schedule engine is unchanged.
|
|
222
236
|
|
|
223
237
|
**v0.1.1** — Packaging fix: added a `require` condition to the exports map so the package is a drop-in for CommonJS consumers (e.g. the hub's tsx/CJS worker) as well as ESM. No API or behaviour change from v0.1.0.
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import CodeMirror from '@uiw/react-codemirror';
|
|
2
|
+
import { EditorView } from '@codemirror/view';
|
|
3
|
+
import { jsx } from 'react/jsx-runtime';
|
|
4
|
+
|
|
5
|
+
// src/ui/PactCodeMirror.tsx
|
|
6
|
+
var GUTTER_BG = "#0d1117";
|
|
7
|
+
var ACTIVE_LINE_BG = "#161616";
|
|
8
|
+
var khronotonEditorTheme = EditorView.theme(
|
|
9
|
+
{
|
|
10
|
+
"&": {
|
|
11
|
+
backgroundColor: "var(--khr-panel, #0a0a0a)",
|
|
12
|
+
color: "var(--khr-mono, #d2d3d4)",
|
|
13
|
+
fontSize: "12px"
|
|
14
|
+
},
|
|
15
|
+
".cm-content": {
|
|
16
|
+
fontFamily: "var(--khr-mono-font, ui-monospace, monospace)",
|
|
17
|
+
caretColor: "var(--khr-accent, #f0a500)"
|
|
18
|
+
},
|
|
19
|
+
".cm-cursor, .cm-dropCursor": {
|
|
20
|
+
borderLeftColor: "var(--khr-accent, #f0a500)"
|
|
21
|
+
},
|
|
22
|
+
"&.cm-focused": {
|
|
23
|
+
outline: "none"
|
|
24
|
+
},
|
|
25
|
+
"&.cm-editor.cm-focused": {
|
|
26
|
+
outline: "1px solid var(--khr-accent, #f0a500)"
|
|
27
|
+
},
|
|
28
|
+
"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection": {
|
|
29
|
+
backgroundColor: "var(--khr-accent-tint, #1a1500)"
|
|
30
|
+
},
|
|
31
|
+
".cm-gutters": {
|
|
32
|
+
backgroundColor: GUTTER_BG,
|
|
33
|
+
color: "var(--khr-text-dim, #8a8f98)",
|
|
34
|
+
border: "none"
|
|
35
|
+
},
|
|
36
|
+
".cm-activeLine": { backgroundColor: ACTIVE_LINE_BG },
|
|
37
|
+
".cm-activeLineGutter": { backgroundColor: ACTIVE_LINE_BG }
|
|
38
|
+
},
|
|
39
|
+
{ dark: true }
|
|
40
|
+
);
|
|
41
|
+
function PactCodeMirror({
|
|
42
|
+
value,
|
|
43
|
+
onChange,
|
|
44
|
+
height
|
|
45
|
+
}) {
|
|
46
|
+
return /* @__PURE__ */ jsx(
|
|
47
|
+
CodeMirror,
|
|
48
|
+
{
|
|
49
|
+
value,
|
|
50
|
+
height: `${height}px`,
|
|
51
|
+
theme: khronotonEditorTheme,
|
|
52
|
+
basicSetup: {
|
|
53
|
+
lineNumbers: true,
|
|
54
|
+
foldGutter: false,
|
|
55
|
+
closeBrackets: false,
|
|
56
|
+
autocompletion: false,
|
|
57
|
+
highlightActiveLine: true
|
|
58
|
+
},
|
|
59
|
+
onChange
|
|
60
|
+
}
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export { PactCodeMirror as default };
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { C as ChainRuntime } from '../seams-BvPnTSmg.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* `@ancientpantheon/khronoton-core/blockchain/stoachain` — the StoaChain edge.
|
|
5
|
+
*
|
|
6
|
+
* khronoton is chain-POLYGLOT, not chain-agnostic: the root `.` schedule engine
|
|
7
|
+
* and the `/server` tick/store engine orchestrate, and each `/blockchain/<chain>`
|
|
8
|
+
* subpath teaches them to speak one chain's language. This one wraps the
|
|
9
|
+
* `@stoachain/*` runtime into the core {@link ChainRuntime} seam so a StoaChain
|
|
10
|
+
* automaton injects one object instead of reaching for `@stoachain/*` directly.
|
|
11
|
+
*
|
|
12
|
+
* The `@stoachain/*` packages are OPTIONAL PEER DEPENDENCIES: importing this
|
|
13
|
+
* subpath costs nothing (the SDK imports are lazy, inside the factory), so a
|
|
14
|
+
* consumer who never talks StoaChain never installs them. Only calling
|
|
15
|
+
* `createStoachainRuntime()` pulls the SDK — and a StoaChain automaton has it.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* Consumer-facing knobs for {@link createStoachainRuntime}. Every field is
|
|
19
|
+
* optional; an omitted field falls back to the corresponding `@stoachain/*`
|
|
20
|
+
* constant. `nodeBaseUrl`, when set, builds a per-chain Pact URL against the
|
|
21
|
+
* consumer's chainweb node; otherwise the runtime uses `constants.getPactUrl`.
|
|
22
|
+
*/
|
|
23
|
+
interface StoachainRuntimeConfig {
|
|
24
|
+
/** Consumer chainweb base; when set, builds getPactUrl, else uses constants.getPactUrl. */
|
|
25
|
+
nodeBaseUrl?: string;
|
|
26
|
+
/** Kadena network id; defaults to constants.KADENA_NETWORK. */
|
|
27
|
+
networkId?: string;
|
|
28
|
+
/** Kadena namespace; defaults to ouronetConstants.KADENA_NAMESPACE. */
|
|
29
|
+
namespace?: string;
|
|
30
|
+
/** Gas station account; defaults to ouronetConstants.STOA_AUTONOMIC_OURONETGASSTATION. */
|
|
31
|
+
gasStationAccount?: string;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Builds the {@link ChainRuntime} seam by wrapping the `@stoachain/*` runtime
|
|
35
|
+
* once. Async because `@stoachain/*` are `type:module` ESM: every value is
|
|
36
|
+
* pulled via `await import()` (a static value-import would break CJS `tsx`
|
|
37
|
+
* workers), every type via `import type`.
|
|
38
|
+
*
|
|
39
|
+
* The imports run SEQUENTIALLY, not via `Promise.all`. The `@stoachain/*` ESM
|
|
40
|
+
* modules internally `require()` one another; loading them concurrently races
|
|
41
|
+
* on Node's ESM/CJS interop and throws `ERR_INTERNAL_ASSERTION` ("Cannot
|
|
42
|
+
* require() ES Module ... not yet fully loaded") on Node 24+. Sequential
|
|
43
|
+
* awaits let each module (and its nested requires) fully settle before the next
|
|
44
|
+
* begins. This is a one-time cost at factory creation, so the latency is moot.
|
|
45
|
+
*/
|
|
46
|
+
declare function createStoachainRuntime(config?: StoachainRuntimeConfig): Promise<ChainRuntime>;
|
|
47
|
+
|
|
48
|
+
export { type StoachainRuntimeConfig, createStoachainRuntime };
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// src/blockchain/stoachain.ts
|
|
2
|
+
async function createStoachainRuntime(config) {
|
|
3
|
+
const client = await import('@stoachain/kadena-stoic-legacy/client');
|
|
4
|
+
const signing = await import('@stoachain/stoa-core/signing');
|
|
5
|
+
const gas = await import('@stoachain/stoa-core/gas');
|
|
6
|
+
const constants = await import('@stoachain/stoa-core/constants');
|
|
7
|
+
const ouronetConstants = await import('@stoachain/ouronet-core/constants');
|
|
8
|
+
const networkId = config?.networkId ?? constants.KADENA_NETWORK;
|
|
9
|
+
const namespace = config?.namespace ?? ouronetConstants.KADENA_NAMESPACE;
|
|
10
|
+
const gasStationAccount = config?.gasStationAccount ?? ouronetConstants.STOA_AUTONOMIC_OURONETGASSTATION;
|
|
11
|
+
const nodeBaseUrl = config?.nodeBaseUrl;
|
|
12
|
+
const getPactUrl = nodeBaseUrl ? (chainId) => `${nodeBaseUrl}/chainweb/0.0/${networkId}/chain/${chainId}/pact` : constants.getPactUrl;
|
|
13
|
+
return {
|
|
14
|
+
Pact: client.Pact,
|
|
15
|
+
createClient: client.createClient,
|
|
16
|
+
isSignedTransaction: client.isSignedTransaction,
|
|
17
|
+
universalSignTransaction: signing.universalSignTransaction,
|
|
18
|
+
calculateAutoGasLimit: gas.calculateAutoGasLimit,
|
|
19
|
+
anuToStoa: gas.anuToStoa,
|
|
20
|
+
getPactUrl,
|
|
21
|
+
networkId,
|
|
22
|
+
namespace,
|
|
23
|
+
gasStationAccount
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export { createStoachainRuntime };
|
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
import { useKhronotonAdapter, useKhronotonConfig, runGated } from './chunk-U3F5HEHO.js';
|
|
2
|
+
import { useState, useRef, useEffect, useCallback } from 'react';
|
|
3
|
+
|
|
4
|
+
function useCronotons(query) {
|
|
5
|
+
const adapter = useKhronotonAdapter();
|
|
6
|
+
const [cronotons, setCronotons] = useState([]);
|
|
7
|
+
const [loading, setLoading] = useState(true);
|
|
8
|
+
const [error, setError] = useState(null);
|
|
9
|
+
const mountedRef = useRef(true);
|
|
10
|
+
useEffect(() => {
|
|
11
|
+
mountedRef.current = true;
|
|
12
|
+
return () => {
|
|
13
|
+
mountedRef.current = false;
|
|
14
|
+
};
|
|
15
|
+
}, []);
|
|
16
|
+
const queryKey = JSON.stringify(query ?? null);
|
|
17
|
+
const load = useCallback(
|
|
18
|
+
async (isActive = () => mountedRef.current) => {
|
|
19
|
+
setLoading(true);
|
|
20
|
+
setError(null);
|
|
21
|
+
try {
|
|
22
|
+
const view = await adapter.list(query);
|
|
23
|
+
if (!isActive()) return;
|
|
24
|
+
setCronotons(view.codexCronotons);
|
|
25
|
+
} catch (err) {
|
|
26
|
+
if (!isActive()) return;
|
|
27
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
28
|
+
} finally {
|
|
29
|
+
if (isActive()) setLoading(false);
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
[adapter, queryKey]
|
|
33
|
+
);
|
|
34
|
+
useEffect(() => {
|
|
35
|
+
let active = true;
|
|
36
|
+
void load(() => active);
|
|
37
|
+
return () => {
|
|
38
|
+
active = false;
|
|
39
|
+
};
|
|
40
|
+
}, [load]);
|
|
41
|
+
return { cronotons, loading, error, refetch: () => load() };
|
|
42
|
+
}
|
|
43
|
+
function useCronoton(id) {
|
|
44
|
+
const adapter = useKhronotonAdapter();
|
|
45
|
+
const [cronoton, setCronoton] = useState(null);
|
|
46
|
+
const [loading, setLoading] = useState(true);
|
|
47
|
+
const [error, setError] = useState(null);
|
|
48
|
+
const mountedRef = useRef(true);
|
|
49
|
+
useEffect(() => {
|
|
50
|
+
mountedRef.current = true;
|
|
51
|
+
return () => {
|
|
52
|
+
mountedRef.current = false;
|
|
53
|
+
};
|
|
54
|
+
}, []);
|
|
55
|
+
const load = useCallback(
|
|
56
|
+
async (isActive = () => mountedRef.current) => {
|
|
57
|
+
setLoading(true);
|
|
58
|
+
setError(null);
|
|
59
|
+
try {
|
|
60
|
+
const view = await adapter.get(id);
|
|
61
|
+
if (!isActive()) return;
|
|
62
|
+
setCronoton(view.codexCronoton);
|
|
63
|
+
} catch (err) {
|
|
64
|
+
if (!isActive()) return;
|
|
65
|
+
setCronoton(null);
|
|
66
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
67
|
+
} finally {
|
|
68
|
+
if (isActive()) setLoading(false);
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
[adapter, id]
|
|
72
|
+
);
|
|
73
|
+
useEffect(() => {
|
|
74
|
+
let active = true;
|
|
75
|
+
void load(() => active);
|
|
76
|
+
return () => {
|
|
77
|
+
active = false;
|
|
78
|
+
};
|
|
79
|
+
}, [load]);
|
|
80
|
+
return { cronoton, loading, error, refetch: () => load() };
|
|
81
|
+
}
|
|
82
|
+
function useCronotonFires(id, opts = {}) {
|
|
83
|
+
const adapter = useKhronotonAdapter();
|
|
84
|
+
const config = useKhronotonConfig();
|
|
85
|
+
const pageSize = opts.pageSize ?? config.pageSize;
|
|
86
|
+
const cadence = config.pollCadenceMs;
|
|
87
|
+
const [fires, setFires] = useState([]);
|
|
88
|
+
const [total, setTotal] = useState(0);
|
|
89
|
+
const [page, setPageState] = useState(0);
|
|
90
|
+
const [loading, setLoading] = useState(false);
|
|
91
|
+
const [error, setError] = useState(null);
|
|
92
|
+
const pageCount = Math.max(1, Math.ceil(total / pageSize));
|
|
93
|
+
const offset = page * pageSize;
|
|
94
|
+
const totalRef = useRef(0);
|
|
95
|
+
totalRef.current = total;
|
|
96
|
+
const setPage = useCallback(
|
|
97
|
+
(next) => {
|
|
98
|
+
const maxPage = Math.max(0, Math.ceil(totalRef.current / pageSize) - 1);
|
|
99
|
+
setPageState(Math.min(Math.max(0, Math.floor(next)), maxPage));
|
|
100
|
+
},
|
|
101
|
+
[pageSize]
|
|
102
|
+
);
|
|
103
|
+
const mountedRef = useRef(true);
|
|
104
|
+
useEffect(() => {
|
|
105
|
+
mountedRef.current = true;
|
|
106
|
+
return () => {
|
|
107
|
+
mountedRef.current = false;
|
|
108
|
+
};
|
|
109
|
+
}, []);
|
|
110
|
+
const load = useCallback(
|
|
111
|
+
async (isActive = () => mountedRef.current) => {
|
|
112
|
+
setLoading(true);
|
|
113
|
+
setError(null);
|
|
114
|
+
try {
|
|
115
|
+
const res = await adapter.fires({ id, limit: pageSize, offset });
|
|
116
|
+
if (!isActive()) return;
|
|
117
|
+
setFires(res.fires);
|
|
118
|
+
setTotal(res.total);
|
|
119
|
+
} catch (err) {
|
|
120
|
+
if (!isActive()) return;
|
|
121
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
122
|
+
} finally {
|
|
123
|
+
if (isActive()) setLoading(false);
|
|
124
|
+
}
|
|
125
|
+
},
|
|
126
|
+
[adapter, id, pageSize, offset]
|
|
127
|
+
);
|
|
128
|
+
useEffect(() => {
|
|
129
|
+
if (typeof window === "undefined") return;
|
|
130
|
+
let active = true;
|
|
131
|
+
void load(() => active);
|
|
132
|
+
return () => {
|
|
133
|
+
active = false;
|
|
134
|
+
};
|
|
135
|
+
}, [load]);
|
|
136
|
+
const anyRunning = fires.some((f) => f.status === "running");
|
|
137
|
+
useEffect(() => {
|
|
138
|
+
if (typeof window === "undefined") return;
|
|
139
|
+
if (!anyRunning) return;
|
|
140
|
+
const timer = setInterval(() => {
|
|
141
|
+
adapter.fires({ id, limit: pageSize, offset }).then((res) => {
|
|
142
|
+
if (!mountedRef.current) return;
|
|
143
|
+
setFires(res.fires);
|
|
144
|
+
setTotal(res.total);
|
|
145
|
+
}).catch(() => {
|
|
146
|
+
});
|
|
147
|
+
}, cadence);
|
|
148
|
+
return () => clearInterval(timer);
|
|
149
|
+
}, [anyRunning, adapter, id, pageSize, offset, cadence]);
|
|
150
|
+
return { fires, total, page, pageCount, loading, error, setPage, refetch: () => void load() };
|
|
151
|
+
}
|
|
152
|
+
function toError(cause) {
|
|
153
|
+
return cause instanceof Error ? cause : new Error(String(cause));
|
|
154
|
+
}
|
|
155
|
+
function useManualBatch(id) {
|
|
156
|
+
const adapter = useKhronotonAdapter();
|
|
157
|
+
const config = useKhronotonConfig();
|
|
158
|
+
const [batch, setBatch] = useState(null);
|
|
159
|
+
const [loading, setLoading] = useState(true);
|
|
160
|
+
const [error, setError] = useState(null);
|
|
161
|
+
const mountedRef = useRef(true);
|
|
162
|
+
useEffect(() => {
|
|
163
|
+
mountedRef.current = true;
|
|
164
|
+
return () => {
|
|
165
|
+
mountedRef.current = false;
|
|
166
|
+
};
|
|
167
|
+
}, []);
|
|
168
|
+
const read = useCallback(
|
|
169
|
+
async (isActive = () => mountedRef.current) => {
|
|
170
|
+
setLoading(true);
|
|
171
|
+
try {
|
|
172
|
+
const res = await adapter.getBatch(id);
|
|
173
|
+
if (!isActive()) return;
|
|
174
|
+
setBatch(res.batch);
|
|
175
|
+
setError(null);
|
|
176
|
+
} catch (cause) {
|
|
177
|
+
if (!isActive()) return;
|
|
178
|
+
setError(toError(cause));
|
|
179
|
+
} finally {
|
|
180
|
+
if (isActive()) setLoading(false);
|
|
181
|
+
}
|
|
182
|
+
},
|
|
183
|
+
[adapter, id]
|
|
184
|
+
);
|
|
185
|
+
const refetch = useCallback(() => read(), [read]);
|
|
186
|
+
useEffect(() => {
|
|
187
|
+
let active2 = true;
|
|
188
|
+
void read(() => active2);
|
|
189
|
+
return () => {
|
|
190
|
+
active2 = false;
|
|
191
|
+
};
|
|
192
|
+
}, [read]);
|
|
193
|
+
const active = batch?.status === "active";
|
|
194
|
+
useEffect(() => {
|
|
195
|
+
if (!active) return;
|
|
196
|
+
const interval = setInterval(() => {
|
|
197
|
+
void adapter.getBatch(id).then((res) => {
|
|
198
|
+
if (mountedRef.current) setBatch(res.batch);
|
|
199
|
+
}).catch(() => {
|
|
200
|
+
});
|
|
201
|
+
}, config.pollCadenceMs);
|
|
202
|
+
return () => clearInterval(interval);
|
|
203
|
+
}, [active, adapter, id, config.pollCadenceMs]);
|
|
204
|
+
return { batch, active, loading, error, refetch };
|
|
205
|
+
}
|
|
206
|
+
function useGatedAction(makeCall, onNeedConfirm, onSuccess) {
|
|
207
|
+
const [pending, setPending] = useState(false);
|
|
208
|
+
const [error, setError] = useState(null);
|
|
209
|
+
const [result, setResult] = useState(null);
|
|
210
|
+
const mounted = useRef(true);
|
|
211
|
+
useEffect(() => {
|
|
212
|
+
mounted.current = true;
|
|
213
|
+
return () => {
|
|
214
|
+
mounted.current = false;
|
|
215
|
+
};
|
|
216
|
+
}, []);
|
|
217
|
+
const run = useCallback(
|
|
218
|
+
async (...args) => {
|
|
219
|
+
setPending(true);
|
|
220
|
+
setError(null);
|
|
221
|
+
try {
|
|
222
|
+
const body = await runGated(makeCall(...args), { onNeedConfirm });
|
|
223
|
+
if (mounted.current) {
|
|
224
|
+
setResult(body);
|
|
225
|
+
setPending(false);
|
|
226
|
+
}
|
|
227
|
+
onSuccess?.();
|
|
228
|
+
return { ok: true, result: body };
|
|
229
|
+
} catch (err) {
|
|
230
|
+
const surfaced = err instanceof Error ? err : new Error(String(err));
|
|
231
|
+
if (mounted.current) {
|
|
232
|
+
setError(surfaced);
|
|
233
|
+
setPending(false);
|
|
234
|
+
}
|
|
235
|
+
return { ok: false, error: surfaced };
|
|
236
|
+
}
|
|
237
|
+
},
|
|
238
|
+
[makeCall, onNeedConfirm, onSuccess]
|
|
239
|
+
);
|
|
240
|
+
return { run, pending, error, result };
|
|
241
|
+
}
|
|
242
|
+
function requireId(id, action) {
|
|
243
|
+
if (id == null) {
|
|
244
|
+
throw new Error(`useCronotonActions: an id is required to ${action} a cronoton`);
|
|
245
|
+
}
|
|
246
|
+
return id;
|
|
247
|
+
}
|
|
248
|
+
function useCronotonActions(id, options = {}) {
|
|
249
|
+
const adapter = useKhronotonAdapter();
|
|
250
|
+
const config = useKhronotonConfig();
|
|
251
|
+
const { onNeedConfirm } = config;
|
|
252
|
+
const { onSuccess } = options;
|
|
253
|
+
const create = useGatedAction(
|
|
254
|
+
useCallback((body) => (opts) => adapter.commit(body, opts), [adapter]),
|
|
255
|
+
onNeedConfirm,
|
|
256
|
+
onSuccess
|
|
257
|
+
);
|
|
258
|
+
const edit = useGatedAction(
|
|
259
|
+
useCallback(
|
|
260
|
+
(patch) => {
|
|
261
|
+
const target = requireId(id, "edit");
|
|
262
|
+
return (opts) => adapter.edit(target, patch, opts);
|
|
263
|
+
},
|
|
264
|
+
[adapter, id]
|
|
265
|
+
),
|
|
266
|
+
onNeedConfirm,
|
|
267
|
+
onSuccess
|
|
268
|
+
);
|
|
269
|
+
const pause = useGatedAction(
|
|
270
|
+
useCallback(() => {
|
|
271
|
+
const target = requireId(id, "pause");
|
|
272
|
+
return (opts) => adapter.pause(target, opts);
|
|
273
|
+
}, [adapter, id]),
|
|
274
|
+
onNeedConfirm,
|
|
275
|
+
onSuccess
|
|
276
|
+
);
|
|
277
|
+
const resume = useGatedAction(
|
|
278
|
+
useCallback(() => {
|
|
279
|
+
const target = requireId(id, "resume");
|
|
280
|
+
return (opts) => adapter.resume(target, opts);
|
|
281
|
+
}, [adapter, id]),
|
|
282
|
+
onNeedConfirm,
|
|
283
|
+
onSuccess
|
|
284
|
+
);
|
|
285
|
+
const remove = useGatedAction(
|
|
286
|
+
useCallback(() => {
|
|
287
|
+
const target = requireId(id, "delete");
|
|
288
|
+
return (opts) => adapter.delete(target, opts);
|
|
289
|
+
}, [adapter, id]),
|
|
290
|
+
onNeedConfirm,
|
|
291
|
+
onSuccess
|
|
292
|
+
);
|
|
293
|
+
return { create, edit, pause, resume, remove };
|
|
294
|
+
}
|
|
295
|
+
var IDLE = { pending: false, error: null };
|
|
296
|
+
function useExecuteAction(invoke) {
|
|
297
|
+
const adapter = useKhronotonAdapter();
|
|
298
|
+
const [state, setState] = useState(IDLE);
|
|
299
|
+
const mounted = useRef(true);
|
|
300
|
+
useEffect(() => {
|
|
301
|
+
mounted.current = true;
|
|
302
|
+
return () => {
|
|
303
|
+
mounted.current = false;
|
|
304
|
+
};
|
|
305
|
+
}, []);
|
|
306
|
+
const run = useCallback(
|
|
307
|
+
async (...args) => {
|
|
308
|
+
setState({ pending: true, error: null });
|
|
309
|
+
try {
|
|
310
|
+
const result = await invoke(adapter, ...args);
|
|
311
|
+
if (mounted.current) setState({ pending: false, error: null, result });
|
|
312
|
+
return result;
|
|
313
|
+
} catch (err) {
|
|
314
|
+
if (mounted.current) {
|
|
315
|
+
setState({ pending: false, error: err });
|
|
316
|
+
}
|
|
317
|
+
return void 0;
|
|
318
|
+
}
|
|
319
|
+
},
|
|
320
|
+
// `invoke` is a stable module-level function per hook; the adapter identity is
|
|
321
|
+
// stable per mount — so `run` only re-creates if the mounted adapter changes.
|
|
322
|
+
[adapter, invoke]
|
|
323
|
+
);
|
|
324
|
+
return { run, pending: state.pending, error: state.error, result: state.result };
|
|
325
|
+
}
|
|
326
|
+
function useExecuteNow() {
|
|
327
|
+
const { onNeedConfirm } = useKhronotonConfig();
|
|
328
|
+
return useExecuteAction(
|
|
329
|
+
useCallback(
|
|
330
|
+
(adapter, id) => runGated((opts) => adapter.executeNow(id, opts), { onNeedConfirm }),
|
|
331
|
+
[onNeedConfirm]
|
|
332
|
+
)
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
function useTrigger() {
|
|
336
|
+
const { onNeedConfirm } = useKhronotonConfig();
|
|
337
|
+
return useExecuteAction(
|
|
338
|
+
useCallback(
|
|
339
|
+
(adapter, id, args) => runGated((opts) => adapter.trigger(id, args, opts), { onNeedConfirm }),
|
|
340
|
+
[onNeedConfirm]
|
|
341
|
+
)
|
|
342
|
+
);
|
|
343
|
+
}
|
|
344
|
+
function useSimulate() {
|
|
345
|
+
const { onNeedConfirm } = useKhronotonConfig();
|
|
346
|
+
return useExecuteAction(
|
|
347
|
+
useCallback(
|
|
348
|
+
(adapter, envelope) => runGated((opts) => adapter.simulate(envelope, opts), { onNeedConfirm }),
|
|
349
|
+
[onNeedConfirm]
|
|
350
|
+
)
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
function useStartBatch() {
|
|
354
|
+
const { onNeedConfirm } = useKhronotonConfig();
|
|
355
|
+
return useExecuteAction(
|
|
356
|
+
useCallback(
|
|
357
|
+
(adapter, id, count) => runGated((opts) => adapter.startBatch(id, count, opts), { onNeedConfirm }),
|
|
358
|
+
[onNeedConfirm]
|
|
359
|
+
)
|
|
360
|
+
);
|
|
361
|
+
}
|
|
362
|
+
function useCancelBatch() {
|
|
363
|
+
return useExecuteAction(
|
|
364
|
+
useCallback((adapter, id) => adapter.cancelBatch(id), [])
|
|
365
|
+
);
|
|
366
|
+
}
|
|
367
|
+
function useRecoverFire() {
|
|
368
|
+
const { onNeedConfirm } = useKhronotonConfig();
|
|
369
|
+
return useExecuteAction(
|
|
370
|
+
useCallback(
|
|
371
|
+
(adapter, id, fireId, requestKey) => runGated((opts) => adapter.recover(id, fireId, requestKey, opts), {
|
|
372
|
+
onNeedConfirm
|
|
373
|
+
}),
|
|
374
|
+
[onNeedConfirm]
|
|
375
|
+
)
|
|
376
|
+
);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
export { useCancelBatch, useCronoton, useCronotonActions, useCronotonFires, useCronotons, useExecuteNow, useManualBatch, useRecoverFire, useSimulate, useStartBatch, useTrigger };
|