@ekrooh/bare 0.7.0 → 0.8.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.
@@ -1,4 +1,4 @@
1
- import { a as invokeEvent } from "./messages-BxviiFuh.mjs";
1
+ import { a as invokeEvent } from "./messages-B5HQRbFA.mjs";
2
2
  // plugins/media/kinds.ts
3
3
  /** The media kinds the native picker understands. Internal (not an `exports`
4
4
  * entry): shared by the worklet plugin and the mock transport so both reject
package/dist/index.mjs CHANGED
@@ -1,3 +1,3 @@
1
1
  import { c as MAX_HEADER_BYTES, i as CoreError, l as MessageType, n as err, o as ErrorCode, r as ok, s as MAX_FRAME_BYTES, t as coerceErrorCode, u as VERSION } from "./errors-Bl5w-m62.mjs";
2
- import { a as invokeEvent, d as createPluginRouter, i as dispatchEvent, l as createPluginBus, n as createBareRuntimeContext, o as MessageProtocol, r as definePlugin, s as createProtocolMessenger, t as installWebConsoleCapture, u as createPluginRegistry } from "./messages-BxviiFuh.mjs";
2
+ import { a as invokeEvent, d as createPluginRouter, i as dispatchEvent, l as createPluginBus, n as createBareRuntimeContext, o as MessageProtocol, r as definePlugin, s as createProtocolMessenger, t as installWebConsoleCapture, u as createPluginRegistry } from "./messages-B5HQRbFA.mjs";
3
3
  export { CoreError, ErrorCode, MAX_FRAME_BYTES, MAX_HEADER_BYTES, MessageProtocol, MessageType, VERSION, coerceErrorCode, createBareRuntimeContext, createPluginBus, createPluginRegistry, createPluginRouter, createProtocolMessenger, definePlugin, dispatchEvent, err, installWebConsoleCapture, invokeEvent, ok };
@@ -493,9 +493,9 @@ function createSharedLogTail() {
493
493
  async function serverLogTail() {
494
494
  if (typeof fetch !== "function" || typeof window === "undefined") return null;
495
495
  try {
496
- const response = await Promise.race([fetch("/logs?tail=50&format=text"), new Promise((resolve) => setTimeout(() => resolve(null), INVOKE_TAIL_TIMEOUT_MS))]);
497
- if (response === null || !response.ok) return null;
498
- const lines = (await response.text()).split("\n").map((line) => line.trim()).filter((line) => line.length > 0).slice(-20);
496
+ const text = await Promise.race([fetch("/logs?tail=50&format=text").then((response) => response.ok ? response.text() : null), new Promise((resolve) => setTimeout(() => resolve(null), INVOKE_TAIL_TIMEOUT_MS))]);
497
+ if (text === null) return null;
498
+ const lines = text.split("\n").map((line) => line.trim()).filter((line) => line.length > 0).slice(-20);
499
499
  return lines.length > 0 ? lines.join(" | ") : null;
500
500
  } catch {
501
501
  return null;
@@ -1,5 +1,5 @@
1
1
  import { n as err, o as ErrorCode, r as ok } from "./errors-Bl5w-m62.mjs";
2
- import { r as definePlugin } from "./messages-BxviiFuh.mjs";
2
+ import { r as definePlugin } from "./messages-B5HQRbFA.mjs";
3
3
  import { discoverySpecs } from "./plugins-discovery-events.mjs";
4
4
  import { healthSpecs } from "./plugins-health-events.mjs";
5
5
  import { logsSpecs } from "./plugins-logs-events.mjs";
@@ -1,7 +1,7 @@
1
1
  import { n as err, o as ErrorCode, r as ok } from "./errors-Bl5w-m62.mjs";
2
- import { r as definePlugin } from "./messages-BxviiFuh.mjs";
3
- import { i as createDiscoveryPlugin, n as createLogsPlugin, r as createHealthPlugin, t as createPermissionsPluginStub } from "./plugin-BnDh08L_.mjs";
4
- import { i as isMediaKind, n as mediaSpecs, r as MEDIA_HOST_TIMEOUT_MS } from "./events-DUGMT3B9.mjs";
2
+ import { r as definePlugin } from "./messages-B5HQRbFA.mjs";
3
+ import { i as createDiscoveryPlugin, n as createLogsPlugin, r as createHealthPlugin, t as createPermissionsPluginStub } from "./plugin-a3LvQrmS.mjs";
4
+ import { i as isMediaKind, n as mediaSpecs, r as MEDIA_HOST_TIMEOUT_MS } from "./events-wkidvYuN.mjs";
5
5
  import crypto from "bare-crypto";
6
6
  // plugins/media/plugin.ts
7
7
  /** Most media mounts are consumed once and then linger. Cap how many stay
@@ -1,4 +1,4 @@
1
- import { a as invokeEvent } from "./messages-BxviiFuh.mjs";
1
+ import { a as invokeEvent } from "./messages-B5HQRbFA.mjs";
2
2
  // plugins/discovery/events.ts
3
3
  const discoverySpecs = { list: {
4
4
  pluginId: "core.discovery",
@@ -1,4 +1,4 @@
1
- import { a as invokeEvent } from "./messages-BxviiFuh.mjs";
1
+ import { a as invokeEvent } from "./messages-B5HQRbFA.mjs";
2
2
  // plugins/health/events.ts
3
3
  const healthSpecs = {
4
4
  ping: {
@@ -1,4 +1,4 @@
1
- import { a as invokeEvent } from "./messages-BxviiFuh.mjs";
1
+ import { a as invokeEvent } from "./messages-B5HQRbFA.mjs";
2
2
  // plugins/logs/events.ts
3
3
  const logsSpecs = {
4
4
  view: {
@@ -1 +1 @@
1
- export { t as mediaEvents, n as mediaSpecs } from "./events-DUGMT3B9.mjs";
1
+ export { t as mediaEvents, n as mediaSpecs } from "./events-wkidvYuN.mjs";
@@ -1,4 +1,4 @@
1
- import { a as invokeEvent } from "./messages-BxviiFuh.mjs";
1
+ import { a as invokeEvent } from "./messages-B5HQRbFA.mjs";
2
2
  // plugins/permissions/events.ts
3
3
  /**
4
4
  * A permission request shows a system prompt the user answers at their own pace
package/dist/plugins.mjs CHANGED
@@ -1 +1 @@
1
- export { t as createDefaultPlugins } from "./plugins-q6Wno9wN.mjs";
1
+ export { t as createDefaultPlugins } from "./plugins-BjPAr5r8.mjs";
package/dist/runtime.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { a as isCanonicalErrorCode, c as MAX_HEADER_BYTES, i as CoreError, l as MessageType, o as ErrorCode, s as MAX_FRAME_BYTES } from "./errors-Bl5w-m62.mjs";
2
- import { c as createRequestId, f as timerMs, m as isShortId, n as createBareRuntimeContext, p as FrameContentError } from "./messages-BxviiFuh.mjs";
3
- import { t as createDefaultPlugins } from "./plugins-q6Wno9wN.mjs";
2
+ import { c as createRequestId, f as timerMs, m as isShortId, n as createBareRuntimeContext, p as FrameContentError } from "./messages-B5HQRbFA.mjs";
3
+ import { t as createDefaultPlugins } from "./plugins-BjPAr5r8.mjs";
4
4
  import { t as createLogRingBuffer } from "./store-Bd2wL58k.mjs";
5
5
  import { TextDecoder, TextEncoder } from "bare-encoding";
6
6
  import fs from "bare-fs";
package/dist/sync.d.mts CHANGED
@@ -1,8 +1,9 @@
1
1
  import { a as Either, n as CoreError } from "./types-BC39OoZB.mjs";
2
2
  type SyncOptions<T> = {
3
- /** Existing directory for this device's sync identity and current room.
4
- * Pass `runtime.config.storage`. Without it (or if it is missing/unwritable)
5
- * identity and room live in memory and a restart starts a new room. */
3
+ /** Existing directory for this device's sync identity, current room and
4
+ * last published value. Pass `runtime.config.storage`. Without it (or if it
5
+ * is missing/unwritable) identity and room live in memory and a restart
6
+ * starts a new room. */
6
7
  storage?: string;
