@marktiderman/genesis-chat 0.4.0 → 0.6.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/src/native/tus.ts CHANGED
@@ -15,6 +15,10 @@
15
15
  *
16
16
  * The path is `<conversation>/<uploader>/<uuid>.<ext>`, as `send_message`
17
17
  * expects; the upload finishes before the send (the outbox orders that).
18
+ *
19
+ * What moves the bytes is a port (`transport`): this file's own TUS client by
20
+ * default, or any `TusTransport` an app passes. chat's paths, file checks and
21
+ * errors stay here either way.
18
22
  */
19
23
  import { CHAT_BUCKET, ChatError } from "../core/client";
20
24
  import { fileExtension, isAllowedExtension, randomId } from "../core/media";
@@ -46,6 +50,49 @@ export interface TusUploadOptions {
46
50
  /** A uuid for each file's name. Default core's `randomId` (crypto.randomUUID where there is one, else getRandomValues). */
47
51
  newId?: () => string;
48
52
  bucket?: string;
53
+ /**
54
+ * What sends the bytes. Default: Supabase Storage's TUS endpoint, built in (with `fetch`,
55
+ * `chunkBytes` and `retries` above). An app opts into another by passing it here.
56
+ */
57
+ transport?: TusTransport;
58
+ }
59
+
60
+ /**
61
+ * Where one file's upload stands: its path and, once the TUS upload is made,
62
+ * where it lives. A transport keeps it current, so a retry of the same file
63
+ * resumes rather than starting again.
64
+ */
65
+ export interface TusUploadRecord {
66
+ path: string;
67
+ location?: string | undefined;
68
+ done?: boolean | undefined;
69
+ }
70
+
71
+ /** What a transport reads a file's bytes from: exactly `from` to `to`. */
72
+ export interface TusUploadSource {
73
+ size: number;
74
+ read(from: number, to: number): Promise<ArrayBuffer>;
75
+ }
76
+
77
+ /** What a transport is told about the file it sends. */
78
+ export interface TusSendInfo {
79
+ bucket: string;
80
+ contentType: string;
81
+ cacheControl: string;
82
+ /** The person's headers (`authorization`, and `apikey` when given). Rejects when they're signed out. */
83
+ headers: () => Promise<Record<string, string>>;
84
+ }
85
+
86
+ /**
87
+ * The upload port: what moves a file's bytes to `record.path` in `info.bucket`.
88
+ * It resolves to the path the object ended at; `renamePath()` gives a fresh
89
+ * one (ask it at most once) when the path is taken by a send that never
90
+ * finished. A rejection whose `failure` is `"forbidden"` or `"invalid"`, or a
91
+ * `ChatError` that isn't transient, is a refusal; anything else is worth
92
+ * trying again.
93
+ */
94
+ export interface TusTransport {
95
+ send(record: TusUploadRecord, source: TusUploadSource, info: TusSendInfo, renamePath: () => string): Promise<string>;
49
96
  }
50
97
 
51
98
  /** An open file, read a chunk at a time. */
@@ -69,11 +116,7 @@ const exact = (bytes: ArrayBuffer | Uint8Array): ArrayBuffer =>
69
116
 
70
117
  const inMemory = (buffer: ArrayBuffer): Source => ({ size: buffer.byteLength, read: async (from, to) => buffer.slice(from, to), close: () => undefined });
71
118
 
72
- interface UploadRecord {
73
- path: string;
74
- location?: string;
75
- done?: boolean;
76
- }
119
+ type UploadRecord = TusUploadRecord;
77
120
 
78
121
  /** Base64 of a UTF-8 string, for TUS's Upload-Metadata (no `btoa`, which isn't on every Hermes build). */
79
122
  export function base64Utf8(text: string): string {
@@ -101,17 +144,36 @@ export function createTusUpload(options: TusUploadOptions): (conversationId: str
101
144
  // share an object, so deleting one never breaks the other.
102
145
  const byFile = new WeakMap<LocalFile, UploadRecord>();
103
146
 
104
- async function headers(extra: Record<string, string> = {}) {
147
+ async function auth(): Promise<Record<string, string>> {
105
148
  const token = await options.getAccessToken();
106
149
  if (!token) throw new ChatError("Sign in to send files", "42501", "upload");
107
150
  return {
108
151
  authorization: `Bearer ${token}`,
109
152
  ...(options.apikey ? { apikey: options.apikey } : {}),
110
- "tus-resumable": "1.0.0",
111
- ...extra,
112
153
  };
113
154
  }
114
155
 
156
+ async function headers(extra: Record<string, string> = {}) {
157
+ return { ...(await auth()), "tus-resumable": "1.0.0", ...extra };
158
+ }
159
+
160
+ const renamePath = (rec: UploadRecord) => `${rec.path.slice(0, rec.path.lastIndexOf("/") + 1)}${newId()}.${rec.path.slice(rec.path.lastIndexOf(".") + 1)}`;
161
+
162
+ /** Sends through the app's own transport, with chat's errors whatever it throws. */
163
+ async function sendThrough(transport: TusTransport, file: LocalFile, rec: UploadRecord, source: Source): Promise<string> {
164
+ try {
165
+ const path = await transport.send(rec, source, { bucket, contentType: file.contentType, cacheControl: "3600", headers: auth }, () => renamePath(rec));
166
+ rec.path = path;
167
+ rec.done = true;
168
+ return path;
169
+ } catch (e) {
170
+ if (e instanceof ChatError) throw e;
171
+ const failure = typeof e === "object" && e !== null ? (e as { failure?: unknown }).failure : undefined;
172
+ // A refusal keeps its kind; anything else (the network) is transient, so the outbox retries it.
173
+ throw new ChatError(e instanceof Error ? e.message : String(e), failure === "forbidden" ? "42501" : failure === "invalid" ? "22023" : undefined, "upload");
174
+ }
175
+ }
176
+
115
177
  async function sourceOf(file: LocalFile): Promise<Source> {
116
178
  const data = file.data;
117
179
  if (typeof data === "string") {
@@ -195,7 +257,7 @@ export function createTusUpload(options: TusUploadOptions): (conversationId: str
195
257
 
196
258
  const source = await sourceOf(file);
197
259
  try {
198
- return await send(file, record, source);
260
+ return await (options.transport ? sendThrough(options.transport, file, record, source) : send(file, record, source));
199
261
  } finally {
200
262
  source.close();
201
263
  }
@@ -246,7 +308,7 @@ export function createTusUpload(options: TusUploadOptions): (conversationId: str
246
308
  if (created === "conflict") {
247
309
  if (fresh) throw new ChatError("The upload is out of step", undefined, "upload");
248
310
  fresh = true;
249
- rec.path = `${rec.path.slice(0, rec.path.lastIndexOf("/") + 1)}${newId()}.${rec.path.slice(rec.path.lastIndexOf(".") + 1)}`;
311
+ rec.path = renamePath(rec);
250
312
  continue;
251
313
  }
252
314
  rec.location = created;