Files
Shade/packages/shade-files/src/rpc/channel.ts
Sterister 70e319fef8
Some checks failed
Test / test (push) Has been cancelled
Docker build and publish / docker (push) Has been cancelled
Publish / publish (push) Has been cancelled
release(v4.0.1): strict-TS publishability fixes
4.0.0 shipped TypeScript source as published main/types, but several
files only compiled inside the monorepo. Consumer projects (Dispatch,
etc.) running their own strict tsc against our published source hit:

- @shade/key-transparency: 4 noUnusedLocals violations
  (IndexAbsenceProof, IndexInclusionProof, IndexProofWire, nodeHash)
- @shade/sdk: KT verifier callbacks returned Promise<unknown> instead
  of Promise<STHWire> / Promise<{ proof: string[] }>
- @shade/sdk: thumbnail.ts globalThis cast collided with consumer's
  lib.dom-supplied createImageBitmap signature
- @shade/files: cycle with @shade/sdk produced "this is not assignable
  to type 'Shade'" because hoisted node_modules layouts duplicated the
  Shade class. Broken by replacing `import type { Shade }` with a
  local structural ShadeBridge interface.
- @shade/storage-encrypted: KeyUsage (lib.dom) used under
  lib: ["ES2022"]
- @shade/transport-bridge: ReadableStreamDefaultReader<any> ↔
  <Uint8Array> mismatch
- @shade/keychain / @shade/dashboard / @shade/storage-encrypted
  tsconfig rootDir / include hygiene

Tooling: scripts/typecheck-all.ts runs `bunx tsc --noEmit` against
every workspace package's tsconfig and fails on any error. Wired into
publish:dry / publish:all and publish-shade.sh as a hard gate so this
class of bug cannot recur.

All 24 packages bumped to 4.0.1 in lockstep.

Migration: <ShadeFilesProvider> now requires an explicit `files` prop
(pass `shade.files`). Wire format unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 19:36:47 +02:00

113 lines
4.1 KiB
TypeScript

import type { ShadeBridge } from '../integration/shade-bridge.js';
import {
encodeEnvelope,
looksLikeFileEnvelope,
tryParseEnvelope,
type ClassifiedEnvelope,
} from '../protocol/envelope-codec.js';
import type { RpcEnvelope } from '../schemas/envelope.js';
/**
* Routing hooks called by the channel when it receives different envelope
* classes. M-Files-1 ships the skeleton; M-Files-2 wires up real handlers
* (server-side dispatcher, client-side response routing).
*/
export interface RpcChannelHooks {
onRequest?: (from: string, env: ClassifiedEnvelope & { kind: 'request' }) => Promise<void>;
onResponse?: (from: string, env: ClassifiedEnvelope & { kind: 'response' }) => void;
onError?: (from: string, env: ClassifiedEnvelope & { kind: 'error' }) => void;
onCancel?: (from: string, env: ClassifiedEnvelope & { kind: 'cancel' }) => void;
}
/**
* `ShadeFileRpcChannel` rides on top of `Shade.send`/`Shade.onMessage`
* and routes `shade.fs.*` JSON envelopes to registered hooks.
*
* Counterpart to `ShadeControlChannel` from `@shade/sdk` — but with
* request-response semantics instead of fire-and-forget.
*
* One channel per `Shade` instance; the SDK's `files` getter memoizes it.
* Both server and client roles share the same channel: the same Shade can
* both serve files and consume them from peers.
*/
export class ShadeFileRpcChannel {
private hooks: RpcChannelHooks = {};
private readonly unsubscribe: () => void;
private destroyed = false;
constructor(private readonly shade: ShadeBridge) {
this.unsubscribe = shade.onMessage(async (from, plaintext) => {
if (!looksLikeFileEnvelope(plaintext)) return;
const classified = tryParseEnvelope(plaintext);
if (classified === null) return;
await this.dispatch(from, classified);
});
}
/**
* Merge hooks into the current set. Returns the previous values for the
* keys being set so callers can restore them on cleanup. Other hook
* slots are left unchanged — the same channel can simultaneously serve
* (`onRequest`+`onCancel`) and consume (`onResponse`+`onError`).
*/
setHooks(hooks: RpcChannelHooks): RpcChannelHooks {
if (this.destroyed) throw new Error('ShadeFileRpcChannel: destroyed');
const prev: RpcChannelHooks = {};
const keys = ['onRequest', 'onResponse', 'onError', 'onCancel'] as const;
for (const key of keys) {
if (key in hooks) {
prev[key] = this.hooks[key] as never;
this.hooks[key] = hooks[key] as never;
}
}
return prev;
}
/**
* Send an envelope to a peer. Encrypts via `Shade.send` (Double Ratchet)
* then delivers the ratchet envelope to the peer's `transferRoute()`
* control endpoint via the SDK's configured envelope transport.
*/
async send(peerAddress: string, envelope: RpcEnvelope): Promise<void> {
if (this.destroyed) throw new Error('ShadeFileRpcChannel: destroyed');
const plaintext = encodeEnvelope(envelope);
const ratchetEnvelope = await this.shade.send(peerAddress, plaintext);
if (this.shade.deliverControlEnvelope === undefined) {
throw new Error(
'ShadeFileRpcChannel: shade.deliverControlEnvelope is required — call shade.configureTransfers({ resolveBaseUrl }) before using the files namespace.',
);
}
await this.shade.deliverControlEnvelope(peerAddress, ratchetEnvelope);
}
destroy(): void {
if (this.destroyed) return;
this.destroyed = true;
this.unsubscribe();
this.hooks = {};
}
private async dispatch(from: string, classified: ClassifiedEnvelope): Promise<void> {
try {
switch (classified.kind) {
case 'request':
if (this.hooks.onRequest !== undefined) {
await this.hooks.onRequest(from, classified);
}
return;
case 'response':
this.hooks.onResponse?.(from, classified);
return;
case 'error':
this.hooks.onError?.(from, classified);
return;
case 'cancel':
this.hooks.onCancel?.(from, classified);
return;
}
} catch (err) {
console.error('[ShadeFileRpcChannel] dispatch error:', err);
}
}
}