llm-large-files 0.8.1 → 0.9.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.
Files changed (204) hide show
  1. package/CHANGELOG.md +631 -0
  2. package/README.md +9 -10
  3. package/dist/access.d.ts +86 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/access.js +131 -0
  6. package/dist/access.js.map +1 -0
  7. package/dist/ask.d.ts +45 -1
  8. package/dist/ask.d.ts.map +1 -1
  9. package/dist/ask.js +181 -20
  10. package/dist/ask.js.map +1 -1
  11. package/dist/cache.d.ts +12 -3
  12. package/dist/cache.d.ts.map +1 -1
  13. package/dist/cache.js +18 -5
  14. package/dist/cache.js.map +1 -1
  15. package/dist/encoding.js +5 -3
  16. package/dist/encoding.js.map +1 -1
  17. package/dist/error-info.d.ts +57 -0
  18. package/dist/error-info.d.ts.map +1 -0
  19. package/dist/error-info.js +217 -0
  20. package/dist/error-info.js.map +1 -0
  21. package/dist/errors.d.ts +72 -8
  22. package/dist/errors.d.ts.map +1 -1
  23. package/dist/errors.js +102 -15
  24. package/dist/errors.js.map +1 -1
  25. package/dist/events.d.ts +35 -9
  26. package/dist/events.d.ts.map +1 -1
  27. package/dist/events.js +42 -11
  28. package/dist/events.js.map +1 -1
  29. package/dist/evidence.d.ts +4 -2
  30. package/dist/evidence.d.ts.map +1 -1
  31. package/dist/evidence.js +14 -3
  32. package/dist/evidence.js.map +1 -1
  33. package/dist/extract.d.ts +32 -8
  34. package/dist/extract.d.ts.map +1 -1
  35. package/dist/extract.js +46 -35
  36. package/dist/extract.js.map +1 -1
  37. package/dist/gemini/adapter.d.ts +19 -3
  38. package/dist/gemini/adapter.d.ts.map +1 -1
  39. package/dist/gemini/adapter.js +84 -12
  40. package/dist/gemini/adapter.js.map +1 -1
  41. package/dist/gemini/chat.d.ts +18 -6
  42. package/dist/gemini/chat.d.ts.map +1 -1
  43. package/dist/gemini/chat.js +2 -0
  44. package/dist/gemini/chat.js.map +1 -1
  45. package/dist/gemini/index.d.ts +1 -1
  46. package/dist/gemini/index.d.ts.map +1 -1
  47. package/dist/index.d.ts +9 -6
  48. package/dist/index.d.ts.map +1 -1
  49. package/dist/index.js +4 -3
  50. package/dist/index.js.map +1 -1
  51. package/dist/ingest.d.ts +70 -0
  52. package/dist/ingest.d.ts.map +1 -0
  53. package/dist/ingest.js +868 -0
  54. package/dist/ingest.js.map +1 -0
  55. package/dist/library.d.ts +176 -34
  56. package/dist/library.d.ts.map +1 -1
  57. package/dist/library.js +332 -512
  58. package/dist/library.js.map +1 -1
  59. package/dist/limiter.d.ts +2 -2
  60. package/dist/limiter.js +2 -2
  61. package/dist/map-reduce.js +3 -3
  62. package/dist/map-reduce.js.map +1 -1
  63. package/dist/model.d.ts +43 -2
  64. package/dist/model.d.ts.map +1 -1
  65. package/dist/model.js +63 -3
  66. package/dist/model.js.map +1 -1
  67. package/dist/node/handlers.d.ts +234 -7
  68. package/dist/node/handlers.d.ts.map +1 -1
  69. package/dist/node/handlers.js +482 -121
  70. package/dist/node/handlers.js.map +1 -1
  71. package/dist/node/index.d.ts +3 -2
  72. package/dist/node/index.d.ts.map +1 -1
  73. package/dist/node/index.js +2 -1
  74. package/dist/node/index.js.map +1 -1
  75. package/dist/node/ingest-child.d.ts +7 -1
  76. package/dist/node/ingest-child.d.ts.map +1 -1
  77. package/dist/node/ingest-child.js +18 -3
  78. package/dist/node/ingest-child.js.map +1 -1
  79. package/dist/node/isolated.d.ts +3 -1
  80. package/dist/node/isolated.d.ts.map +1 -1
  81. package/dist/node/isolated.js +11 -4
  82. package/dist/node/isolated.js.map +1 -1
  83. package/dist/node/originals.d.ts +19 -0
  84. package/dist/node/originals.d.ts.map +1 -0
  85. package/dist/node/originals.js +82 -0
  86. package/dist/node/originals.js.map +1 -0
  87. package/dist/node/spool.d.ts +102 -0
  88. package/dist/node/spool.d.ts.map +1 -0
  89. package/dist/node/spool.js +365 -0
  90. package/dist/node/spool.js.map +1 -0
  91. package/dist/node/sse.d.ts +4 -3
  92. package/dist/node/sse.d.ts.map +1 -1
  93. package/dist/node/sse.js +7 -6
  94. package/dist/node/sse.js.map +1 -1
  95. package/dist/pdf-layout.d.ts.map +1 -1
  96. package/dist/pdf-layout.js +71 -12
  97. package/dist/pdf-layout.js.map +1 -1
  98. package/dist/ranged.d.ts +22 -11
  99. package/dist/ranged.d.ts.map +1 -1
  100. package/dist/ranged.js +50 -12
  101. package/dist/ranged.js.map +1 -1
  102. package/dist/retry.d.ts +3 -1
  103. package/dist/retry.d.ts.map +1 -1
  104. package/dist/retry.js +6 -2
  105. package/dist/retry.js.map +1 -1
  106. package/dist/scope.d.ts +25 -0
  107. package/dist/scope.d.ts.map +1 -0
  108. package/dist/scope.js +60 -0
  109. package/dist/scope.js.map +1 -0
  110. package/dist/source.d.ts +60 -0
  111. package/dist/source.d.ts.map +1 -0
  112. package/dist/source.js +170 -0
  113. package/dist/source.js.map +1 -0
  114. package/dist/stores.d.ts +120 -31
  115. package/dist/stores.d.ts.map +1 -1
  116. package/dist/stores.js +582 -139
  117. package/dist/stores.js.map +1 -1
  118. package/dist/testing/fake-fetch.d.ts +31 -0
  119. package/dist/testing/fake-fetch.d.ts.map +1 -0
  120. package/dist/testing/fake-fetch.js +66 -0
  121. package/dist/testing/fake-fetch.js.map +1 -0
  122. package/dist/testing/fake-model.d.ts +38 -0
  123. package/dist/testing/fake-model.d.ts.map +1 -0
  124. package/dist/testing/fake-model.js +62 -0
  125. package/dist/testing/fake-model.js.map +1 -0
  126. package/dist/testing/index.d.ts +7 -0
  127. package/dist/testing/index.d.ts.map +1 -0
  128. package/dist/testing/index.js +9 -0
  129. package/dist/testing/index.js.map +1 -0
  130. package/dist/testing/store-checks.d.ts +72 -0
  131. package/dist/testing/store-checks.d.ts.map +1 -0
  132. package/dist/testing/store-checks.js +619 -0
  133. package/dist/testing/store-checks.js.map +1 -0
  134. package/dist/tools.d.ts +25 -0
  135. package/dist/tools.d.ts.map +1 -1
  136. package/dist/tools.js +135 -13
  137. package/dist/tools.js.map +1 -1
  138. package/dist/types.d.ts +116 -13
  139. package/dist/types.d.ts.map +1 -1
  140. package/docs/README.md +17 -8
  141. package/docs/getting-started.md +18 -13
  142. package/docs/guides/anthropic.md +12 -8
  143. package/docs/guides/conversations.md +112 -47
  144. package/docs/guides/costs-and-limits.md +16 -7
  145. package/docs/guides/deployment.md +309 -87
  146. package/docs/guides/errors-and-reliability.md +161 -23
  147. package/docs/guides/own-adapter-and-loop.md +27 -10
  148. package/docs/guides/pdfs.md +123 -29
  149. package/docs/guides/storage.md +634 -143
  150. package/docs/guides/testing.md +78 -129
  151. package/docs/guides/vertex-and-gemini.md +10 -7
  152. package/docs/guides/web-app.md +322 -77
  153. package/docs/how-it-works.md +35 -8
  154. package/docs/measurements.md +63 -8
  155. package/docs/publishing.md +112 -36
  156. package/docs/reference/ask.md +154 -13
  157. package/docs/reference/errors-and-retries.md +166 -14
  158. package/docs/reference/events.md +53 -20
  159. package/docs/reference/gemini.md +70 -21
  160. package/docs/reference/library.md +709 -165
  161. package/docs/reference/node.md +633 -104
  162. package/docs/reference/testing.md +311 -0
  163. package/docs/reference/tools.md +15 -5
  164. package/docs/security.md +316 -70
  165. package/docs/troubleshooting.md +165 -58
  166. package/docs/upgrading-0.9.md +890 -0
  167. package/package.json +12 -3
  168. package/src/access.ts +144 -0
  169. package/src/ask.ts +230 -19
  170. package/src/cache.ts +20 -5
  171. package/src/encoding.ts +6 -4
  172. package/src/error-info.ts +255 -0
  173. package/src/errors.ts +129 -15
  174. package/src/events.ts +86 -21
  175. package/src/evidence.ts +14 -3
  176. package/src/extract.ts +50 -33
  177. package/src/gemini/adapter.ts +97 -11
  178. package/src/gemini/chat.ts +20 -6
  179. package/src/gemini/index.ts +1 -1
  180. package/src/index.ts +9 -6
  181. package/src/ingest.ts +927 -0
  182. package/src/library.ts +482 -523
  183. package/src/limiter.ts +2 -2
  184. package/src/map-reduce.ts +3 -3
  185. package/src/model.ts +69 -5
  186. package/src/node/handlers.ts +691 -117
  187. package/src/node/index.ts +13 -2
  188. package/src/node/ingest-child.ts +23 -5
  189. package/src/node/isolated.ts +11 -4
  190. package/src/node/originals.ts +78 -0
  191. package/src/node/spool.ts +365 -0
  192. package/src/node/sse.ts +7 -6
  193. package/src/pdf-layout.ts +69 -11
  194. package/src/ranged.ts +42 -14
  195. package/src/retry.ts +6 -2
  196. package/src/scope.ts +63 -0
  197. package/src/source.ts +178 -0
  198. package/src/stores.ts +635 -140
  199. package/src/testing/fake-fetch.ts +80 -0
  200. package/src/testing/fake-model.ts +78 -0
  201. package/src/testing/index.ts +11 -0
  202. package/src/testing/store-checks.ts +660 -0
  203. package/src/tools.ts +150 -14
  204. package/src/types.ts +106 -13