7
8
  /** Validates a peer's value. Return the typed value, or undefined to drop
8
9
  * it. Required. */
@@ -18,9 +19,12 @@ interface Sync<T> {
18
19
  invite(): string;
19
20
  /** Leave the current room and join the one named by `code`. */
20
21
  join(code: string): Either<CoreError, true>;
21
- /** Replace this device's value and send it to every connected device. */
22
+ /** Replace this device's value, save it when `storage` is set, and send it
23
+ * to every connected device. Returns `sync/save-failed` and changes nothing
24
+ * when the save fails. */
22
25
  publish(value: T): Either<CoreError, true>;
23
- /** Latest value of every device seen in this room: self first, then by peer id. */
26
+ /** Latest value of every device seen in this room: self first, then by peer
27
+ * id. This device's own value is kept across restarts when `storage` is set. */
24
28
  values(): SyncValue<T>[];
25
29
  /** Devices connected right now (not counting this one). */
26
30
  connected(): number;
package/dist/sync.mjs CHANGED
@@ -20,7 +20,7 @@ function topicForInvite(code) {
20
20
  return Buffer.from(crypto.createHash("sha-256").update(`ekrooh/sync/v1\n${code}`).digest());
21
21
  }
22
22
  // core/sync/sync-state-file.ts
23
- const FILE_NAME = "ekrooh-sync.json";
23
+ const FILE_NAME$1 = "ekrooh-sync.json";
24
24
  const SEED_PATTERN = /^[0-9a-f]{64}$/;
25
25
  const ROOM_PATTERN = /^[0-9a-f]{32}$/;
26
26
  function freshState() {
@@ -47,7 +47,7 @@ function readRaw(file) {
47
47
  * directory, or when it is unwritable, the state lives in memory. */
48
48
  function loadSyncState(storage) {
49
49
  if (storage === void 0 || storage === "") return ok(freshState());
50
- const file = path.join(storage, FILE_NAME);
50
+ const file = path.join(storage, FILE_NAME$1);
51
51
  const raw = readRaw(file);
52
52
  if (raw.found) {
53
53
  let parsed;
@@ -74,7 +74,7 @@ let warnedWrite = false;
74
74
  * warning) when the write fails; callers carry on in memory. */
75
75
  function saveSyncState(storage, state) {
76
76
  if (storage === void 0 || storage === "") return false;
77
- const file = path.join(storage, FILE_NAME);
77
+ const file = path.join(storage, FILE_NAME$1);
78
78
  const tmp = `${file}.tmp`;
79
79
  try {
80
80
  fs.writeFileSync(tmp, JSON.stringify(state));
@@ -88,6 +88,48 @@ function saveSyncState(storage, state) {
88
88
  return false;
89
89
  }
90
90
  }
91
+ // core/sync/sync-values-file.ts
92
+ const FILE_NAME = "ekrooh-sync-values.json";
93
+ /** Reads this device's last published value. Missing, unreadable or rejected
94
+ * values give undefined (one warning when a file existed but is unusable). */
95
+ function loadSelfValue(storage, parse) {
96
+ if (storage === void 0 || storage === "") return void 0;
97
+ const file = path.join(storage, FILE_NAME);
98
+ let text;
99
+ try {
100
+ text = fs.readFileSync(file, "utf8");
101
+ } catch (error) {
102
+ if (error.code !== "ENOENT") console.warn(`[sync] could not read ${file}; starting without it`);
103
+ return;
104
+ }
105
+ let value;
106
+ try {
107
+ const record = JSON.parse(text);
108
+ if (record.version === 1) value = parse(record.self);
109
+ } catch {
110
+ value = void 0;
111
+ }
112
+ if (value === void 0) console.warn(`[sync] ${file} is unreadable; starting without it`);
113
+ return value;
114
+ }
115
+ /** Writes this device's value through a tmp file + rename. Without a storage
116
+ * directory nothing is written (in memory by design). */
117
+ function saveSelfValue(storage, value) {
118
+ if (storage === void 0 || storage === "") return ok(true);
119
+ const file = path.join(storage, FILE_NAME);
120
+ const tmp = `${file}.tmp`;
121
+ try {
122
+ fs.writeFileSync(tmp, JSON.stringify({
123
+ version: 1,
124
+ self: value
125
+ }));
126
+ fs.renameSync(tmp, file);
127
+ return ok(true);
128
+ } catch (error) {
129
+ const reason = error instanceof Error ? error.message : String(error);
130
+ return err("sync/save-failed", `Could not save ${file}: ${reason}`);
131
+ }
132
+ }
91
133
  /** Largest line a peer may send before the connection is dropped. */
92
134
  const MAX_LINE_BYTES = 32768;
93
135
  /** One wire line: `{"v":1,"value":<json>}\n`. */
@@ -142,7 +184,12 @@ function createSyncWith(options, deps) {
142
184
  let room = state.room;
143
185
  let topic = topicForInvite(room);
144
186
  let selfLine;
145
- let selfValue;
187
+ let selfValue = loadSelfValue(options.storage, options.parse);
188
+ if (selfValue !== void 0) {
189
+ const [encodeError, line] = encodeSyncLine(selfValue);
190
+ if (encodeError === null) selfLine = line;
191
+ else selfValue = void 0;
192
+ }
146
193
  let closed = false;
147
194
  const fire = () => {
148
195
  for (const listener of [...listeners]) try {
@@ -272,6 +319,8 @@ function createSyncWith(options, deps) {
272
319
  if (closed) return err("sync/closed", "This sync was closed.");
273
320
  const [error, line] = encodeSyncLine(value);
274
321
  if (error !== null) return [error, null];
322
+ const [saveError] = saveSelfValue(options.storage, value);
323
+ if (saveError !== null) return [saveError, null];
275
324
  selfLine = line;
276
325
  selfValue = value;
277
326
  for (const peer of peers.values()) for (const conn of peer.conns) conn.write(line);
@@ -52,6 +52,12 @@ interface MessageTransport {
52
52
  * `TRANSPORT_ERROR`. Later sends fail the same way. Optional so existing
53
53
  * custom transports still satisfy the interface. */
54
54
  close?(): void;
55
+ /** Resolves once the transport is open, or has stopped trying (gave up,
56
+ * closed, replaced). A request's timeout starts when the caller invokes, so
57
+ * a request queued behind a slow connect can time out before it was ever
58
+ * sent; awaiting this first starts that clock at the socket. Optional so
59
+ * existing custom transports still satisfy the interface. */
60
+ ready?(): Promise<void>;
55
61
  }
56
62
  export declare function createWebSocketTransport(urlOrOptions?: string | CreateWebSocketTransportOptions): MessageTransport;
57
63
  /**
@@ -1,7 +1,7 @@
1
1
  import { l as MessageType, n as err, o as ErrorCode, r as ok } from "./errors-Bl5w-m62.mjs";
2
- import { d as createPluginRouter, o as MessageProtocol, r as definePlugin, u as createPluginRegistry } from "./messages-BxviiFuh.mjs";
3
- import { i as createDiscoveryPlugin, n as createLogsPlugin, r as createHealthPlugin, t as createPermissionsPluginStub } from "./plugin-BnDh08L_.mjs";
4
- import { i as isMediaKind, n as mediaSpecs } from "./events-DUGMT3B9.mjs";
2
+ import { d as createPluginRouter, o as MessageProtocol, r as definePlugin, u as createPluginRegistry } from "./messages-B5HQRbFA.mjs";
3
+ import { i as createDiscoveryPlugin, n as createLogsPlugin, r as createHealthPlugin, t as createPermissionsPluginStub } from "./plugin-a3LvQrmS.mjs";
4
+ import { i as isMediaKind, n as mediaSpecs } from "./events-wkidvYuN.mjs";
5
5
  import { t as createLogRingBuffer } from "./store-Bd2wL58k.mjs";
6
6
  import { Actor, RealClock, event, state } from "@mantaq/core";
7
7
  // web/connection-machine.ts
@@ -269,6 +269,10 @@ function createWebSocketTransport(urlOrOptions = {}) {
269
269
  const credential = (typeof window !== "undefined" ? window.__ekrooh : void 0)?.bootstrap;
270
270
  const shouldLogin = options.login !== false && typeof credential === "string" && credential.length > 0;
271
271
  const listeners = /* @__PURE__ */ new Set();
272
+ const readyWaiters = [];
273
+ const releaseReady = () => {
274
+ for (const release of readyWaiters.splice(0)) release();
275
+ };
272
276
  const queued = [];
273
277
  let socket = null;
274
278
  /** Invokes sent on the current socket and not yet answered, by requestId.
@@ -285,6 +289,7 @@ function createWebSocketTransport(urlOrOptions = {}) {
285
289
  * collapsing login rejection, login timeout and retry exhaustion into a
286
290
  * single string. */
287
291
  let loginFailureDetail = null;
292
+ let loginTimedOut = false;
288
293
  /** Error text for requests lost to a terminal give-up. */
289
294
  function gaveUpMessage() {
290
295
  return loginFailureDetail === null ? `${WS_DISCONNECTED_MESSAGE} (socket never opened after ${maxRetries} retries)` : `${WS_DISCONNECTED_MESSAGE} (${loginFailureDetail})`;
@@ -359,6 +364,7 @@ function createWebSocketTransport(urlOrOptions = {}) {
359
364
  if (socket !== current) return;
360
365
  machine.sendOpen();
361
366
  flushQueued();
367
+ releaseReady();
362
368
  };
363
369
  current.onmessage = (event) => {
364
370
  if (socket !== current) return;
@@ -386,6 +392,7 @@ function createWebSocketTransport(urlOrOptions = {}) {
386
392
  current.onerror = () => {};
387
393
  }
388
394
  machine.onChange((state) => {
395
+ if (state === "gaveUp" || state === "closed" || machine.isReplaced()) releaseReady();
389
396
  if (state !== "opening" && state !== "connected" && socket) dropSocket(state === "closed" ? CLOSED_MESSAGE : SOCKET_LOST_MESSAGE);
390
397
  if (state === "opening") openSocket();
391
398
  else if (state === "gaveUp") failWithServerDetail();
@@ -441,6 +448,7 @@ function createWebSocketTransport(urlOrOptions = {}) {
441
448
  async function bootstrap() {
442
449
  if (shouldLogin && !loggedIn) {
443
450
  loginFailureDetail = null;
451
+ loginTimedOut = false;
444
452
  try {
445
453
  let outcome = await postLogin();
446
454
  if (outcome === "spent") {
@@ -453,6 +461,7 @@ function createWebSocketTransport(urlOrOptions = {}) {
453
461
  loggedIn = true;
454
462
  machine.sendLoginOk();
455
463
  } else {
464
+ loginTimedOut = outcome === "timeout";
456
465
  loginFailureDetail = outcome === "timeout" ? `session login timed out after ${loginTimeoutMs}ms` : "session login rejected";
457
466
  machine.sendLoginFail();
458
467
  }
@@ -477,6 +486,7 @@ function createWebSocketTransport(urlOrOptions = {}) {
477
486
  }
478
487
  if (machine.isGaveUp()) {
479
488
  emitTransportError(header, gaveUpMessage());
489
+ if (shouldLogin && !loggedIn && loginTimedOut) machine.sendWake();
480
490
  return;
481
491
  }
482
492
  if (machine.isReplaced()) {
@@ -504,6 +514,12 @@ function createWebSocketTransport(urlOrOptions = {}) {
504
514
  dropSocket(CLOSED_MESSAGE);
505
515
  failQueuedMessages(CLOSED_MESSAGE);
506
516
  },
517
+ ready() {
518
+ if (closed || machine.isGaveUp() || machine.isReplaced() || machine.isConnected() && socket?.readyState === WebSocket.OPEN) return Promise.resolve();
519
+ return new Promise((resolve) => {
520
+ readyWaiters.push(resolve);
521
+ });
522
+ },
507
523
  subscribe(handler) {
508
524
  listeners.add(handler);
509
525
  return () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ekrooh/bare",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "type": "module",
5
5
  "description": "One soul, many platforms — the boring bootstrap for cross-platform apps on the Bare runtime: wire protocol, plugin kernel, RPC messenger, transports, and native host bridges.",
6
6
  "license": "Apache-2.0",
@@ -48,8 +48,6 @@
48
48
  "dev:bare": "node scripts/dev-bare.mjs",
49
49
  "dev:mock": "VITE_TRANSPORT_MODE=mock vp -C examples/web dev",
50
50
  "predev:mock": "npm run build:pkg",
51
- "dev:ws": "vp -C examples/web dev",
52
- "predev:ws": "npm run build:pkg",
53
51
  "dev:e2e": "vp -C examples/web dev --host 127.0.0.1 --port 4173 --strictPort",
54
52
  "predev:e2e": "npm run build:pkg",
55
53
  "build": "npm run build:android-assets",
@@ -63,7 +61,6 @@
63
61
  "build:desktop": "node scripts/build-desktop-app.mjs",
64
62
  "smoke:desktop": "node scripts/smoke-desktop.mjs",
65
63
  "test:ios": "node scripts/test-ios.mjs",
66
- "build:bare": "npm run build:core",
67
64
  "build:bare:app": "esbuild core/main.core.ts --bundle --packages=external --platform=node --format=esm --outfile=core/main.core.gen.js",
68
65
  "build:harness": "esbuild core/harness.core.ts --bundle --packages=external --platform=node --format=esm --outfile=core/harness.core.gen.js",
69
66
  "harness:e2e": "npm run build:harness && npm run build:web && node scripts/harness-e2e.mjs",