@spooky-sync/core 0.0.1-canary.98 → 1.0.0-beta.1
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/AGENTS.md +57 -21
- package/README.md +59 -16
- package/dist/index.d.ts +2096 -929
- package/dist/index.js +18217 -5019
- package/dist/live.d.ts +149 -0
- package/dist/live.js +739 -0
- package/dist/otel/index.d.ts +1 -1
- package/dist/pure.d.ts +401 -0
- package/dist/pure.js +24 -0
- package/dist/sqlite-open.js +392 -0
- package/dist/sqlite-worker.d.ts +1 -0
- package/dist/sqlite-worker.js +439 -0
- package/dist/sw.d.ts +207 -0
- package/dist/sw.js +393 -0
- package/dist/tabs-broker-worker.d.ts +8 -0
- package/dist/tabs-broker-worker.js +477 -0
- package/dist/types.d.ts +1968 -82
- package/dist/worker-edges.js +498 -0
- package/dist/worker-impersonation.js +60 -0
- package/dist/worker-ref-tables.d.ts +48 -0
- package/dist/worker-types.d.ts +112 -0
- package/dist/worker-types.js +73 -0
- package/package.json +34 -8
- package/scripts/check-broker-bundle.mjs +33 -0
- package/scripts/check-worker-entries.mjs +173 -0
- package/skills/sp00ky-core/SKILL.md +42 -8
- package/skills/sp00ky-core/references/config.md +8 -2
- package/src/boot/auth-flip.saga.test.ts +174 -0
- package/src/boot/auth-flip.saga.ts +77 -0
- package/src/boot/boot.saga.test.ts +203 -0
- package/src/boot/boot.saga.ts +146 -0
- package/src/boot/bucket-switch.saga.test.ts +191 -0
- package/src/boot/bucket-switch.saga.ts +151 -0
- package/src/boot/preload.saga.test.ts +96 -0
- package/src/boot/preload.saga.ts +45 -0
- package/src/bucket-blurhash.test.ts +148 -0
- package/src/client/bucket-handle.test.ts +195 -0
- package/src/client/bucket-handle.ts +352 -0
- package/src/client/router.test.ts +59 -0
- package/src/client/router.ts +104 -0
- package/src/client/runtime.test.ts +319 -0
- package/src/client/runtime.ts +307 -0
- package/src/client/services.test.ts +74 -0
- package/src/client/services.ts +437 -0
- package/src/client/sp00ky-client.test.ts +428 -0
- package/src/client/sp00ky-client.ts +737 -0
- package/src/index.ts +78 -0
- package/src/kernel/constants.test.ts +19 -0
- package/src/kernel/constants.ts +94 -0
- package/src/kernel/effects.test.ts +40 -0
- package/src/kernel/effects.ts +171 -0
- package/src/kernel/events.ts +60 -0
- package/src/kernel/interpreter.test.ts +116 -0
- package/src/kernel/interpreter.ts +148 -0
- package/src/kernel/saga.test.ts +89 -0
- package/src/kernel/saga.ts +73 -0
- package/src/live/index.test.ts +512 -0
- package/src/live/index.ts +1059 -0
- package/src/modules/app-release/index.test.ts +125 -0
- package/src/modules/app-release/index.ts +209 -0
- package/src/modules/auth/auth.local-first.test.ts +228 -0
- package/src/modules/auth/auth.session-recheck.test.ts +140 -0
- package/src/modules/auth/events/index.ts +7 -1
- package/src/modules/auth/impersonation-banner.ts +443 -0
- package/src/modules/auth/impersonation.integration.test.ts +209 -0
- package/src/modules/auth/impersonation.test.ts +377 -0
- package/src/modules/auth/impersonation.ts +179 -0
- package/src/modules/auth/index.ts +516 -34
- package/src/modules/channel/channel.test.ts +752 -0
- package/src/modules/channel/index.ts +1153 -0
- package/src/modules/channel/webrtc.ts +472 -0
- package/src/modules/crdt/acceptance.ts +75 -0
- package/src/modules/crdt/bytes.ts +50 -0
- package/src/modules/crdt/crdt-field.ts +82 -238
- package/src/modules/crdt/crdt.test.ts +546 -0
- package/src/modules/crdt/hash.ts +103 -0
- package/src/modules/crdt/index.ts +740 -271
- package/src/modules/crdt/loro-loader.ts +25 -0
- package/src/modules/crdt/mirror.ts +37 -0
- package/src/modules/devtools/flags.ts +349 -0
- package/src/modules/devtools/index.ts +661 -99
- package/src/modules/devtools/mutations.test.ts +92 -0
- package/src/modules/devtools/mutations.ts +160 -0
- package/src/modules/devtools/notify-throttle.test.ts +166 -0
- package/src/modules/devtools/state-shape.test.ts +263 -0
- package/src/modules/devtools/storage-info.test.ts +79 -0
- package/src/modules/devtools/storage-info.ts +168 -0
- package/src/modules/devtools/versions.ts +29 -0
- package/src/modules/feature-flag/index.test.ts +179 -1
- package/src/modules/feature-flag/index.ts +117 -10
- package/src/modules/ref-tables.test.ts +28 -1
- package/src/modules/ref-tables.ts +23 -1
- package/src/modules/web-push/index.test.ts +824 -0
- package/src/modules/web-push/index.ts +1027 -0
- package/src/mutation/ingest-outage.integration.test.ts +400 -0
- package/src/mutation/jobs.test.ts +25 -0
- package/src/mutation/jobs.ts +41 -0
- package/src/mutation/mutation-id.test.ts +37 -0
- package/src/mutation/mutation-id.ts +35 -0
- package/src/mutation/pending-writes.integration.test.ts +175 -0
- package/src/mutation/push.saga.test.ts +361 -0
- package/src/mutation/push.saga.ts +245 -0
- package/src/mutation/rows.test.ts +278 -0
- package/src/mutation/rows.ts +515 -0
- package/src/mutation/tray.saga.test.ts +63 -0
- package/src/mutation/tray.saga.ts +48 -0
- package/src/mutation/write.saga.test.ts +436 -0
- package/src/mutation/write.saga.ts +384 -0
- package/src/pure.ts +66 -0
- package/src/push/types.ts +174 -0
- package/src/query/anon-query-isolation.integration.test.ts +531 -0
- package/src/query/env.test.ts +23 -0
- package/src/query/env.ts +65 -0
- package/src/query/fetch.saga.test.ts +199 -0
- package/src/query/fetch.saga.ts +120 -0
- package/src/query/hash.test.ts +14 -0
- package/src/query/hash.ts +18 -0
- package/src/query/id-set-plan.test.ts +132 -0
- package/src/query/lifecycle.saga.test.ts +274 -0
- package/src/query/lifecycle.saga.ts +186 -0
- package/src/query/list-ref-live.integration.test.ts +203 -0
- package/src/query/materialize.saga.test.ts +200 -0
- package/src/query/materialize.saga.ts +102 -0
- package/src/query/materialize.test.ts +58 -0
- package/src/query/materialize.ts +57 -0
- package/src/query/membership.saga.test.ts +514 -0
- package/src/query/membership.saga.ts +339 -0
- package/src/query/membership.test.ts +151 -0
- package/src/query/membership.ts +234 -0
- package/src/query/register.saga.test.ts +369 -0
- package/src/query/register.saga.ts +293 -0
- package/src/query/render-set.test.ts +47 -0
- package/src/query/render-set.ts +71 -0
- package/src/query/session-guard.integration.test.ts +304 -0
- package/src/query/sql.test.ts +118 -0
- package/src/query/sql.ts +174 -0
- package/src/{modules/data → query}/window-query.test.ts +22 -4
- package/src/{modules/data → query}/window-query.ts +86 -8
- package/src/services/blobs/blob-cache.test.ts +359 -0
- package/src/services/blobs/blob-cache.ts +603 -0
- package/src/services/blobs/blob-manifest.ts +227 -0
- package/src/services/blobs/blob-store.test.ts +77 -0
- package/src/services/blobs/blob-store.ts +359 -0
- package/src/services/blobs/blob.fixture.ts +90 -0
- package/src/services/blobs/index.ts +70 -0
- package/src/services/database/cache-engine.ts +209 -0
- package/src/services/database/connection-supervisor.test.ts +318 -0
- package/src/services/database/connection-supervisor.ts +422 -0
- package/src/services/database/database.query-timeout.test.ts +140 -0
- package/src/services/database/database.responses.test.ts +43 -0
- package/src/services/database/database.ts +151 -56
- package/src/services/database/engine-factory.ts +33 -0
- package/src/services/database/errors.ts +34 -0
- package/src/services/database/index.ts +7 -0
- package/src/services/database/landed-body-clear.integration.test.ts +236 -0
- package/src/services/database/local-migrator.integration.test.ts +110 -0
- package/src/services/database/local-migrator.ts +54 -9
- package/src/services/database/local.test.ts +117 -0
- package/src/services/database/local.ts +364 -74
- package/src/services/database/plan-render.test.ts +159 -0
- package/src/services/database/plan-render.ts +108 -0
- package/src/services/database/relation-resolver.test.ts +484 -0
- package/src/services/database/relation-resolver.ts +0 -0
- package/src/services/database/remote.ts +283 -4
- package/src/services/database/sqlite-cache-engine.test.ts +628 -0
- package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
- package/src/services/database/sqlite-cache-engine.ts +1401 -0
- package/src/services/database/sqlite-column-reset.integration.test.ts +100 -0
- package/src/services/database/sqlite-column-reset.ts +91 -0
- package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
- package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
- package/src/services/database/sqlite-lock-verify.test.ts +33 -0
- package/src/services/database/sqlite-lock-verify.ts +45 -0
- package/src/services/database/sqlite-open.test.ts +150 -0
- package/src/services/database/sqlite-open.ts +164 -0
- package/src/services/database/sqlite-plan-sql.test.ts +164 -0
- package/src/services/database/sqlite-plan-sql.ts +196 -0
- package/src/services/database/sqlite-projection.test.ts +121 -0
- package/src/services/database/sqlite-select.integration.test.ts +185 -0
- package/src/services/database/sqlite-select.test.ts +261 -0
- package/src/services/database/sqlite-select.ts +131 -0
- package/src/services/database/sqlite-transport.fixture.ts +30 -0
- package/src/services/database/sqlite-transport.ts +229 -0
- package/src/services/database/sqlite-worker.ts +437 -0
- package/src/services/database/surql-translate.ts +417 -0
- package/src/services/database/surreal-cache-engine.ts +163 -0
- package/src/services/logger/index.test.ts +132 -0
- package/src/services/logger/index.ts +187 -6
- package/src/services/persistence/surrealdb.ts +2 -2
- package/src/services/stream-processor/index.ts +621 -93
- package/src/services/stream-processor/stream-processor.batch.test.ts +57 -7
- package/src/services/stream-processor/stream-processor.prime.test.ts +234 -0
- package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
- package/src/services/stream-processor/wasm-types.ts +41 -1
- package/src/services/tabs/broker-client.ts +284 -0
- package/src/services/tabs/broker.test.ts +381 -0
- package/src/services/tabs/coordinator.test.ts +386 -0
- package/src/services/tabs/coordinator.ts +646 -0
- package/src/services/tabs/fake-ports.fixture.ts +112 -0
- package/src/services/tabs/leader-locks.ts +75 -0
- package/src/services/tabs/protocol.ts +262 -0
- package/src/services/tabs/support.ts +36 -0
- package/src/services/tabs/tabs-broker-worker.ts +652 -0
- package/src/sp00ky.ts +5 -648
- package/src/state/client-state.ts +231 -0
- package/src/state/lifecycle.test.ts +184 -0
- package/src/state/lifecycle.ts +127 -0
- package/src/state/reducers.test.ts +337 -0
- package/src/state/reducers.ts +571 -0
- package/src/state/selectors.test.ts +203 -0
- package/src/state/selectors.ts +264 -0
- package/src/sw/index.test.ts +582 -0
- package/src/sw/index.ts +607 -0
- package/src/sw/store.ts +96 -0
- package/src/sync/connection.saga.test.ts +97 -0
- package/src/sync/connection.saga.ts +89 -0
- package/src/sync/live.saga.test.ts +229 -0
- package/src/sync/live.saga.ts +116 -0
- package/src/sync/policy.health.test.ts +56 -0
- package/src/{modules/sync/utils.test.ts → sync/policy.test.ts} +96 -11
- package/src/{modules/sync/utils.ts → sync/policy.ts} +186 -7
- package/src/sync/poll.saga.test.ts +51 -0
- package/src/sync/poll.saga.ts +36 -0
- package/src/sync/tabs.saga.test.ts +78 -0
- package/src/sync/tabs.saga.ts +96 -0
- package/src/testing/adapters.ts +137 -0
- package/src/testing/build.ts +63 -0
- package/src/testing/fake-services.ts +63 -0
- package/src/testing/run-pure.test.ts +92 -0
- package/src/testing/run-pure.ts +128 -0
- package/src/testing/services.ts +17 -0
- package/src/types.ts +568 -25
- package/src/utils/blurhash.ts +90 -0
- package/src/utils/edges.ts +57 -0
- package/src/utils/error-classification.test.ts +116 -0
- package/src/utils/error-classification.ts +74 -0
- package/src/utils/index.ts +58 -3
- package/src/utils/parser.test.ts +67 -102
- package/src/utils/parser.ts +62 -1
- package/src/utils/semver.test.ts +32 -0
- package/src/utils/semver.ts +30 -0
- package/src/utils/sha256.ts +15 -0
- package/src/utils/surql.ts +17 -15
- package/src/utils/utils.test.ts +3 -2
- package/tsdown.config.ts +64 -4
- package/vitest.config.ts +48 -0
- package/src/modules/cache/index.ts +0 -253
- package/src/modules/cache/types.ts +0 -19
- package/src/modules/crdt/crdt-hydration.test.ts +0 -206
- package/src/modules/data/data.status.test.ts +0 -108
- package/src/modules/data/data.test.ts +0 -58
- package/src/modules/data/index.ts +0 -1491
- package/src/modules/sync/engine.ts +0 -227
- package/src/modules/sync/events/index.ts +0 -84
- package/src/modules/sync/index.ts +0 -3
- package/src/modules/sync/queue/index.ts +0 -2
- package/src/modules/sync/queue/queue-down.ts +0 -90
- package/src/modules/sync/queue/queue-up.ts +0 -224
- package/src/modules/sync/scheduler.ts +0 -121
- package/src/modules/sync/sync.ts +0 -1244
- package/src/sp00ky.auth-order.test.ts +0 -65
|
@@ -1,26 +1,42 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import type {
|
|
1
|
+
import type { LocalStore, RemoteDatabaseService } from '../../services/database/index';
|
|
2
|
+
import type { Level } from 'pino';
|
|
3
|
+
import type { LogRead, LogTap, Logger } from '../../services/logger/index';
|
|
3
4
|
import type { SchemaStructure } from '@spooky-sync/query-builder';
|
|
4
5
|
import { RecordId } from 'surrealdb';
|
|
5
6
|
import type { StreamUpdate, StreamUpdateReceiver } from '../../services/stream-processor/index';
|
|
6
7
|
import { encodeRecordId } from '../../utils/index';
|
|
7
8
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
import type {
|
|
9
|
+
import type { MutationEventType, QueryState, QueryTimings } from '../../types';
|
|
10
|
+
import type { ClientState } from '../../state/client-state';
|
|
11
|
+
import {
|
|
12
|
+
parsePendingRow,
|
|
13
|
+
parseStoredRecordId,
|
|
14
|
+
storedIdString,
|
|
15
|
+
type FailedMutationRow,
|
|
16
|
+
type PendingMutationRow,
|
|
17
|
+
} from '../../mutation/rows';
|
|
18
|
+
import type {
|
|
19
|
+
AuthService,
|
|
20
|
+
ActiveImpersonation,
|
|
21
|
+
ImpersonationCandidate,
|
|
22
|
+
ImpersonationInfo,
|
|
23
|
+
} from '../auth/index';
|
|
18
24
|
import { AuthEventTypes } from '../auth/events/index';
|
|
19
25
|
import {
|
|
20
26
|
type BackendInfo,
|
|
21
27
|
emptyBackendInfo,
|
|
22
28
|
parseBackendInfo,
|
|
29
|
+
UNAVAILABLE,
|
|
23
30
|
} from './versions';
|
|
31
|
+
import { walkOpfs, type BlobCacheInfo, type SharedTabsInfo, type StorageInfo } from './storage-info';
|
|
32
|
+
import { FlagsAdminService, type LocalOverrideStore } from './flags';
|
|
33
|
+
import {
|
|
34
|
+
buildMutationsState,
|
|
35
|
+
queuedAtOf,
|
|
36
|
+
trimHistory,
|
|
37
|
+
type DevToolsMutationsState,
|
|
38
|
+
type MutationHistoryEntry,
|
|
39
|
+
} from './mutations';
|
|
24
40
|
|
|
25
41
|
// Real bundled frontend versions, injected at build time by tsdown's
|
|
26
42
|
// version-define plugin (see tsdown.config.ts). The `typeof` guard keeps these
|
|
@@ -34,29 +50,158 @@ const WASM_VERSION =
|
|
|
34
50
|
const SURREAL_VERSION =
|
|
35
51
|
typeof __SP00KY_SURREAL_VERSION__ !== 'undefined' ? __SP00KY_SURREAL_VERSION__ : 'unknown';
|
|
36
52
|
|
|
53
|
+
/** What DevTools reads about live queries; the runtime derives it from state. */
|
|
54
|
+
export interface DevToolsQuerySource {
|
|
55
|
+
getActiveQueries(): QueryState[];
|
|
56
|
+
getQueryById(id: RecordId<string>): QueryState | undefined;
|
|
57
|
+
phaseTimings(q: QueryState): QueryTimings;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export type ImpersonationOp = 'status' | 'listUsers' | 'start' | 'stop';
|
|
61
|
+
|
|
62
|
+
/** What the Mutations tab reads and does; the client wires it to the runtime. */
|
|
63
|
+
export interface DevToolsMutationSource {
|
|
64
|
+
state(): ClientState;
|
|
65
|
+
listFailed(): Promise<FailedMutationRow[]>;
|
|
66
|
+
retryFailed(mutationId: string): Promise<boolean>;
|
|
67
|
+
discardFailed(mutationId: string): Promise<boolean>;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export type MutationOp = 'listFailed' | 'get' | 'retry' | 'discard' | 'clearHistory';
|
|
71
|
+
|
|
72
|
+
export interface MutationOpResult {
|
|
73
|
+
success: boolean;
|
|
74
|
+
error?: string;
|
|
75
|
+
failed?: FailedMutationRow[];
|
|
76
|
+
/** `get`: the stored outbox row, or null once it left the outbox. */
|
|
77
|
+
row?: PendingMutationRow | null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export type LogOp = 'read' | 'setCaptureLevel' | 'clear';
|
|
81
|
+
|
|
82
|
+
export type LogOpResult = { success: boolean; error?: string } & Partial<LogRead>;
|
|
83
|
+
|
|
84
|
+
export interface ImpersonationOpResult {
|
|
85
|
+
success: boolean;
|
|
86
|
+
error?: string;
|
|
87
|
+
/** Whether the generated schema says the project enabled impersonation. */
|
|
88
|
+
enabled?: boolean;
|
|
89
|
+
isAdmin?: boolean;
|
|
90
|
+
current?: ImpersonationInfo | null;
|
|
91
|
+
active?: ActiveImpersonation[];
|
|
92
|
+
users?: ImpersonationCandidate[];
|
|
93
|
+
}
|
|
94
|
+
|
|
37
95
|
export class DevToolsService implements StreamUpdateReceiver {
|
|
38
|
-
private eventsHistory: DevToolsEvent[] = [];
|
|
39
|
-
private eventIdCounter = 0;
|
|
40
96
|
// Real bundled frontend version (injected at build time via tsdown `define`).
|
|
41
97
|
private version = CORE_VERSION;
|
|
42
98
|
// Backend stack info (versions + per-entity status), read via the
|
|
43
99
|
// `fn::spooky::info()` SurrealQL function; empty/'unavailable' until resolved.
|
|
44
100
|
private backendInfo: BackendInfo = emptyBackendInfo();
|
|
45
101
|
// Dormant until a devtools consumer (extension panel or MCP) handshakes via
|
|
46
|
-
// `SP00KY_DEVTOOLS_CONNECT`. While false, `notifyDevTools()
|
|
47
|
-
// work, so prod pays zero serialization/postMessage cost for an
|
|
102
|
+
// `SP00KY_DEVTOOLS_CONNECT`. While false, `notifyDevTools()` and the mutation
|
|
103
|
+
// history do no work, so prod pays zero serialization/postMessage cost for an
|
|
104
|
+
// unwatched panel.
|
|
48
105
|
// `window.__00__.getState()` stays live regardless, so the panel's first paint
|
|
49
106
|
// (the on-demand GET_STATE pull) still works before the push channel turns on.
|
|
50
107
|
private enabled = false;
|
|
51
108
|
|
|
109
|
+
// A state push serializes EVERY active query's full record set (see
|
|
110
|
+
// `getActiveQueries`) and postMessage clones it again, so its cost scales with
|
|
111
|
+
// the whole client dataset — and it is requested on every sync event (it used
|
|
112
|
+
// to be one per local DB query, when those were recorded as events).
|
|
113
|
+
// Unthrottled, a page load's burst of requests turned a handful of MB of rows
|
|
114
|
+
// into GBs of short-lived large-object garbage and OOMed the renderer (V8
|
|
115
|
+
// "young object promotion failed"). Coalesce instead: push immediately when
|
|
116
|
+
// idle, then at most once per window, always serializing the LATEST state.
|
|
117
|
+
private static readonly NOTIFY_MIN_INTERVAL_MS = 250;
|
|
118
|
+
private notifyTimer: ReturnType<typeof setTimeout> | null = null;
|
|
119
|
+
private lastNotifyAt = 0;
|
|
120
|
+
/** How many ids a pushed state carries per view; the rest is on demand. */
|
|
121
|
+
private static readonly STATE_IDS_CAP = 200;
|
|
122
|
+
/** devtools numeric hash -> the query's `_00_query` id, for on-demand rows. */
|
|
123
|
+
private hashToQuery = new Map<number, unknown>();
|
|
124
|
+
|
|
125
|
+
/** Shared-tabs snapshot for the panel, wired by Sp00kyClient whenever the
|
|
126
|
+
* feature was REQUESTED (so an inactive/degraded tab still reports why). */
|
|
127
|
+
private tabsInfoProvider: (() => SharedTabsInfo | null) | null = null;
|
|
128
|
+
|
|
129
|
+
setTabsInfoProvider(provider: () => SharedTabsInfo | null): void {
|
|
130
|
+
this.tabsInfoProvider = provider;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Blob cache counters for the panel, wired by Sp00kyClient. */
|
|
134
|
+
private blobInfoProvider: (() => BlobCacheInfo) | null = null;
|
|
135
|
+
|
|
136
|
+
/** Outbox, debounced writes and the failed tray, wired by Sp00kyClient. */
|
|
137
|
+
private mutationSource: DevToolsMutationSource | null = null;
|
|
138
|
+
/**
|
|
139
|
+
* Mutations seen since a consumer attached, by id, oldest first. The outbox
|
|
140
|
+
* only knows what is still queued; this is what lets the panel show a write
|
|
141
|
+
* as synced or rolled back after it left.
|
|
142
|
+
*/
|
|
143
|
+
private mutationHistory = new Map<string, MutationHistoryEntry>();
|
|
144
|
+
private static readonly MUTATIONS_CAP = 200;
|
|
145
|
+
|
|
146
|
+
setMutationSource(source: DevToolsMutationSource): void {
|
|
147
|
+
this.mutationSource = source;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* The page's log buffer. It records whether or not anybody is watching (so
|
|
152
|
+
* a panel opened late still sees the boot); while a consumer is attached,
|
|
153
|
+
* new lines go out as small `SP00KY_LOGS` deltas, never inside the state
|
|
154
|
+
* push, which would re-serialize the whole buffer every time.
|
|
155
|
+
*/
|
|
156
|
+
private logTap: LogTap | null = null;
|
|
157
|
+
/** `seq` of the newest line already pushed. */
|
|
158
|
+
private logCursor = 0;
|
|
159
|
+
private logTimer: ReturnType<typeof setTimeout> | null = null;
|
|
160
|
+
private lastLogPushAt = 0;
|
|
161
|
+
|
|
162
|
+
setLogTap(tap: LogTap): void {
|
|
163
|
+
this.logTap = tap;
|
|
164
|
+
this.logCursor = tap.head;
|
|
165
|
+
tap.subscribe(() => this.scheduleLogPush());
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
setBlobInfoProvider(provider: () => BlobCacheInfo): void {
|
|
169
|
+
this.blobInfoProvider = provider;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Full local table list (incl. internal `_00_*`), enumerated from the local DB
|
|
173
|
+
// via our own reliable `service.query` — the DevTools panel's page-eval query
|
|
174
|
+
// bridge is unreliable under load, so the panel relies on this instead.
|
|
175
|
+
private localTables: string[] = [];
|
|
176
|
+
private localTablesFetching = false;
|
|
177
|
+
private localTablesAt = 0;
|
|
178
|
+
|
|
179
|
+
// Feature flag admin, backing the panel's Access tab. The local-override
|
|
180
|
+
// store is injected later (`setFeatureFlagOverrides`) because the
|
|
181
|
+
// FeatureFlagModule is built after this service.
|
|
182
|
+
private featureOverrides: LocalOverrideStore | null = null;
|
|
183
|
+
private readonly flagsAdmin: FlagsAdminService;
|
|
184
|
+
|
|
52
185
|
constructor(
|
|
53
|
-
private databaseService:
|
|
186
|
+
private databaseService: LocalStore,
|
|
54
187
|
private remoteDatabaseService: RemoteDatabaseService,
|
|
55
188
|
private logger: Logger,
|
|
56
189
|
private schema: SchemaStructure,
|
|
57
190
|
private authService: AuthService<SchemaStructure>,
|
|
58
|
-
private dataManager?:
|
|
191
|
+
private dataManager?: DevToolsQuerySource
|
|
59
192
|
) {
|
|
193
|
+
this.flagsAdmin = new FlagsAdminService({
|
|
194
|
+
remote: this.remoteDatabaseService,
|
|
195
|
+
local: this.databaseService,
|
|
196
|
+
logger: this.logger,
|
|
197
|
+
currentUserId: () => {
|
|
198
|
+
const id = this.authService.currentUser?.id;
|
|
199
|
+
if (!id) return null;
|
|
200
|
+
return id instanceof RecordId ? encodeRecordId(id) : String(id);
|
|
201
|
+
},
|
|
202
|
+
overrides: () => this.featureOverrides,
|
|
203
|
+
});
|
|
204
|
+
|
|
60
205
|
this.exposeToWindow();
|
|
61
206
|
|
|
62
207
|
// Stay dormant until a devtools consumer announces itself. The extension's
|
|
@@ -68,6 +213,10 @@ export class DevToolsService implements StreamUpdateReceiver {
|
|
|
68
213
|
const type = (e.data as { type?: string } | undefined)?.type;
|
|
69
214
|
if (type === 'SP00KY_DEVTOOLS_CONNECT') {
|
|
70
215
|
this.enabled = true;
|
|
216
|
+
// The consumer pulls the backlog itself (`logOp('read')`); pushes
|
|
217
|
+
// carry only what arrives after this point.
|
|
218
|
+
this.logCursor = this.logTap?.head ?? 0;
|
|
219
|
+
this.refreshLocalTables();
|
|
71
220
|
this.notifyDevTools();
|
|
72
221
|
} else if (type === 'SP00KY_DEVTOOLS_DISCONNECT') {
|
|
73
222
|
this.enabled = false;
|
|
@@ -75,11 +224,24 @@ export class DevToolsService implements StreamUpdateReceiver {
|
|
|
75
224
|
});
|
|
76
225
|
}
|
|
77
226
|
|
|
78
|
-
// Subscribe to auth events
|
|
227
|
+
// Subscribe to auth events. The initial fire-and-forget version fetch (below)
|
|
228
|
+
// races the remote connection; on the free plan the remote DB (SurrealDB
|
|
229
|
+
// Cloud) has no guest access, so `fn::spooky::info()` is only callable once
|
|
230
|
+
// signed in. Re-fetch when auth resolves — until the versions actually land —
|
|
231
|
+
// instead of leaving them 'unavailable' forever.
|
|
79
232
|
this.authService.eventSystem.subscribe(AuthEventTypes.AuthStateChanged, () => {
|
|
80
|
-
this.
|
|
233
|
+
if (this.authService.isAuthenticated && this.backendInfo.versions.ssp === UNAVAILABLE) {
|
|
234
|
+
void this.refreshBackendVersions();
|
|
235
|
+
} else {
|
|
236
|
+
this.notifyDevTools();
|
|
237
|
+
}
|
|
81
238
|
});
|
|
82
239
|
|
|
240
|
+
// Push state when the local store reports its durability (the open happens
|
|
241
|
+
// during connect, typically before a panel attaches, so this mostly matters
|
|
242
|
+
// for a later bucket switch that loses OPFS).
|
|
243
|
+
this.databaseService.subscribeToStorageHealth?.(() => this.notifyDevTools());
|
|
244
|
+
|
|
83
245
|
// Fire-and-forget backend version discovery; re-push state when it lands.
|
|
84
246
|
void this.refreshBackendVersions();
|
|
85
247
|
|
|
@@ -117,6 +279,13 @@ export class DevToolsService implements StreamUpdateReceiver {
|
|
|
117
279
|
const queries = this.dataManager.getActiveQueries();
|
|
118
280
|
queries.forEach((q) => {
|
|
119
281
|
const queryHash = this.hashString(encodeRecordId(q.config.id));
|
|
282
|
+
const createdAt =
|
|
283
|
+
q.config.lastActiveAt instanceof Date
|
|
284
|
+
? q.config.lastActiveAt.getTime()
|
|
285
|
+
: new Date(q.config.lastActiveAt || Date.now()).getTime();
|
|
286
|
+
this.hashToQuery.set(queryHash, q.config.id);
|
|
287
|
+
const localArray = q.config.localArray ?? [];
|
|
288
|
+
const remoteArray = q.config.remoteArray ?? [];
|
|
120
289
|
result.set(queryHash, {
|
|
121
290
|
queryHash,
|
|
122
291
|
status: 'active',
|
|
@@ -124,82 +293,223 @@ export class DevToolsService implements StreamUpdateReceiver {
|
|
|
124
293
|
// registration flag above. `fetchStatus` is 'idle' | 'fetching'.
|
|
125
294
|
fetchStatus: q.status,
|
|
126
295
|
isFetching: q.status === 'fetching',
|
|
127
|
-
createdAt
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
lastUpdate: Date.now(),
|
|
296
|
+
createdAt,
|
|
297
|
+
// Real last-update time; before the first update it equals createdAt.
|
|
298
|
+
// (Previously Date.now(), which reset the column on every state push.)
|
|
299
|
+
lastUpdate: q.lastUpdatedAt ?? createdAt,
|
|
132
300
|
updateCount: q.updateCount,
|
|
301
|
+
ttl: q.config.ttl,
|
|
133
302
|
query: q.config.surql,
|
|
134
303
|
variables: q.config.params || {},
|
|
135
304
|
dataSize: q.records?.length || 0,
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
305
|
+
// Counts and (capped) ids only. The rows themselves used to ride along
|
|
306
|
+
// here: every push then deep-cloned every view's records twice
|
|
307
|
+
// (serialize + postMessage), on a 4k-row client dataset up to four
|
|
308
|
+
// times a second, from inside the ingest call stack. The panel pulls
|
|
309
|
+
// rows on demand through `getQueryRows` instead.
|
|
310
|
+
localCount: localArray.length,
|
|
311
|
+
remoteCount: remoteArray.length,
|
|
312
|
+
localIds: localArray.slice(0, DevToolsService.STATE_IDS_CAP).map(([id]) => id),
|
|
313
|
+
remoteIds: remoteArray.slice(0, DevToolsService.STATE_IDS_CAP).map(([id]) => id),
|
|
314
|
+
idsTruncated:
|
|
315
|
+
localArray.length > DevToolsService.STATE_IDS_CAP ||
|
|
316
|
+
remoteArray.length > DevToolsService.STATE_IDS_CAP,
|
|
317
|
+
// Membership state, so "why is this list empty" is answerable from
|
|
318
|
+
// the panel: is the server's set known, has a non-empty one been seen
|
|
319
|
+
// this session, how many empty reads were ignored.
|
|
320
|
+
membershipKnown: q.config.membershipKnown === true,
|
|
321
|
+
// What the bindings' `isAuthoritative()` reads: the known set's rows
|
|
322
|
+
// are painted, not just the set read.
|
|
323
|
+
authoritative: q.answered === true,
|
|
324
|
+
viewLost: q.viewLost === true,
|
|
325
|
+
serverState: q.serverState ?? null,
|
|
139
326
|
// Detailed per-phase processing-time breakdown (SSP sub-phases, local/
|
|
140
327
|
// remote record fetch, frontend reconcile, registration). Flows to both
|
|
141
328
|
// the DevTools panel and the MCP (which returns activeQueries verbatim).
|
|
142
|
-
timings: this.dataManager
|
|
329
|
+
timings: this.dataManager!.phaseTimings(q),
|
|
143
330
|
});
|
|
144
331
|
});
|
|
145
332
|
return result;
|
|
146
333
|
}
|
|
147
334
|
|
|
148
|
-
public
|
|
335
|
+
public onStreamUpdate(update: StreamUpdate) {
|
|
336
|
+
// A synthetic re-materialize is not an ingest (DataModule.scheduleRematerialize).
|
|
337
|
+
if (update.synthetic) return;
|
|
338
|
+
// Counts and timings, not the `localArray` itself: that is one [id, version]
|
|
339
|
+
// pair per row of the view. The Logs tab shows this line at debug.
|
|
149
340
|
this.logger.debug(
|
|
150
|
-
{
|
|
151
|
-
|
|
341
|
+
{
|
|
342
|
+
queryHash: update.queryHash,
|
|
343
|
+
op: update.op,
|
|
344
|
+
localCount: update.localArray?.length ?? 0,
|
|
345
|
+
materializationTimeMs: update.materializationTimeMs,
|
|
346
|
+
storeApplyMs: update.storeApplyMs,
|
|
347
|
+
circuitStepMs: update.circuitStepMs,
|
|
348
|
+
transformMs: update.transformMs,
|
|
349
|
+
Category: 'sp00ky-client::DevToolsService::onStreamUpdate',
|
|
350
|
+
},
|
|
351
|
+
'StreamUpdate'
|
|
152
352
|
);
|
|
153
|
-
|
|
353
|
+
this.notifyDevTools();
|
|
354
|
+
}
|
|
154
355
|
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
query: payload.sql,
|
|
158
|
-
variables: {},
|
|
159
|
-
});
|
|
356
|
+
public onMutation(payload: any[]) {
|
|
357
|
+
for (const p of payload) this.recordQueued(p);
|
|
160
358
|
this.notifyDevTools();
|
|
161
359
|
}
|
|
162
360
|
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
361
|
+
/** A write entered the outbox. */
|
|
362
|
+
private recordQueued(p: any): void {
|
|
363
|
+
if (!this.enabled || !p?.mutation_id) return;
|
|
364
|
+
const id = storedIdString(p.mutation_id);
|
|
365
|
+
const recordId = p.record_id ? encodeRecordId(p.record_id) : '';
|
|
366
|
+
this.mutationHistory.set(id, {
|
|
367
|
+
id,
|
|
368
|
+
op: (p.type ?? 'create') as MutationEventType,
|
|
369
|
+
recordId,
|
|
370
|
+
table: typeof p.tableName === 'string' ? p.tableName : recordId.split(':')[0],
|
|
371
|
+
fields: p.data && typeof p.data === 'object' ? Object.keys(p.data) : [],
|
|
372
|
+
queuedAt: queuedAtOf(id) || Date.now(),
|
|
373
|
+
});
|
|
374
|
+
trimHistory(this.mutationHistory, DevToolsService.MUTATIONS_CAP);
|
|
375
|
+
}
|
|
172
376
|
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
377
|
+
/** The server answered a write: accepted (`synced`) or rejected (`rolled-back`). */
|
|
378
|
+
public onMutationOutcome(e: {
|
|
379
|
+
mutationId: string;
|
|
380
|
+
recordId: string;
|
|
381
|
+
eventType: string;
|
|
382
|
+
status: 'synced' | 'rolled-back';
|
|
383
|
+
error?: string;
|
|
384
|
+
}): void {
|
|
385
|
+
if (!this.enabled) return;
|
|
386
|
+
const prev = this.mutationHistory.get(e.mutationId);
|
|
387
|
+
this.mutationHistory.set(e.mutationId, {
|
|
388
|
+
...(prev ?? {
|
|
389
|
+
id: e.mutationId,
|
|
390
|
+
op: e.eventType as MutationEventType,
|
|
391
|
+
recordId: e.recordId,
|
|
392
|
+
table: e.recordId.split(':')[0],
|
|
393
|
+
queuedAt: queuedAtOf(e.mutationId),
|
|
394
|
+
}),
|
|
395
|
+
outcome: { status: e.status, at: Date.now(), error: e.error },
|
|
176
396
|
});
|
|
397
|
+
trimHistory(this.mutationHistory, DevToolsService.MUTATIONS_CAP);
|
|
177
398
|
this.notifyDevTools();
|
|
178
399
|
}
|
|
179
400
|
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
{ update, Category: 'sp00ky-client::DevToolsService::onStreamUpdate' },
|
|
183
|
-
'StreamUpdate'
|
|
184
|
-
);
|
|
185
|
-
this.addEvent('STREAM_UPDATE', {
|
|
186
|
-
updates: [update],
|
|
187
|
-
});
|
|
401
|
+
/** Something the panel shows moved (a query's status, the outbox, sync health): re-push. */
|
|
402
|
+
public onStateChanged(): void {
|
|
188
403
|
this.notifyDevTools();
|
|
189
404
|
}
|
|
190
405
|
|
|
191
|
-
|
|
192
|
-
const
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
406
|
+
private mutationsState(): DevToolsMutationsState | null {
|
|
407
|
+
const source = this.mutationSource;
|
|
408
|
+
if (!source) return null;
|
|
409
|
+
const s = source.state();
|
|
410
|
+
return buildMutationsState({
|
|
411
|
+
outbox: s.outbox,
|
|
412
|
+
pendingWrites: s.pendingWrites.values(),
|
|
413
|
+
failedCount: s.failedCount,
|
|
414
|
+
tabRole: s.tabRole,
|
|
415
|
+
health: s.sync.health,
|
|
416
|
+
history: this.mutationHistory.values(),
|
|
417
|
+
cap: DevToolsService.MUTATIONS_CAP,
|
|
201
418
|
});
|
|
202
|
-
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* The Mutations tab's on-demand half: the failed tray (a local read), one
|
|
423
|
+
* queued row's payload, and the tray's retry / discard.
|
|
424
|
+
*/
|
|
425
|
+
public async mutationOp(op: MutationOp, args: Record<string, unknown>): Promise<MutationOpResult> {
|
|
426
|
+
const source = this.mutationSource;
|
|
427
|
+
if (!source) return { success: false, error: 'this client does not expose its mutations' };
|
|
428
|
+
const id = String(args.id ?? '');
|
|
429
|
+
try {
|
|
430
|
+
switch (op) {
|
|
431
|
+
case 'listFailed':
|
|
432
|
+
return this.serializeForDevTools({ success: true, failed: await source.listFailed() });
|
|
433
|
+
case 'get': {
|
|
434
|
+
const res = await this.databaseService.query<any>('SELECT * FROM $ids', {
|
|
435
|
+
ids: [parseStoredRecordId(id)],
|
|
436
|
+
});
|
|
437
|
+
const raw = Array.isArray(res?.[0]) ? res[0][0] : undefined;
|
|
438
|
+
return this.serializeForDevTools({ success: true, row: raw ? parsePendingRow(raw) : null });
|
|
439
|
+
}
|
|
440
|
+
case 'retry':
|
|
441
|
+
return (await source.retryFailed(id))
|
|
442
|
+
? { success: true }
|
|
443
|
+
: { success: false, error: `${id} is not in the failed tray` };
|
|
444
|
+
case 'discard':
|
|
445
|
+
return (await source.discardFailed(id))
|
|
446
|
+
? { success: true }
|
|
447
|
+
: { success: false, error: `${id} is not in the failed tray` };
|
|
448
|
+
case 'clearHistory':
|
|
449
|
+
this.mutationHistory.clear();
|
|
450
|
+
this.notifyDevTools();
|
|
451
|
+
return { success: true };
|
|
452
|
+
default:
|
|
453
|
+
return { success: false, error: `Unknown mutation op: ${String(op)}` };
|
|
454
|
+
}
|
|
455
|
+
} catch (e) {
|
|
456
|
+
return { success: false, error: e instanceof Error ? e.message : String(e) };
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** The Logs tab: read the buffer, change what it records, empty it. */
|
|
461
|
+
public logOp(op: LogOp, args: Record<string, unknown>): LogOpResult {
|
|
462
|
+
const tap = this.logTap;
|
|
463
|
+
if (!tap) return { success: false, error: 'this client does not capture its logs' };
|
|
464
|
+
try {
|
|
465
|
+
switch (op) {
|
|
466
|
+
case 'read': {
|
|
467
|
+
const limit = typeof args.limit === 'number' ? args.limit : undefined;
|
|
468
|
+
return { success: true, ...tap.read(Number(args.after ?? 0), limit) };
|
|
469
|
+
}
|
|
470
|
+
case 'setCaptureLevel':
|
|
471
|
+
tap.setCaptureLevel(String(args.level) as Level);
|
|
472
|
+
this.notifyDevTools();
|
|
473
|
+
return { success: true, captureLevel: tap.captureLevel, consoleLevel: tap.consoleLevel };
|
|
474
|
+
case 'clear':
|
|
475
|
+
tap.clear();
|
|
476
|
+
return { success: true, head: tap.head };
|
|
477
|
+
default:
|
|
478
|
+
return { success: false, error: `Unknown log op: ${String(op)}` };
|
|
479
|
+
}
|
|
480
|
+
} catch (e) {
|
|
481
|
+
return { success: false, error: e instanceof Error ? e.message : String(e) };
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/** Same coalescing as {@link notifyDevTools}, for the log delta channel. */
|
|
486
|
+
private scheduleLogPush(): void {
|
|
487
|
+
if (!this.enabled || typeof window === 'undefined' || this.logTimer !== null) return;
|
|
488
|
+
const waited = Date.now() - this.lastLogPushAt;
|
|
489
|
+
const delay = Math.max(0, DevToolsService.NOTIFY_MIN_INTERVAL_MS - waited);
|
|
490
|
+
this.logTimer = setTimeout(() => {
|
|
491
|
+
this.logTimer = null;
|
|
492
|
+
if (this.enabled) this.flushLogs();
|
|
493
|
+
}, delay);
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
private flushLogs(): void {
|
|
497
|
+
const tap = this.logTap;
|
|
498
|
+
if (!tap) return;
|
|
499
|
+
this.lastLogPushAt = Date.now();
|
|
500
|
+
const delta = tap.read(this.logCursor);
|
|
501
|
+
this.logCursor = delta.head;
|
|
502
|
+
if (delta.entries.length === 0) return;
|
|
503
|
+
window.postMessage(
|
|
504
|
+
{
|
|
505
|
+
type: 'SP00KY_LOGS',
|
|
506
|
+
source: 'sp00ky-devtools-page',
|
|
507
|
+
entries: delta.entries,
|
|
508
|
+
head: delta.head,
|
|
509
|
+
dropped: delta.dropped,
|
|
510
|
+
},
|
|
511
|
+
'*'
|
|
512
|
+
);
|
|
203
513
|
}
|
|
204
514
|
|
|
205
515
|
private hashString(str: string): number {
|
|
@@ -213,30 +523,65 @@ export class DevToolsService implements StreamUpdateReceiver {
|
|
|
213
523
|
return hash;
|
|
214
524
|
}
|
|
215
525
|
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
526
|
+
/** Unwrap a SurrealDB `INFO FOR DB` result to its `{ tables, ... }` object. */
|
|
527
|
+
private unwrapInfo(res: any): any {
|
|
528
|
+
if (!Array.isArray(res) || !res[0]) return null;
|
|
529
|
+
const first = res[0];
|
|
530
|
+
if (first && typeof first === 'object' && 'result' in first) return first.result;
|
|
531
|
+
if (Array.isArray(first)) return first[0];
|
|
532
|
+
return first;
|
|
219
533
|
}
|
|
220
534
|
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
535
|
+
/**
|
|
536
|
+
* Refresh the cached full local-table list from `INFO FOR DB`. Fire-and-forget
|
|
537
|
+
* and throttled — called from getState() so the panel gets every table
|
|
538
|
+
* (including internal `_00_*`) without running its own (flaky) queries.
|
|
539
|
+
*/
|
|
540
|
+
private refreshLocalTables(): void {
|
|
541
|
+
if (this.localTablesFetching) return;
|
|
542
|
+
const now = Date.now();
|
|
543
|
+
if (now - this.localTablesAt < 30_000) return;
|
|
544
|
+
this.localTablesFetching = true;
|
|
545
|
+
void this.databaseService
|
|
546
|
+
.query<any>('INFO FOR DB')
|
|
547
|
+
.then((res) => {
|
|
548
|
+
const info = this.unwrapInfo(res);
|
|
549
|
+
this.localTablesAt = Date.now();
|
|
550
|
+
if (info && info.tables) {
|
|
551
|
+
// The circuit snapshot table holds a BLOB, not JSON rows; the
|
|
552
|
+
// explorer cannot render it and has nothing to show for it.
|
|
553
|
+
const names = Object.keys(info.tables).filter((n) => n !== '_00_circuit_snapshot');
|
|
554
|
+
const changed =
|
|
555
|
+
names.length !== this.localTables.length ||
|
|
556
|
+
names.some((n, i) => n !== this.localTables[i]);
|
|
557
|
+
this.localTables = names;
|
|
558
|
+
if (changed) this.notifyDevTools();
|
|
559
|
+
}
|
|
560
|
+
})
|
|
561
|
+
.catch(() => {
|
|
562
|
+
// Ignore — fall back to the declared app schema below.
|
|
563
|
+
})
|
|
564
|
+
.finally(() => {
|
|
565
|
+
this.localTablesFetching = false;
|
|
566
|
+
});
|
|
231
567
|
}
|
|
232
568
|
|
|
233
|
-
private getState() {
|
|
569
|
+
private getState(opts: { refreshTables?: boolean } = {}) {
|
|
570
|
+
// The local-table list (`INFO FOR DB`, a local round trip) is refreshed on
|
|
571
|
+
// an explicit pull only, never by the push path: pushes follow every sync
|
|
572
|
+
// event, and a local query per push competed with the app's own writes for
|
|
573
|
+
// the single local op queue.
|
|
574
|
+
if (opts.refreshTables) this.refreshLocalTables();
|
|
234
575
|
return this.serializeForDevTools({
|
|
235
|
-
|
|
576
|
+
// The event log is gone (the Logs and Mutations tabs carry what it did);
|
|
577
|
+
// still sent empty because panels before canary.291 read it to tell this
|
|
578
|
+
// state shape apart from their own.
|
|
579
|
+
eventsHistory: [],
|
|
236
580
|
activeQueries: Object.fromEntries(this.getActiveQueries()),
|
|
237
581
|
auth: {
|
|
238
582
|
authenticated: this.authService.isAuthenticated,
|
|
239
583
|
userId: this.authService.currentUser?.id,
|
|
584
|
+
impersonation: this.authService.impersonation,
|
|
240
585
|
},
|
|
241
586
|
version: this.version,
|
|
242
587
|
versions: {
|
|
@@ -249,25 +594,195 @@ export class DevToolsService implements StreamUpdateReceiver {
|
|
|
249
594
|
entities: this.backendInfo.entities,
|
|
250
595
|
},
|
|
251
596
|
database: {
|
|
252
|
-
|
|
597
|
+
// Prefer the live local-table list (includes internal `_00_*`); fall
|
|
598
|
+
// back to the declared app schema until the first enumeration lands.
|
|
599
|
+
tables: this.localTables.length
|
|
600
|
+
? this.localTables
|
|
601
|
+
: this.schema.tables.map((t) => t.name),
|
|
253
602
|
tableData: {},
|
|
603
|
+
// Which backend answers "Local". The Database explorer labels its source
|
|
604
|
+
// picker with it and explains translation failures against `sqlite`,
|
|
605
|
+
// whose SurrealQL vocabulary is a bounded subset.
|
|
606
|
+
engine: this.databaseService.engineKind ?? 'custom',
|
|
607
|
+
// Durability of the local store. `fallback: true` means persistence was
|
|
608
|
+
// requested but the dataset is actually sitting in RAM.
|
|
609
|
+
storage: this.databaseService.storageHealth ?? { status: 'unknown', fallback: false },
|
|
610
|
+
// Shared-tabs role state (null when the feature is off / fell back).
|
|
611
|
+
tabs: this.tabsInfoProvider?.() ?? null,
|
|
254
612
|
},
|
|
613
|
+
// Outbox, debounced writes, tray count and recent outcomes. Small by
|
|
614
|
+
// construction (capped entries, field names only, never payloads).
|
|
615
|
+
mutations: this.mutationsState(),
|
|
616
|
+
// Log buffer metadata only; the lines travel as `SP00KY_LOGS` deltas and
|
|
617
|
+
// through `logOp('read')`.
|
|
618
|
+
logs: this.logTap
|
|
619
|
+
? {
|
|
620
|
+
head: this.logTap.head,
|
|
621
|
+
consoleLevel: this.logTap.consoleLevel,
|
|
622
|
+
captureLevel: this.logTap.captureLevel,
|
|
623
|
+
}
|
|
624
|
+
: null,
|
|
255
625
|
});
|
|
256
626
|
}
|
|
257
627
|
|
|
628
|
+
/**
|
|
629
|
+
* The Access tab's impersonation controls. Errors come back as
|
|
630
|
+
* `{ success: false, error }` with the server's own message, so the panel
|
|
631
|
+
* can show why (not an admin, feature disabled, target is an admin).
|
|
632
|
+
*/
|
|
633
|
+
public async impersonationOp(
|
|
634
|
+
op: ImpersonationOp,
|
|
635
|
+
args: Record<string, unknown>
|
|
636
|
+
): Promise<ImpersonationOpResult> {
|
|
637
|
+
const enabled = this.schema.policy?.impersonation === true;
|
|
638
|
+
try {
|
|
639
|
+
switch (op) {
|
|
640
|
+
case 'status': {
|
|
641
|
+
const current = this.authService.impersonation;
|
|
642
|
+
const snapshot = await this.flagsAdmin.getFlags().catch(() => null);
|
|
643
|
+
const isAdmin = snapshot?.isAdmin === true;
|
|
644
|
+
const active =
|
|
645
|
+
enabled && isAdmin && !current
|
|
646
|
+
? await this.authService.listActiveImpersonations().catch(() => [])
|
|
647
|
+
: [];
|
|
648
|
+
return this.serializeForDevTools({ success: true, enabled, isAdmin, current, active });
|
|
649
|
+
}
|
|
650
|
+
case 'listUsers':
|
|
651
|
+
return this.serializeForDevTools({
|
|
652
|
+
success: true,
|
|
653
|
+
users: await this.authService.searchImpersonationTargets(String(args.search ?? '')),
|
|
654
|
+
});
|
|
655
|
+
case 'start': {
|
|
656
|
+
const current = await this.authService.impersonate(
|
|
657
|
+
String(args.target ?? ''),
|
|
658
|
+
String(args.reason ?? '')
|
|
659
|
+
);
|
|
660
|
+
return this.serializeForDevTools({ success: true, current });
|
|
661
|
+
}
|
|
662
|
+
case 'stop':
|
|
663
|
+
await this.authService.stopImpersonating();
|
|
664
|
+
return { success: true, current: null };
|
|
665
|
+
default:
|
|
666
|
+
return { success: false, error: `Unknown impersonation op: ${String(op)}` };
|
|
667
|
+
}
|
|
668
|
+
} catch (e) {
|
|
669
|
+
return { success: false, error: e instanceof Error ? e.message : String(e) };
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/**
|
|
674
|
+
* Full storage diagnostics for the DevTools Storage tab. Every section is
|
|
675
|
+
* gathered independently and failures land in that section's `error` field,
|
|
676
|
+
* so one broken source (a mid-switch worker, a browser without OPFS) never
|
|
677
|
+
* blanks the whole panel.
|
|
678
|
+
*/
|
|
679
|
+
public async getStorageInfo(opts?: { tableCounts?: boolean }): Promise<StorageInfo> {
|
|
680
|
+
const nav = typeof navigator !== 'undefined' ? navigator : undefined;
|
|
681
|
+
|
|
682
|
+
const info: StorageInfo = {
|
|
683
|
+
at: Date.now(),
|
|
684
|
+
engine: {
|
|
685
|
+
kind: this.databaseService.engineKind ?? 'custom',
|
|
686
|
+
store: this.databaseService.getConfig()?.store ?? 'memory',
|
|
687
|
+
bucketId: this.databaseService.currentBucketId,
|
|
688
|
+
},
|
|
689
|
+
health: this.databaseService.storageHealth ?? { status: 'unknown', fallback: false },
|
|
690
|
+
tabs: this.tabsInfoProvider?.() ?? null,
|
|
691
|
+
browser: {},
|
|
692
|
+
opfs: { supported: false, entries: [], totalBytes: 0, truncated: false },
|
|
693
|
+
};
|
|
694
|
+
|
|
695
|
+
try {
|
|
696
|
+
if (nav?.storage?.estimate) {
|
|
697
|
+
const est = await nav.storage.estimate();
|
|
698
|
+
info.browser.usage = est.usage;
|
|
699
|
+
info.browser.quota = est.quota;
|
|
700
|
+
// Chrome-only per-storage-system breakdown; absent elsewhere.
|
|
701
|
+
const details = (est as any).usageDetails;
|
|
702
|
+
if (details && typeof details === 'object') info.browser.usageDetails = details;
|
|
703
|
+
}
|
|
704
|
+
if (nav?.storage?.persisted) {
|
|
705
|
+
info.browser.persisted = await nav.storage.persisted();
|
|
706
|
+
}
|
|
707
|
+
} catch (e) {
|
|
708
|
+
info.browser.error = e instanceof Error ? e.message : String(e);
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
info.opfs = await walkOpfs();
|
|
712
|
+
|
|
713
|
+
try {
|
|
714
|
+
info.blobs = this.blobInfoProvider?.();
|
|
715
|
+
} catch (e) {
|
|
716
|
+
this.logger.warn(
|
|
717
|
+
{ err: e, Category: 'sp00ky-client::DevToolsService::getStorageInfo' },
|
|
718
|
+
'Blob cache diagnostics failed'
|
|
719
|
+
);
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
const stats = (globalThis as any).__sqliteStats;
|
|
723
|
+
if (stats && typeof stats === 'object') {
|
|
724
|
+
info.sqliteStats = { ...stats, byType: { ...(stats.byType ?? {}) } };
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
try {
|
|
728
|
+
info.engineDiagnostics = await this.databaseService.getStorageDiagnostics?.(opts);
|
|
729
|
+
} catch (e) {
|
|
730
|
+
this.logger.warn(
|
|
731
|
+
{ err: e, Category: 'sp00ky-client::DevToolsService::getStorageInfo' },
|
|
732
|
+
'Engine storage diagnostics failed'
|
|
733
|
+
);
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
return this.serializeForDevTools(info);
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
/** Ask the browser to exempt this origin's storage from eviction. */
|
|
740
|
+
public async requestPersistentStorage(): Promise<{ granted: boolean }> {
|
|
741
|
+
try {
|
|
742
|
+
const granted = (await navigator.storage?.persist?.()) ?? false;
|
|
743
|
+
return { granted };
|
|
744
|
+
} catch {
|
|
745
|
+
return { granted: false };
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
/**
|
|
750
|
+
* Request a state push. Coalesced (see {@link NOTIFY_MIN_INTERVAL_MS}): the
|
|
751
|
+
* first call after an idle period pushes straight away so the panel stays
|
|
752
|
+
* responsive, and any calls during the window collapse into ONE trailing push
|
|
753
|
+
* that serializes the state as of the flush, not as of the request. Callers
|
|
754
|
+
* stay fire-and-forget.
|
|
755
|
+
*/
|
|
258
756
|
private notifyDevTools() {
|
|
259
757
|
// No consumer attached → no getState() serialization, no postMessage broadcast.
|
|
260
758
|
if (!this.enabled) return;
|
|
261
|
-
if (typeof window
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
759
|
+
if (typeof window === 'undefined') return;
|
|
760
|
+
// A trailing push is already queued; it will carry this change too.
|
|
761
|
+
if (this.notifyTimer !== null) return;
|
|
762
|
+
|
|
763
|
+
// Always a macrotask, never inline: this is called from inside the ingest
|
|
764
|
+
// and mutation call stacks (onStreamUpdate / onMutation), i.e. inside the
|
|
765
|
+
// `await db.create(...)` the app is waiting on. A push that serializes the
|
|
766
|
+
// state right there charged every write for the panel's refresh.
|
|
767
|
+
const waited = Date.now() - this.lastNotifyAt;
|
|
768
|
+
const delay = Math.max(0, DevToolsService.NOTIFY_MIN_INTERVAL_MS - waited);
|
|
769
|
+
this.notifyTimer = setTimeout(() => {
|
|
770
|
+
this.notifyTimer = null;
|
|
771
|
+
// Still gated on `enabled`: the panel may have disconnected while queued.
|
|
772
|
+
if (this.enabled) this.flushNotify();
|
|
773
|
+
}, delay);
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
private flushNotify() {
|
|
777
|
+
this.lastNotifyAt = Date.now();
|
|
778
|
+
window.postMessage(
|
|
779
|
+
{
|
|
780
|
+
type: 'SP00KY_STATE_CHANGED',
|
|
781
|
+
source: 'sp00ky-devtools-page',
|
|
782
|
+
state: this.getState(),
|
|
783
|
+
},
|
|
784
|
+
'*'
|
|
785
|
+
);
|
|
271
786
|
}
|
|
272
787
|
|
|
273
788
|
private serializeForDevTools(data: any, seen = new WeakSet<object>()): any {
|
|
@@ -308,6 +823,10 @@ export class DevToolsService implements StreamUpdateReceiver {
|
|
|
308
823
|
const result: Record<string, any> = {};
|
|
309
824
|
for (const key in data) {
|
|
310
825
|
if (Object.prototype.hasOwnProperty.call(data, key)) {
|
|
826
|
+
// Skip absent optional fields: recursing them would emit the STRING
|
|
827
|
+
// 'undefined' (the top-level mapping below), which panels then have
|
|
828
|
+
// to filter back out (see 3d84fe8a).
|
|
829
|
+
if (data[key] === undefined) continue;
|
|
311
830
|
result[key] = this.serializeForDevTools(data[key], seen);
|
|
312
831
|
}
|
|
313
832
|
}
|
|
@@ -317,16 +836,59 @@ export class DevToolsService implements StreamUpdateReceiver {
|
|
|
317
836
|
return data;
|
|
318
837
|
}
|
|
319
838
|
|
|
839
|
+
/**
|
|
840
|
+
* Hand the FeatureFlagModule to the Access tab so it can read and write local
|
|
841
|
+
* overrides. Called from `Sp00kyClient` once both are constructed; until then
|
|
842
|
+
* the override methods are no-ops that report an empty map.
|
|
843
|
+
*/
|
|
844
|
+
public setFeatureFlagOverrides(store: LocalOverrideStore): void {
|
|
845
|
+
this.featureOverrides = store;
|
|
846
|
+
}
|
|
847
|
+
|
|
320
848
|
private exposeToWindow() {
|
|
321
849
|
if (typeof window !== 'undefined') {
|
|
322
850
|
(window as any).__00__ = {
|
|
323
851
|
version: this.version,
|
|
324
|
-
getState: () => this.getState(),
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
852
|
+
getState: () => this.getState({ refreshTables: true }),
|
|
853
|
+
// The rows of ONE view, on demand. The pushed state carries counts and
|
|
854
|
+
// capped ids only (see getActiveQueries); the panel's Data tab and the
|
|
855
|
+
// MCP fetch the rows here when somebody actually looks at them.
|
|
856
|
+
getQueryRows: (queryHash: number) => {
|
|
857
|
+
const id = this.hashToQuery.get(Number(queryHash));
|
|
858
|
+
const q = id !== undefined ? this.dataManager?.getQueryById(id as any) : undefined;
|
|
859
|
+
if (!q) return null;
|
|
860
|
+
return this.serializeForDevTools({
|
|
861
|
+
queryHash: Number(queryHash),
|
|
862
|
+
data: q.records,
|
|
863
|
+
localArray: q.config.localArray,
|
|
864
|
+
remoteArray: q.config.remoteArray,
|
|
865
|
+
});
|
|
328
866
|
},
|
|
867
|
+
// ---- Feature flags (Access tab) --------------------------------
|
|
868
|
+
// Remote reads/writes are admin-gated by SurrealDB, not here: a
|
|
869
|
+
// non-admin gets an empty flag list, and the `fn::feature::*` calls
|
|
870
|
+
// are denied outright. The override methods are purely local and
|
|
871
|
+
// work signed out.
|
|
872
|
+
getFlags: () => this.flagsAdmin.getFlags(),
|
|
873
|
+
// ---- Impersonation (Access tab) --------------------------------
|
|
874
|
+
// Every op is authorized by SurrealDB (`fn::_00_impersonate::*` are
|
|
875
|
+
// admin-only and absent unless the project enabled the feature);
|
|
876
|
+
// nothing here grants anything.
|
|
877
|
+
impersonationOp: (op: ImpersonationOp, args?: Record<string, unknown>) =>
|
|
878
|
+
this.impersonationOp(op, args ?? {}),
|
|
879
|
+
// ---- Mutations + Logs tabs ---------------------------------------
|
|
880
|
+
mutationOp: (op: MutationOp, args?: Record<string, unknown>) => this.mutationOp(op, args ?? {}),
|
|
881
|
+
logOp: (op: LogOp, args?: Record<string, unknown>) => this.logOp(op, args ?? {}),
|
|
882
|
+
setFlagEnabled: (key: string, enabled: boolean) =>
|
|
883
|
+
this.flagsAdmin.setFlagEnabled(key, enabled),
|
|
884
|
+
setFlagUserVariant: (key: string, variant: string, remove: boolean, userId?: string) =>
|
|
885
|
+
this.flagsAdmin.setFlagUserVariant(key, variant, remove, userId),
|
|
886
|
+
setLocalFlagOverride: (key: string, variant: string | null, payload?: unknown) =>
|
|
887
|
+
this.flagsAdmin.setLocalFlagOverride(key, variant, payload),
|
|
888
|
+
clearLocalFlagOverrides: () => this.flagsAdmin.clearLocalFlagOverrides(),
|
|
329
889
|
refreshVersions: () => this.refreshBackendVersions(),
|
|
890
|
+
getStorageInfo: (opts?: { tableCounts?: boolean }) => this.getStorageInfo(opts),
|
|
891
|
+
requestPersistentStorage: () => this.requestPersistentStorage(),
|
|
330
892
|
getTableData: async (tableName: string) => {
|
|
331
893
|
try {
|
|
332
894
|
// Returns the first statement result as T.
|