@@ -1,15 +1,18 @@
1
- import { IngestError, isStoreWriteFailure } from "../errors.js";
1
+ import { tmpdir } from "node:os";
2
+ import path from "node:path";
3
+ import { errorInfoOf, STORE_RETRY_AFTER_MS, UNREADABLE_MESSAGE } from "../error-info.js";
4
+ import { DocumentScopeError, DocumentStoreError, IngestError, isErrorCode } from "../errors.js";
2
5
  import { eventStream, newRunId } from "../events.js";
3
- import { checkOwner, toDocumentSummary } from "../library.js";
6
+ import { checkOwner, cleanFileName, toDocumentSummary } from "../library.js";
7
+ import { DocumentsNotFoundError, errorKindOf, ModelRequestError } from "../model.js";
4
8
  import { formatBytes } from "../plan.js";
9
+ import { checkScope } from "../scope.js";
10
+ import { BodyFile, checkRefFolders, HttpError, parsedBody, readBody, Room, spoolFileIn, writeBody } from "./spool.js";
5
11
  import { writeSseEvents } from "./sse.js";
6
- class HttpError extends Error {
7
- status;
8
- constructor(status, message) {
9
- super(message);
10
- this.status = status;
11
- }
12
- }
12
+ /** A whole HTTP status of an error, from 400 to 599. */
13
+ const isErrorStatus = (value) => typeof value === "number" && Number.isInteger(value) && value >= 400 && value <= 599;
14
+ /** A wait in milliseconds: a finite number of 0 or more. */
15
+ const isWait = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
13
16
  /** The HTTP status an error carries: this module's, or one `getOwner` throws (`http-errors` style). */
14
17
  function statusOf(error) {
15
18
  if (error instanceof HttpError)
@@ -18,49 +21,102 @@ function statusOf(error) {
18
21
  return undefined;
19
22
  const { status, statusCode } = error;
20
23
  const value = typeof status === "number" ? status : statusCode;
21
- return typeof value === "number" && Number.isInteger(value) && value >= 400 && value <= 599 ? value : undefined;
24
+ return isErrorStatus(value) ? value : undefined;
22
25
  }
23
26
  /**
24
27
  * The code of a Node system error (a file or network call that failed, as `ENOSPC`). Its message
25
- * names server paths or hosts, so only the code is passed on.
28
+ * names server paths or hosts, so only the code is passed on, and only when it reads as one: a
29
+ * driver may put a host in `code`.
26
30
  */
27
31
  function systemErrorCode(error) {
28
32
  const { code, syscall } = (error ?? {});
29
- return typeof code === "string" && typeof syscall === "string" ? code : undefined;
33
+ return isErrorCode(code) && typeof syscall === "string" ? code : undefined;
30
34
  }
35
+ /** What the handlers answer a scope that is gone (`DocumentScopeError` "scope_missing"): the chat was deleted. */
36
+ const CHAT_GONE = "This chat no longer exists.";
31
37
  /**
32
- * The answer to a failed request. An error with a status keeps its status and message. Anything
33
- * else is the server's trouble: a 500 that says what failed and, for a system error, its code.
38
+ * An error as the handlers answer it, `failed` saying what failed ("Upload failed"). See
39
+ * `uploadAnswerOf`. It never throws: an error whose fields throw when read is a 500.
34
40
  */
35
- function answerOf(error, failed, tooLarge) {
36
- const status = statusOf(error);
37
- if (status !== undefined) {
38
- return { status, message: status === 413 ? tooLarge : error instanceof Error && error.message ? error.message : `${failed}.` };
41
+ function answerFor(error, failed) {
42
+ const plain = { status: 500, error: `${failed}.` };
43
+ try {
44
+ if (error instanceof HttpError)
45
+ return { status: error.status, error: error.message || plain.error };
46
+ if (IngestError.is(error)) {
47
+ const status = isErrorStatus(error.status) ? error.status : 422;
48
+ return {
49
+ status,
50
+ // An unreadable file has the words of a parser, or of an extractor of your own, which may
51
+ // name a host: not words for a user (as for errorInfoOf).
52
+ error: error.code === "unreadable" ? UNREADABLE_MESSAGE : typeof error.message === "string" && error.message ? error.message : plain.error,
53
+ code: error.code,
54
+ ...(status === 503 && isWait(error.retryAfterMs) ? { retryAfterMs: error.retryAfterMs } : {}),
55
+ };
56
+ }
57
+ // Its message names what failed and a code, never a path or a host.
58
+ if (DocumentStoreError.is(error))
59
+ return { status: 503, error: errorInfoOf(error).message, retryAfterMs: STORE_RETRY_AFTER_MS };
60
+ // A scope the server gave wrong, or did not give, is its own bug: not the client's to fix.
61
+ if (DocumentScopeError.is(error))
62
+ return error.code === "scope_missing" ? { status: 404, error: CHAT_GONE } : plain;
63
+ // A model's error (an ingest or a hook of your own that asks one): its status is the provider's,
64
+ // and its message the provider's words, which may name a project or a key.
65
+ if (ModelRequestError.is(error) || errorKindOf(error) !== undefined) {
66
+ const info = errorInfoOf(error);
67
+ if (info.category === "model")
68
+ return { status: info.status, error: info.message, ...(info.status === 429 || info.status === 503 ? retryOf(info.retryAfterMs) : {}) };
69
+ }
70
+ const status = statusOf(error);
71
+ if (status !== undefined) {
72
+ const message = error.message;
73
+ return { status, error: typeof message === "string" && message ? message : plain.error, ...(status === 503 ? retryOf(error.retryAfterMs) : {}) };
74
+ }
75
+ const code = systemErrorCode(error);
76
+ return code ? { status: 500, error: `${failed} (${code}).` } : plain;
39
77
  }
40
- const code = systemErrorCode(error);
41
- return { status: 500, message: code ? `${failed} (${code}).` : `${failed}.` };
42
- }
43
- /** Answers a failed request with JSON (see `answerOf`). A refusal that says when to try again (a busy reader) sets `Retry-After`. */
44
- function fail(response, error, failed, tooLarge, unread) {
45
- const { status, message } = answerOf(error, failed, tooLarge);
46
- const retryAfterMs = error?.retryAfterMs;
47
- if (status === 503 && typeof retryAfterMs === "number" && Number.isFinite(retryAfterMs) && !response.headersSent) {
48
- response.setHeader("Retry-After", String(Math.max(1, Math.ceil(retryAfterMs / 1_000))));
78
+ catch {
79
+ return plain;
49
80
  }
50
- send(response, status, { error: message }, unread);
51
81
  }
82
+ const retryOf = (value) => (isWait(value) ? { retryAfterMs: value } : {});
52
83
  /**
53
- * An error of `ingest` as the upload answers it. A file that cannot be read is the client's 422,
54
- * with the reason. An error with a status keeps it, and a system error is the server's 500 with its
55
- * code. A store that failed in another way is the server's 500 too, without its message: that is
56
- * the store's own, and may name a database host. So is a value that is not an Error, whoever threw it.
84
+ * How the upload handler answers an error, for a route of your own that ingests files and should
85
+ * answer as it does:
86
+ * - an `IngestError` (a file that could not be read): its status (422; 413, 409, or 503 for "busy"
87
+ * with its `retryAfterMs`), its message and its `code`. Only an `IngestError` is a 422. An
88
+ * "unreadable" file is told in fixed words, as `errorInfoOf` tells it: its own message is a
89
+ * parser's, or that of an extractor of your own;
90
+ * - a `DocumentStoreError`: 503, its message (which names no path or host), and 5 s to wait;
91
+ * - a `DocumentScopeError` "scope_missing": 404 "This chat no longer exists."; the other codes
92
+ * are the server's mistake: 500 "Upload failed.";
93
+ * - a model's error (`ModelRequestError`): the status and words of `errorInfoOf`, never the
94
+ * provider's own;
95
+ * - any other error with a `status` (or `statusCode`) from 400 to 599: that status and its message;
96
+ * - a Node system error (a `code` and a `syscall`): 500 "Upload failed (ENOSPC).", or "Upload
97
+ * failed." when its code does not read as one (capitals, digits and "_"), as a host does;
98
+ * - anything else: 500 "Upload failed.", without its message, which may name a host.
99
+ *
100
+ * It reads the errors of every copy of the package, and never throws. New in 0.9.0.
57
101
  */
58
- function ingestFailure(error) {
59
- if (statusOf(error) !== undefined || systemErrorCode(error) !== undefined)
60
- return error;
61
- if (isStoreWriteFailure(error) || !(error instanceof Error))
62
- return error;
63
- return new HttpError(422, error.message);
102
+ export function uploadAnswerOf(error) {
103
+ return answerFor(error, "Upload failed");
104
+ }
105
+ /**
106
+ * Answers a failed request with JSON (see `answerFor`). A 413 of the handler or of `ingest` gets the
107
+ * size message of the upload. An answer that says when to try again (a busy reader, a store, a
108
+ * model's rate limit) sets `Retry-After`.
109
+ */
110
+ function fail(response, error, failed, tooLarge, unread) {
111
+ const answer = answerFor(error, failed);
112
+ if (answer.retryAfterMs !== undefined && !response.headersSent) {
113
+ response.setHeader("Retry-After", String(Math.max(1, Math.ceil(answer.retryAfterMs / 1_000))));
114
+ }
115
+ send(response, answer.status, { error: messageOf(answer, error, tooLarge) }, unread);
116
+ }
117
+ /** The message of an answer: a 413 of the handler itself, or of `ingest`, says the upload limit. */
118
+ function messageOf(answer, error, tooLarge) {
119
+ return answer.status === 413 && (error instanceof HttpError || IngestError.is(error)) ? tooLarge : answer.error;
64
120
  }
65
121
  /**
66
122
  * Whether the client asked for the upload's progress as Server-Sent Events: its `Accept` header
@@ -77,13 +133,53 @@ function wantsEvents(request) {
77
133
  return q === undefined || Number(q[1]) > 0;
78
134
  });
79
135
  }
136
+ /**
137
+ * An error as `ingest.error` carries it: the message, status and code of the JSON answer, and which
138
+ * of the library's errors it is, so that `errorInfoOf` reads it in the browser as on the server.
139
+ */
140
+ function eventErrorFor(error, tooLarge) {
141
+ const answer = answerFor(error, "Upload failed");
142
+ // A file that could not be read also says why, for a page that tells it in its own words.
143
+ return { message: messageOf(answer, error, tooLarge), status: answer.status, ...identityOf(error), ...(answer.code !== undefined ? { code: answer.code } : {}) };
144
+ }
145
+ /**
146
+ * The name of a store's failure, of documents that are gone, or of a scope that cannot be used
147
+ * (with its code, which tells a deleted chat apart), and the kind of a model's error (an ingest or
148
+ * a hook of yours that asks one), as `answerFor` answers it, for `EventError`. Nothing for other
149
+ * errors: a refused file is told by its `code`.
150
+ */
151
+ function identityOf(error) {
152
+ try {
153
+ if (DocumentStoreError.is(error))
154
+ return { name: "DocumentStoreError" };
155
+ if (DocumentsNotFoundError.is(error))
156
+ return { name: "DocumentsNotFoundError" };
157
+ if (DocumentScopeError.is(error))
158
+ return { name: "DocumentScopeError", ...(typeof error.code === "string" ? { code: error.code } : {}) };
159
+ // A model's EventError always has its kind, as in the events of a question.
160
+ if (ModelRequestError.is(error) || errorKindOf(error) !== undefined) {
161
+ const info = errorInfoOf(error);
162
+ if (info.category === "model")
163
+ return { kind: info.code };
164
+ }
165
+ }
166
+ catch {
167
+ // A proxy whose traps throw: told plainly.
168
+ }
169
+ return {};
170
+ }
80
171
  /**
81
172
  * Ingests the upload and answers with its events as Server-Sent Events. The last one is always
82
- * `ingest.finish` or `ingest.error`, even with a `LargeFiles` of your own whose `ingest` sends no events.
173
+ * `ingest.finish` or `ingest.error`, even with a `LargeFiles` of your own whose `ingest` sends no
174
+ * events. `uploaded` runs `onUploaded` once, before `ingest.finish` is sent; or after the stream, for
175
+ * a document stored once the client went away. `start` starts the ingest (see `upload`); `release`
176
+ * is called once the ingest ended, before `onUploaded`.
83
177
  */
84
- async function streamIngest(files, input, response, tooLarge) {
178
+ async function streamIngest(start, signal, response, tooLarge, uploaded, release) {
85
179
  const runId = newRunId("ing");
86
- const stream = eventStream((onEvent, signal) => files.ingest({ ...input, runId, onEvent, signal }), { signal: input.signal });
180
+ const stream = eventStream((onEvent, stop) => start({ runId, onEvent, signal: stop }), { signal });
181
+ // The ingest ended: its room is given back, while `onUploaded` may still run.
182
+ stream.result.then(release, release);
87
183
  // The error as a JSON answer would give it: the event's own may hold a store's message.
88
184
  const answer = async (fallback) => {
89
185
  try {
@@ -91,11 +187,25 @@ async function streamIngest(files, input, response, tooLarge) {
91
187
  return { message: fallback.message, ...(fallback.status !== undefined ? { status: fallback.status } : {}) };
92
188
  }
93
189
  catch (error) {
94
- const failure = ingestFailure(error);
95
- // A file that could not be read also says why, for a page that tells it in its own words.
96
- return { ...answerOf(failure, "Upload failed", tooLarge), ...(failure instanceof IngestError ? { code: failure.code } : {}) };
190
+ return eventErrorFor(error, tooLarge);
97
191
  }
98
192
  };
193
+ /** The last event of a stored document: `ingest.finish` once `onUploaded` is done, or `ingest.error` when it failed. */
194
+ const finished = async (base, last) => {
195
+ let meta;
196
+ try {
197
+ meta = await stream.result;
198
+ }
199
+ catch {
200
+ // An ingest of your own that sent ingest.finish, then failed.
201
+ return { ...base, type: "ingest.error", error: await answer({ message: "Upload failed." }) };
202
+ }
203
+ const hooked = await uploaded(meta);
204
+ if ("failure" in hooked)
205
+ return { ...base, type: "ingest.error", error: eventErrorFor(hooked.failure, tooLarge) };
206
+ const event = last ?? { ...base, type: "ingest.finish", document: toDocumentSummary(meta) };
207
+ return hooked.answer ? { ...event, app: hooked.answer } : event;
208
+ };
99
209
  async function* events() {
100
210
  let seq = 0;
101
211
  for await (const event of stream) {
@@ -104,22 +214,25 @@ async function streamIngest(files, input, response, tooLarge) {
104
214
  yield { ...event, error: await answer(event.error) };
105
215
  return;
106
216
  }
107
- yield event;
108
- if (event.type === "ingest.finish")
217
+ if (event.type === "ingest.finish") {
218
+ yield await finished({ seq: event.seq, runId: event.runId, time: event.time }, event);
109
219
  return;
220
+ }
221
+ yield event;
110
222
  }
111
223
  // The ingest ended without a last event: a `LargeFiles` of your own whose ingest sends none.
112
- const base = { seq: seq + 1, runId, time: Date.now() };
113
- try {
114
- yield { ...base, type: "ingest.finish", document: toDocumentSummary(await stream.result) };
115
- }
116
- catch {
117
- yield { ...base, type: "ingest.error", error: await answer({ message: "Upload failed." }) };
118
- }
224
+ yield await finished({ seq: seq + 1, runId, time: Date.now() }, undefined);
119
225
  }
120
226
  // Each message is the event itself, as for a question: `ingest.finish` holds the summary a 201
121
227
  // answer would (`document`), `ingest.error` the message and status a JSON answer would (`error`).
122
228
  await writeSseEvents(response, events());
229
+ // A client that went away ends the stream at once, while the ingest stops (a store write may still
230
+ // be under way): the upload is held until then, as on the JSON path. A document stored all the
231
+ // same (the ingest had ended, or an ingest of your own did not stop) still goes to `onUploaded`
232
+ // (with `clientGone`), once.
233
+ const meta = await stream.result.catch(() => undefined);
234
+ if (meta !== undefined)
235
+ await uploaded(meta);
123
236
  }
124
237
  /**
125
238
  * Answers with `value` as JSON. With `unread`, a request whose body was not read to its end (an
@@ -137,9 +250,18 @@ function send(response, status, value, unread) {
137
250
  response.write(body);
138
251
  drain(unread, response);
139
252
  }
140
- function header(request, name) {
253
+ /** A header's value as it came (the first, when it came more than once), or "". */
254
+ function rawHeader(request, name) {
141
255
  const raw = request.headers[name];
142
256
  const value = Array.isArray(raw) ? raw[0] : raw;
257
+ return value ?? "";
258
+ }
259
+ /**
260
+ * A header the page URI-encodes (`X-File-Name`, `X-File-Type`), decoded: a value that does not
261
+ * decode is used as it is.
262
+ */
263
+ function header(request, name) {
264
+ const value = rawHeader(request, name);
143
265
  if (!value)
144
266
  return "";
145
267
  try {
@@ -149,33 +271,92 @@ function header(request, name) {
149
271
  return value;
150
272
  }
151
273
  }
152
- /** Reads the raw body, or uses one a framework already parsed into a Buffer (e.g. express.raw()). */
153
- async function readBody(request, limit) {
154
- const parsed = request.body;
155
- if (parsed instanceof Uint8Array) {
156
- if (parsed.byteLength > limit)
157
- throw new HttpError(413, "");
158
- return parsed;
274
+ /** `uploadIdleTimeoutMs`, checked: a number of 0 or more (0 and Infinity for no limit). */
275
+ function idleLimit(value) {
276
+ if (value === undefined)
277
+ return 30_000;
278
+ if (typeof value !== "number" || Number.isNaN(value) || value < 0) {
279
+ throw new RangeError(`uploadIdleTimeoutMs must be a number of 0 or more, and is ${typeof value === "number" ? value : typeof value}. Leave it out for the default.`);
280
+ }
281
+ return value;
282
+ }
283
+ /** `maxPendingUploadBytes` or `maxSpooledUploadBytes` (`name`), checked: a number above 0 (Infinity for no limit). */
284
+ function roomLimit(name, value, fallback) {
285
+ if (value === undefined)
286
+ return fallback;
287
+ if (typeof value !== "number" || Number.isNaN(value) || value <= 0) {
288
+ throw new RangeError(`${name} must be a number above 0, and is ${typeof value === "number" ? value : typeof value}. Leave it out for the default.`);
289
+ }
290
+ return value;
291
+ }
292
+ /** `uploadSpool`, checked: undefined for no spool. */
293
+ function spoolOf(value) {
294
+ if (value === undefined || value === false)
295
+ return undefined;
296
+ const given = value === true ? {} : value;
297
+ if (typeof given !== "object" || given === null)
298
+ throw new TypeError("uploadSpool must be true, false, or { directory?, minBytes? }.");
299
+ const { directory, minBytes } = given;
300
+ if (directory !== undefined && (typeof directory !== "string" || directory.length === 0 || directory.includes("\0"))) {
301
+ throw new TypeError("uploadSpool.directory must be the path of a folder: a string that is not empty.");
159
302
  }
160
- if (parsed !== undefined && typeof parsed === "object" && parsed !== null && Object.keys(parsed).length) {
161
- throw new HttpError(400, "The upload body was already parsed by another middleware. Mount the upload route before body parsers, or send Content-Type: application/octet-stream.");
303
+ if (minBytes !== undefined && (typeof minBytes !== "number" || Number.isNaN(minBytes) || minBytes < 0)) {
304
+ throw new RangeError(`uploadSpool.minBytes must be a number of 0 or more, and is ${typeof minBytes === "number" ? minBytes : typeof minBytes}. Leave it out for the default.`);
162
305
  }
163
- const declared = Number(request.headers["content-length"]);
164
- if (Number.isFinite(declared) && declared > limit)
165
- throw new HttpError(413, "");
166
- const chunks = [];
167
- let size = 0;
168
- // Leaving the loop early must not destroy the request: the rest of the body is drained after
169
- // the answer (see `drain`), which a destroyed request would not do.
170
- for await (const chunk of request.iterator({ destroyOnReturn: false })) {
171
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
172
- size += buffer.byteLength;
173
- if (size > limit)
174
- throw new HttpError(413, "");
175
- chunks.push(buffer);
306
+ return { directory: path.resolve(directory ?? tmpdir()), minBytes: minBytes ?? 1024 * 1024 };
307
+ }
308
+ /** `uploadFileMode`, checked: a file mode from 0 to 0o777. */
309
+ function fileModeOf(value) {
310
+ if (value === undefined)
311
+ return 0o600;
312
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > 0o777) {
313
+ throw new TypeError("uploadFileMode must be a file mode from 0 to 0o777, such as 0o640.");
314
+ }
315
+ return value;
316
+ }
317
+ const PREPARED_SHAPE = "prepareUpload must return nothing, or { id?, path?, original? }: id a string, path an absolute path, original { ref } with a path.";
318
+ /**
319
+ * What `prepareUpload` returned, checked (a copy). Null fields are left out, as a database gives
320
+ * them. Anything else is a TypeError, the server's mistake: a 500 "Upload failed.". The rules of
321
+ * `id` and `original.ref` are the library's, checked by `ingest`.
322
+ */
323
+ function preparedOf(value) {
324
+ if (value === undefined || value === null)
325
+ return {};
326
+ if (typeof value !== "object")
327
+ throw new TypeError(PREPARED_SHAPE);
328
+ const { id, path: at, original } = value;
329
+ const prepared = {};
330
+ if (id !== undefined && id !== null) {
331
+ if (typeof id !== "string")
332
+ throw new TypeError(PREPARED_SHAPE);
333
+ prepared.id = id;
334
+ }
335
+ if (at !== undefined && at !== null) {
336
+ if (typeof at !== "string" || at.includes("\0") || !path.isAbsolute(at))
337
+ throw new TypeError(PREPARED_SHAPE);
338
+ prepared.path = at;
339
+ }
340
+ if (original !== undefined && original !== null) {
341
+ const ref = typeof original === "object" ? original.ref : undefined;
342
+ // A ref names the file the body is saved to: without a path, it would name a file the handler never wrote.
343
+ if (typeof ref !== "string" || prepared.path === undefined)
344
+ throw new TypeError(PREPARED_SHAPE);
345
+ prepared.original = { ref };
176
346
  }
177
- const body = Buffer.concat(chunks);
178
- return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
347
+ return prepared;
348
+ }
349
+ /**
350
+ * The bytes an upload will hold: a body a framework already read, its declared `Content-Length`,
351
+ * or the upload limit when it declares none. Never more than the limit: a larger one is refused
352
+ * when it is read (413).
353
+ */
354
+ function expectedSize(request, limit) {
355
+ const parsed = request.body;
356
+ if (parsed instanceof Uint8Array)
357
+ return Math.min(parsed.byteLength, limit);
358
+ const declared = Number(request.headers["content-length"]);
359
+ return Number.isFinite(declared) && declared >= 0 ? Math.min(declared, limit) : limit;
179
360
  }
180
361
  /**
181
362
  * The most bytes of an upload's body that are read and dropped after it was answered before the
@@ -222,7 +403,99 @@ function drain(request, response) {
222
403
  */
223
404
  export function createDocumentHandlers(files, options = {}) {
224
405
  const tooLarge = `The file is larger than the ${formatBytes(files.maxUploadBytes)} upload limit.`;
225
- const owner = async (request) => options.getOwner?.(request);
406
+ // The upload limit bounds each body, and the room for all of them: a LargeFiles of your own
407
+ // without it (from JavaScript) had neither.
408
+ if (typeof files.maxUploadBytes !== "number" || !(files.maxUploadBytes > 0)) {
409
+ throw new TypeError(`createDocumentHandlers needs files.maxUploadBytes, a number above 0, and it is ${String(files.maxUploadBytes)}. A LargeFiles of your own must keep the one of the library it wraps.`);
410
+ }
411
+ for (const name of ["getScope", "prepareUpload", "onUploaded", "onRemoved"]) {
412
+ if (options[name] !== undefined && typeof options[name] !== "function")
413
+ throw new TypeError(`${name} must be a function, and is ${typeof options[name]}.`);
414
+ }
415
+ // A library that requires an owner or a scope on every call cannot be served without them: every
416
+ // request would fail, after its body was read.
417
+ const requireOwner = files.access?.requireOwner === true;
418
+ const requireScope = files.access?.requireScope === true;
419
+ if (requireOwner && typeof options.getOwner !== "function") {
420
+ throw new TypeError("createDocumentHandlers needs getOwner: the library requires an owner on every call (requireOwner).");
421
+ }
422
+ if (requireScope && typeof options.getScope !== "function") {
423
+ throw new TypeError("createDocumentHandlers needs getScope: the library requires a scope on every call (requireScope).");
424
+ }
425
+ const idleMs = idleLimit(options.uploadIdleTimeoutMs);
426
+ /** The bodies held in memory, from the reading of each to the end of its ingest (`maxPendingUploadBytes`). */
427
+ const memoryRoom = new Room(roomLimit("maxPendingUploadBytes", options.maxPendingUploadBytes, 2 * files.maxUploadBytes));
428
+ const spool = spoolOf(options.uploadSpool);
429
+ /** The files of the spool, from the writing of each to its removal (`maxSpooledUploadBytes`). */
430
+ const spoolRoom = new Room(roomLimit("maxSpooledUploadBytes", options.maxSpooledUploadBytes, 10 * files.maxUploadBytes));
431
+ const fileMode = fileModeOf(options.uploadFileMode);
432
+ /**
433
+ * Whether the body of an upload goes to a file of the spool: with `uploadSpool`, one over
434
+ * `minBytes`, or that does not say its size. Not a body a framework already read into memory.
435
+ */
436
+ function spools(declared, parsed) {
437
+ if (spool === undefined || parsed !== undefined)
438
+ return false;
439
+ return !(Number.isFinite(declared) && declared >= 0 && declared <= spool.minBytes);
440
+ }
441
+ /**
442
+ * Who is asking: the owner and the scope of the request, checked, before its body is read. Under
443
+ * `requireOwner`, a request without an owner is answered 401. An owner the library refuses (on
444
+ * the upload, or on every route under `requireOwner`), a scope that is not valid, or none under
445
+ * `requireScope`, is the server's mistake: a 500 that says which, and nothing else. `failed` says
446
+ * what failed ("Upload failed").
447
+ */
448
+ async function callerOf(request, failed, checkOwnerShape) {
449
+ const owner = await options.getOwner?.(request);
450
+ // No owner, or null (`req.user?.id ?? null` from JavaScript), is a request that is not signed in.
451
+ if (requireOwner && (owner === undefined || owner === null))
452
+ throw new HttpError(401, "Sign in first.");
453
+ // An owner that `ingest` would refuse ("", or an object such as `req.user` from JavaScript) is
454
+ // the server's mistake, answered with a 500 before the body is read. Its message says which, so
455
+ // that the operator knows where to look; it says nothing else. (Without `requireOwner`, `get`
456
+ // and `remove` pass it on, as before, so that documents of 0.5.0 with the owner "" stay
457
+ // readable. Under it, the library refuses such an owner on every call: so do they, in the same
458
+ // words as the upload.)
459
+ if (checkOwnerShape || requireOwner) {
460
+ try {
461
+ checkOwner(owner);
462
+ }
463
+ catch {
464
+ const empty = typeof owner === "string" || owner === null;
465
+ throw new HttpError(500, empty ? `${failed} (empty owner).` : `${failed} (owner is not a string).`);
466
+ }
467
+ }
468
+ const given = options.getScope ? await options.getScope(request) : undefined;
469
+ let scope;
470
+ try {
471
+ // Null is no scope, as for the library.
472
+ scope = checkScope(given ?? undefined);
473
+ }
474
+ catch {
475
+ throw new HttpError(500, `${failed} (invalid scope).`);
476
+ }
477
+ if (requireScope && scope === undefined)
478
+ throw new HttpError(500, `${failed} (no scope).`);
479
+ return { ...(owner !== undefined ? { owner } : {}), ...(scope !== undefined ? { scope } : {}) };
480
+ }
481
+ /**
482
+ * Runs `onUploaded` for a stored document. When it throws, or its `answer` is not a plain object
483
+ * that JSON can hold, the document is deleted (a failure to delete is not told: the upload has
484
+ * failed either way) and the error is what the upload answers.
485
+ */
486
+ async function uploaded(meta, request, caller, clientGone, saved) {
487
+ if (!options.onUploaded)
488
+ return {};
489
+ try {
490
+ const returned = await options.onUploaded(meta, { request, ...caller, clientGone, ...(saved !== undefined ? { path: saved } : {}) });
491
+ return hookAnswerOf(returned);
492
+ }
493
+ catch (error) {
494
+ // A delete of your own that throws at once is told no more than one that rejects.
495
+ await Promise.resolve().then(() => files.delete(meta.id, caller)).catch(() => undefined);
496
+ return { failure: error };
497
+ }
498
+ }
226
499
  return {
227
500
  async upload(request, response) {
228
501
  try {
@@ -230,51 +503,119 @@ export function createDocumentHandlers(files, options = {}) {
230
503
  const name = header(request, "x-file-name").trim() || url.searchParams.get("name")?.trim() || "";
231
504
  if (!name)
232
505
  throw new HttpError(400, "Name the file with an X-File-Name header or a ?name= query parameter.");
233
- // Who is asking comes first: a refused upload is not read into memory. An owner that
234
- // `ingest` would refuse ("", or an object such as `req.user` from JavaScript) is the server's
235
- // mistake, answered with a 500 before the body is read. Its message says which, so that the
236
- // operator knows where to look; it says nothing else.
237
- const currentOwner = await owner(request);
238
- try {
239
- checkOwner(currentOwner);
240
- }
241
- catch {
242
- const empty = typeof currentOwner === "string" || currentOwner === null;
243
- throw new HttpError(500, empty ? "Upload failed (empty owner)." : "Upload failed (owner is not a string).");
506
+ // Who is asking comes first: a refused upload is not read into memory.
507
+ const caller = await callerOf(request, "Upload failed", true);
508
+ // Too large is said first, before any wait for room.
509
+ const declared = Number(request.headers["content-length"]);
510
+ const parsed = parsedBody(request);
511
+ if ((Number.isFinite(declared) && declared > files.maxUploadBytes) || (parsed !== undefined && parsed.byteLength > files.maxUploadBytes)) {
512
+ throw new HttpError(413, "");
244
513
  }
245
- const bytes = await readBody(request, files.maxUploadBytes);
246
- const contentType = header(request, "content-type");
247
- const mimeType = header(request, "x-file-type") || (contentType && !contentType.startsWith("application/octet-stream") ? contentType : "");
248
- // A client that goes away before the answer stops the reading of its file: nobody would
249
- // get the document, and the server has other work.
250
- const gone = new AbortController();
251
- const onClose = () => {
252
- if (!response.writableFinished)
253
- gone.abort(new Error("The upload was cancelled: the client closed the connection."));
254
- };
255
- response.once("close", onClose);
256
- const input = {
257
- name,
258
- bytes,
259
- ...(mimeType ? { mimeType } : {}),
260
- ...(currentOwner !== undefined ? { owner: currentOwner } : {}),
261
- signal: gone.signal,
262
- };
263
- let meta;
514
+ const prepared = options.prepareUpload ? preparedOf(await options.prepareUpload(request, { name: cleanFileName(name), ...caller })) : {};
515
+ // A file `fileOriginals` would not read back by its ref is refused before anything is written.
516
+ if (prepared.path !== undefined && prepared.original !== undefined)
517
+ await checkRefFolders(prepared.path, prepared.original.ref, idleMs);
518
+ // Where the body is while it is ingested: in the application's file (`prepareUpload`), in a
519
+ // file of the spool, or in memory. Room is taken for it before it is read, so that a refused
520
+ // upload is not read: in the spool, or in memory. The application's file takes none: it is
521
+ // on the application's disk, and stays.
522
+ const spooled = prepared.path === undefined && spools(declared, parsed);
523
+ const held = prepared.path !== undefined ? undefined : (spooled ? spoolRoom : memoryRoom).take(expectedSize(request, files.maxUploadBytes));
524
+ /** Gives the upload's room back, once: when its ingest ended, so that an `onUploaded` that waits on a database of yours does not hold it, or when the upload failed. */
525
+ const release = () => held?.release();
526
+ let file;
264
527
  try {
265
- if (wantsEvents(request))
266
- return await streamIngest(files, input, response, tooLarge);
267
- meta = await files.ingest(input);
268
- }
269
- catch (error) {
270
- throw ingestFailure(error);
528
+ let body;
529
+ if (prepared.path !== undefined || spooled) {
530
+ const at = prepared.path ?? spoolFileIn(spool.directory);
531
+ const size = await writeBody(request, at, { limit: files.maxUploadBytes, idleMs, mode: prepared.path !== undefined ? fileMode : 0o600 });
532
+ file = new BodyFile(at, prepared.path !== undefined, idleMs);
533
+ held?.resize(size);
534
+ }
535
+ else {
536
+ body = await readBody(request, files.maxUploadBytes, idleMs);
537
+ // Counted at its size once read (an upload without a Content-Length was counted at the limit).
538
+ held?.resize(body.byteLength);
539
+ }
540
+ // Content-Type is a header of HTTP, not one the page encodes: it is taken as it came (S11).
541
+ // `ingest` cleans what it keeps of either.
542
+ const contentType = rawHeader(request, "content-type");
543
+ const mimeType = header(request, "x-file-type") || (contentType && !contentType.startsWith("application/octet-stream") ? contentType : "");
544
+ // A client that goes away before the answer stops the reading of its file: nobody would
545
+ // get the document, and the server has other work.
546
+ const gone = new AbortController();
547
+ const onClose = () => {
548
+ if (!response.writableFinished)
549
+ gone.abort(new Error("The upload was cancelled: the client closed the connection."));
550
+ };
551
+ response.once("close", onClose);
552
+ // One that left already is told no more: while the last piece of its body was written,
553
+ // or its file closed (where a network volume writes what it held back), or before a body
554
+ // a framework read was taken.
555
+ if (response.destroyed || request.socket?.destroyed)
556
+ onClose();
557
+ const chosen = { ...(prepared.id !== undefined ? { id: prepared.id } : {}), ...(prepared.original !== undefined ? { original: prepared.original } : {}) };
558
+ /**
559
+ * Starts the upload's ingest, once. A body in memory is then the ingest's alone: it is
560
+ * freed when the ingest ends, while `onUploaded` may still run. The input is built in
561
+ * this function, whose frame ends at once: a value in the frame of `upload`, an async
562
+ * function, is kept until it returns, the hook's wait included. A body in a file is
563
+ * ingested from its path: the file of the spool is removed when the ingest ends, and the
564
+ * application's file when the ingest fails.
565
+ */
566
+ const start = (more) => {
567
+ const input = { name, ...(mimeType ? { mimeType } : {}), ...chosen, ...caller, signal: gone.signal, ...more };
568
+ if (file)
569
+ return file.settle(files.ingest({ ...input, source: { path: file.path } }));
570
+ const bytes = body;
571
+ body = undefined;
572
+ return files.ingest({ ...input, bytes });
573
+ };
574
+ // The path is told only for the application's own file: the spool's is gone by then.
575
+ const saved = file?.kept ? file.path : undefined;
576
+ const hook = async (meta) => {
577
+ const hooked = await uploaded(meta, request, caller, gone.signal.aborted, saved);
578
+ // The document is deleted: the file saved for it goes too.
579
+ if ("failure" in hooked)
580
+ await file?.remove();
581
+ return hooked;
582
+ };
583
+ try {
584
+ if (wantsEvents(request)) {
585
+ // `onUploaded` runs once, for the event before ingest.finish or after the stream.
586
+ let hooking;
587
+ return await streamIngest(start, gone.signal, response, tooLarge, (meta) => (hooking ??= hook(meta)), release);
588
+ }
589
+ const meta = await start();
590
+ release();
591
+ const hooked = await hook(meta);
592
+ if ("failure" in hooked)
593
+ throw hooked.failure;
594
+ // The summary's own fields win over the hook's.
595
+ send(response, 201, { ...hooked.answer, ...toDocumentSummary(meta) });
596
+ }
597
+ finally {
598
+ response.off("close", onClose);
599
+ }
271
600
  }
272
601
  finally {
273
- response.off("close", onClose);
602
+ release();
603
+ // Whatever happened: the spool's file is gone, and so is the application's unless its document is stored.
604
+ await file?.end();
274
605
  }
275
- send(response, 201, toDocumentSummary(meta));
276
606
  }
277
607
  catch (error) {
608
+ // A body that stopped arriving is not drained: the answer ends, and so does the connection.
609
+ if (error instanceof HttpError && error.close) {
610
+ if (!response.headersSent)
611
+ response.setHeader("Connection", "close");
612
+ send(response, error.status, { error: error.message });
613
+ if (response.writableFinished)
614
+ request.destroy();
615
+ else
616
+ response.once("finish", () => request.destroy());
617
+ return;
618
+ }
278
619
  // Answered before the body was read to its end (too large, no name): the rest is drained.
279
620
  fail(response, error, "Upload failed", tooLarge, request);
280
621
  // An event stream that failed after its headers were sent cannot answer with a status. (An
@@ -285,8 +626,8 @@ export function createDocumentHandlers(files, options = {}) {
285
626
  },
286
627
  async get(request, response, id) {
287
628
  try {
288
- const currentOwner = await owner(request);
289
- const meta = await files.getMeta(id, currentOwner !== undefined ? { owner: currentOwner } : {});
629
+ const caller = await callerOf(request, "The file could not be looked up", false);
630
+ const meta = await files.getMeta(id, caller);
290
631
  if (meta)
291
632
  send(response, 200, toDocumentSummary(meta));
292
633
  else
@@ -298,8 +639,11 @@ export function createDocumentHandlers(files, options = {}) {
298
639
  },
299
640
  async remove(request, response, id) {
300
641
  try {
301
- const currentOwner = await owner(request);
302
- send(response, 200, { deleted: await files.delete(id, currentOwner !== undefined ? { owner: currentOwner } : {}) });
642
+ const caller = await callerOf(request, "The file could not be deleted", false);
643
+ const deleted = await files.delete(id, caller);
644
+ if (deleted && options.onRemoved)
645
+ await options.onRemoved(id, { request, ...caller });
646
+ send(response, 200, { deleted });
303
647
  }
304
648
  catch (error) {
305
649
  fail(response, error, "The file could not be deleted", tooLarge);
@@ -307,4 +651,21 @@ export function createDocumentHandlers(files, options = {}) {
307
651
  },
308
652
  };
309
653
  }
654
+ /**
655
+ * What `onUploaded` returned, as the fields to add to the answer: `{ answer }` with a plain object
656
+ * that JSON can hold (a copy of it, as JSON reads it back). Anything else without an `answer` (a
657
+ * database's own result) adds nothing. An `answer` of another kind is a TypeError.
658
+ */
659
+ function hookAnswerOf(returned) {
660
+ if (typeof returned !== "object" || returned === null)
661
+ return {};
662
+ const answer = returned.answer;
663
+ if (answer === undefined || answer === null)
664
+ return {};
665
+ const proto = typeof answer === "object" ? Object.getPrototypeOf(answer) : undefined;
666
+ if (typeof answer !== "object" || Array.isArray(answer) || (proto !== Object.prototype && proto !== null)) {
667
+ throw new TypeError("onUploaded must return nothing, or { answer } with a plain object that JSON can hold.");
668
+ }
669
+ return { answer: JSON.parse(JSON.stringify(answer)) };
670
+ }
310
671
  //# sourceMappingURL=handlers.js.map