@procedures/media 0.0.0-stage → 0.68.15
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/LICENSE +21 -0
- package/README.md +46 -2
- package/dist/base64.d.ts +17 -0
- package/dist/base64.d.ts.map +1 -0
- package/dist/base64.js +39 -0
- package/dist/base64.js.map +1 -0
- package/dist/document.d.ts +84 -0
- package/dist/document.d.ts.map +1 -0
- package/dist/document.js +212 -0
- package/dist/document.js.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/dist/module.d.ts +15 -0
- package/dist/module.d.ts.map +1 -0
- package/dist/module.js +17 -0
- package/dist/module.js.map +1 -0
- package/dist/ranges.d.ts +31 -0
- package/dist/ranges.d.ts.map +1 -0
- package/dist/ranges.js +87 -0
- package/dist/ranges.js.map +1 -0
- package/dist/transfer.d.ts +68 -0
- package/dist/transfer.d.ts.map +1 -0
- package/dist/transfer.js +145 -0
- package/dist/transfer.js.map +1 -0
- package/dist/types.d.ts +7 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +7 -0
- package/dist/types.js.map +1 -0
- package/dist/web.d.ts +13 -0
- package/dist/web.d.ts.map +1 -0
- package/dist/web.js +20 -0
- package/dist/web.js.map +1 -0
- package/package.json +76 -3
- package/src/base64.ts +42 -0
- package/src/document.ts +263 -0
- package/src/index.ts +37 -0
- package/src/media.test.ts +189 -0
- package/src/module.ts +20 -0
- package/src/ranges.test.ts +129 -0
- package/src/ranges.ts +92 -0
- package/src/transfer.ts +170 -0
- package/src/types.ts +7 -0
- package/src/web.ts +29 -0
package/src/document.ts
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Media documents: a small JSON record first, and its files after it.
|
|
3
|
+
*
|
|
4
|
+
* A media document has two parts. `$data` is the record of the app. `$media` is the table of its files: each key is the
|
|
5
|
+
* id of a file, the SHA-256 of its bytes as 64 lowercase hex characters. Each entry tells where the file is in `$data`
|
|
6
|
+
* (a JSON Pointer, RFC 6901), its media type, its size and its state. At that pointer, `$data` holds the id.
|
|
7
|
+
*
|
|
8
|
+
* The states are these:
|
|
9
|
+
*
|
|
10
|
+
* - `pending`: the store has no bytes of the file.
|
|
11
|
+
* - `partial`: the store has `received` bytes, more than 0 and fewer than `size`.
|
|
12
|
+
* - `complete`: the store has all the bytes.
|
|
13
|
+
* - `embedded`: the bytes are in the entry, as the canonical base64 text `base64`.
|
|
14
|
+
* - `linked`: the bytes are at the URL `url` (http or https).
|
|
15
|
+
*
|
|
16
|
+
* Thus a reader can show the record before its files are complete. Because the id is the hash of the bytes, an upload
|
|
17
|
+
* is idempotent, and a store can examine each file that it gets.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { ok, err, type Result } from "@mark1russell7/optional";
|
|
21
|
+
import { assertJson, formatPointer, lookup, parsePointer, type JsonValue } from "@procedures/json";
|
|
22
|
+
import { base64Size, decodeBase64 } from "./base64.js";
|
|
23
|
+
import { urlProtocol } from "./web.js";
|
|
24
|
+
|
|
25
|
+
/** The states of a file, in the order of an upload. */
|
|
26
|
+
export const MEDIA_STATES = ["pending", "partial", "complete", "embedded", "linked"] as const;
|
|
27
|
+
|
|
28
|
+
/** The state of a file. */
|
|
29
|
+
export type MediaState = (typeof MEDIA_STATES)[number];
|
|
30
|
+
|
|
31
|
+
/** The fields that each entry has. */
|
|
32
|
+
export interface MediaEntryBase {
|
|
33
|
+
/** The JSON Pointer of the file in `$data`. */
|
|
34
|
+
readonly path: string;
|
|
35
|
+
/** The media type (RFC 6838), in lowercase, for example `image/jpeg`. */
|
|
36
|
+
readonly type: string;
|
|
37
|
+
/** The number of bytes of the file. */
|
|
38
|
+
readonly size: number;
|
|
39
|
+
/** The SHA-256 of the bytes, as 64 lowercase hex characters. It is equal to the key of the entry. */
|
|
40
|
+
readonly sha256: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** An entry of the media table. The state selects the other fields. */
|
|
44
|
+
export type MediaEntry =
|
|
45
|
+
| (MediaEntryBase & { readonly state: "pending" })
|
|
46
|
+
| (MediaEntryBase & { readonly state: "partial"; readonly received: number })
|
|
47
|
+
| (MediaEntryBase & { readonly state: "complete" })
|
|
48
|
+
| (MediaEntryBase & { readonly state: "embedded"; readonly base64: string })
|
|
49
|
+
| (MediaEntryBase & { readonly state: "linked"; readonly url: string });
|
|
50
|
+
|
|
51
|
+
/** The media table: each file by its id. */
|
|
52
|
+
export type MediaTable = Readonly<Record<string, MediaEntry>>;
|
|
53
|
+
|
|
54
|
+
/** A media document: the record of the app in `$data`, and the table of its files in `$media`. */
|
|
55
|
+
export interface MediaDocument<D extends JsonValue = JsonValue> {
|
|
56
|
+
readonly $media: MediaTable;
|
|
57
|
+
readonly $data: D;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The kind of a problem in a media document. */
|
|
61
|
+
export type MediaIssueCode =
|
|
62
|
+
| "NOT_OBJECT"
|
|
63
|
+
| "MISSING_FIELD"
|
|
64
|
+
| "UNKNOWN_FIELD"
|
|
65
|
+
| "NOT_JSON"
|
|
66
|
+
| "BAD_ID"
|
|
67
|
+
| "ID_MISMATCH"
|
|
68
|
+
| "BAD_TYPE"
|
|
69
|
+
| "BAD_SIZE"
|
|
70
|
+
| "BAD_STATE"
|
|
71
|
+
| "BAD_PATH"
|
|
72
|
+
| "PATH_NOT_FOUND"
|
|
73
|
+
| "PATH_NOT_ID"
|
|
74
|
+
| "PATH_SHARED"
|
|
75
|
+
| "BAD_RECEIVED"
|
|
76
|
+
| "BAD_BASE64"
|
|
77
|
+
| "SIZE_MISMATCH"
|
|
78
|
+
| "BAD_URL";
|
|
79
|
+
|
|
80
|
+
/** A problem in a media document. `at` is the JSON Pointer of the bad value in the document. */
|
|
81
|
+
export interface MediaIssue {
|
|
82
|
+
readonly at: string;
|
|
83
|
+
readonly code: MediaIssueCode;
|
|
84
|
+
readonly message: string;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const ID = /^[0-9a-f]{64}$/;
|
|
88
|
+
|
|
89
|
+
/** This function tells if a text is a media id: 64 lowercase hex characters. */
|
|
90
|
+
export function isMediaId(text: unknown): text is string {
|
|
91
|
+
return typeof text === "string" && ID.test(text);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// RFC 6838, section 4.2: a name has 1 to 127 characters, and starts with a letter or a digit.
|
|
95
|
+
const NAME = "[a-z0-9][a-z0-9!#$&^_.+-]{0,126}";
|
|
96
|
+
const TOKEN = "[a-z0-9!#$%&'*+.^_`|~-]+";
|
|
97
|
+
const QUOTED = '"(?:[^"\\\\\\r\\n]|\\\\.)*"';
|
|
98
|
+
const MEDIA_TYPE = new RegExp(`^${NAME}/${NAME}(?:; ?${TOKEN}=(?:[A-Za-z0-9!#$%&'*+.^_\`|~-]+|${QUOTED}))*$`);
|
|
99
|
+
|
|
100
|
+
/** This function tells if a text is a media type in lowercase, with optional parameters (`text/plain; charset=utf-8`). */
|
|
101
|
+
export function isMediaType(text: unknown): text is string {
|
|
102
|
+
return typeof text === "string" && MEDIA_TYPE.test(text);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** This function tells if a text is an absolute http or https URL. */
|
|
106
|
+
export function isMediaUrl(text: unknown): text is string {
|
|
107
|
+
if (typeof text !== "string") return false;
|
|
108
|
+
try {
|
|
109
|
+
const protocol = urlProtocol(text);
|
|
110
|
+
return protocol === "https:" || protocol === "http:";
|
|
111
|
+
} catch {
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** The fields of each state, after the base fields. */
|
|
117
|
+
const STATE_FIELDS: Readonly<Record<MediaState, readonly string[]>> = {
|
|
118
|
+
pending: [],
|
|
119
|
+
partial: ["received"],
|
|
120
|
+
complete: [],
|
|
121
|
+
embedded: ["base64"],
|
|
122
|
+
linked: ["url"],
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
const BASE_FIELDS = ["path", "type", "size", "sha256", "state"] as const;
|
|
126
|
+
|
|
127
|
+
function isObject(value: unknown): value is Record<string, unknown> {
|
|
128
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function isState(value: unknown): value is MediaState {
|
|
132
|
+
return typeof value === "string" && (MEDIA_STATES as readonly string[]).includes(value);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** The text of an unknown value in a message. */
|
|
136
|
+
function shown(value: unknown): string {
|
|
137
|
+
const text = typeof value === "string" ? JSON.stringify(value) : String(value);
|
|
138
|
+
return text.length > 80 ? `${text.slice(0, 77)}...` : text;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* This function examines a value as a media document. It gives the document, or each problem that it found. A problem
|
|
143
|
+
* in one entry does not stop the examination of the other entries.
|
|
144
|
+
*/
|
|
145
|
+
export function checkMediaDocument(value: unknown): Result<MediaDocument, readonly MediaIssue[]> {
|
|
146
|
+
const issues: MediaIssue[] = [];
|
|
147
|
+
const add = (tokens: readonly (string | number)[], code: MediaIssueCode, message: string): void => {
|
|
148
|
+
issues.push({ at: formatPointer(tokens), code, message });
|
|
149
|
+
};
|
|
150
|
+
if (!isObject(value)) {
|
|
151
|
+
add([], "NOT_OBJECT", "A media document is an object with the fields $media and $data");
|
|
152
|
+
return err(issues);
|
|
153
|
+
}
|
|
154
|
+
for (const key of Object.keys(value)) {
|
|
155
|
+
if (key !== "$media" && key !== "$data") add([key], "UNKNOWN_FIELD", `A media document has only $media and $data, not ${shown(key)}`);
|
|
156
|
+
}
|
|
157
|
+
if (!(Object.hasOwn(value, "$data"))) add(["$data"], "MISSING_FIELD", "A media document needs the field $data");
|
|
158
|
+
if (!(Object.hasOwn(value, "$media"))) add(["$media"], "MISSING_FIELD", "A media document needs the field $media");
|
|
159
|
+
const data = value["$data"];
|
|
160
|
+
let dataIsJson = Object.hasOwn(value, "$data");
|
|
161
|
+
if (dataIsJson) {
|
|
162
|
+
try {
|
|
163
|
+
assertJson(data, "$data");
|
|
164
|
+
} catch (error) {
|
|
165
|
+
dataIsJson = false;
|
|
166
|
+
add(["$data"], "NOT_JSON", error instanceof Error ? error.message : String(error));
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const media = value["$media"];
|
|
170
|
+
if (Object.hasOwn(value, "$media") && !isObject(media)) add(["$media"], "NOT_OBJECT", "The field $media is an object: each file by its id");
|
|
171
|
+
if (isObject(media)) {
|
|
172
|
+
const owners = new Map<string, string>();
|
|
173
|
+
for (const [id, entry] of Object.entries(media)) {
|
|
174
|
+
checkEntry(id, entry, dataIsJson ? (data as JsonValue) : undefined, owners, add);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return issues.length === 0 ? ok(value as unknown as MediaDocument) : err(issues);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
type Add = (tokens: readonly (string | number)[], code: MediaIssueCode, message: string) => void;
|
|
181
|
+
|
|
182
|
+
function checkEntry(id: string, entry: unknown, data: JsonValue | undefined, owners: Map<string, string>, add: Add): void {
|
|
183
|
+
const at = ["$media", id];
|
|
184
|
+
if (!isMediaId(id)) add(at, "BAD_ID", `The id ${shown(id)} is not a SHA-256 in 64 lowercase hex characters`);
|
|
185
|
+
if (!isObject(entry)) {
|
|
186
|
+
add(at, "NOT_OBJECT", "An entry of $media is an object with path, type, size, sha256 and state");
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
for (const field of BASE_FIELDS) {
|
|
190
|
+
if (!Object.hasOwn(entry, field)) add([...at, field], "MISSING_FIELD", `An entry of $media needs the field ${field}`);
|
|
191
|
+
}
|
|
192
|
+
const { path, type, size, sha256, state } = entry;
|
|
193
|
+
if (Object.hasOwn(entry, "sha256") && sha256 !== id) add([...at, "sha256"], "ID_MISMATCH", "The field sha256 of an entry is equal to its id");
|
|
194
|
+
if (Object.hasOwn(entry, "type") && !isMediaType(type)) add([...at, "type"], "BAD_TYPE", `The type ${shown(type)} is not a media type in lowercase, for example image/jpeg`);
|
|
195
|
+
const sizeIsGood = Number.isSafeInteger(size) && (size as number) >= 0;
|
|
196
|
+
if (Object.hasOwn(entry, "size") && !sizeIsGood) add([...at, "size"], "BAD_SIZE", `The size ${shown(size)} is not a safe integer of 0 or more`);
|
|
197
|
+
if (Object.hasOwn(entry, "state") && !isState(state)) add([...at, "state"], "BAD_STATE", `The state ${shown(state)} is not one of ${MEDIA_STATES.join(", ")}`);
|
|
198
|
+
if (Object.hasOwn(entry, "path")) checkPath(id, path, data, owners, [...at, "path"], add);
|
|
199
|
+
if (!isState(state)) return;
|
|
200
|
+
const allowed = new Set<string>([...BASE_FIELDS, ...STATE_FIELDS[state]]);
|
|
201
|
+
for (const field of Object.keys(entry)) {
|
|
202
|
+
if (!allowed.has(field)) add([...at, field], "UNKNOWN_FIELD", `An entry in the state ${state} has no field ${shown(field)}`);
|
|
203
|
+
}
|
|
204
|
+
for (const field of STATE_FIELDS[state]) {
|
|
205
|
+
if (!Object.hasOwn(entry, field)) add([...at, field], "MISSING_FIELD", `An entry in the state ${state} needs the field ${field}`);
|
|
206
|
+
}
|
|
207
|
+
if (state === "partial" && Object.hasOwn(entry, "received")) {
|
|
208
|
+
const received = entry["received"];
|
|
209
|
+
const good = Number.isSafeInteger(received) && (received as number) > 0 && (!sizeIsGood || (received as number) < (size as number));
|
|
210
|
+
if (!good) add([...at, "received"], "BAD_RECEIVED", `The count received ${shown(received)} of a partial file is more than 0 and less than its size`);
|
|
211
|
+
}
|
|
212
|
+
if (state === "embedded" && Object.hasOwn(entry, "base64")) {
|
|
213
|
+
const text = entry["base64"];
|
|
214
|
+
if (typeof text !== "string" || decodeBase64(text) === undefined) {
|
|
215
|
+
add([...at, "base64"], "BAD_BASE64", "The field base64 is the canonical base64 text of the bytes (RFC 4648, with padding)");
|
|
216
|
+
} else if (sizeIsGood && base64Size(text) !== size) {
|
|
217
|
+
add([...at, "base64"], "SIZE_MISMATCH", `The base64 text has ${base64Size(text)} bytes, but the size is ${String(size)}`);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
if (state === "linked" && Object.hasOwn(entry, "url") && !isMediaUrl(entry["url"])) {
|
|
221
|
+
add([...at, "url"], "BAD_URL", `The url ${shown(entry["url"])} is not an absolute http or https URL`);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function checkPath(id: string, path: unknown, data: JsonValue | undefined, owners: Map<string, string>, at: readonly string[], add: Add): void {
|
|
226
|
+
if (typeof path !== "string" || path.startsWith("#")) {
|
|
227
|
+
add(at, "BAD_PATH", `The path ${shown(path)} is not a JSON Pointer: it is "" or starts with "/"`);
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
let tokens: string[];
|
|
231
|
+
try {
|
|
232
|
+
tokens = parsePointer(path, "path");
|
|
233
|
+
} catch (error) {
|
|
234
|
+
add(at, "BAD_PATH", error instanceof Error ? error.message : String(error));
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
const owner = owners.get(path);
|
|
238
|
+
if (owner !== undefined) add(at, "PATH_SHARED", `The path ${shown(path)} is also the path of the file ${owner}`);
|
|
239
|
+
else owners.set(path, id);
|
|
240
|
+
if (data === undefined) return;
|
|
241
|
+
const found = lookup(data, tokens);
|
|
242
|
+
if (!found.found) add(at, "PATH_NOT_FOUND", `The path ${shown(path)} is not in $data`);
|
|
243
|
+
else if (found.value !== id) add(at, "PATH_NOT_ID", `At the path ${shown(path)}, $data holds ${shown(found.value)}, not the id of the file`);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** This function gives the document, or throws a `MediaDocumentError` with each problem. */
|
|
247
|
+
export function assertMediaDocument(value: unknown): MediaDocument {
|
|
248
|
+
const result = checkMediaDocument(value);
|
|
249
|
+
if (result.tag === "err") throw new MediaDocumentError(result.error);
|
|
250
|
+
return result.value;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** The error of a value that is not a media document. It has the list of the problems. */
|
|
254
|
+
export class MediaDocumentError extends Error {
|
|
255
|
+
readonly issues: readonly MediaIssue[];
|
|
256
|
+
constructor(issues: readonly MediaIssue[]) {
|
|
257
|
+
const first = issues[0];
|
|
258
|
+
const more = issues.length > 1 ? ` (and ${issues.length - 1} more)` : "";
|
|
259
|
+
super(first === undefined ? "The value is not a media document" : `${first.at || "/"}: ${first.message}${more}`);
|
|
260
|
+
this.name = "MediaDocumentError";
|
|
261
|
+
this.issues = issues;
|
|
262
|
+
}
|
|
263
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// The root registers nothing: import "<package>/register", or give the module to createRegistry()
|
|
2
|
+
export * from "./module.js";
|
|
3
|
+
export * from "./types.js";
|
|
4
|
+
|
|
5
|
+
// The pure core of media documents. It has no Node.js import, so it runs in a browser too.
|
|
6
|
+
export {
|
|
7
|
+
MEDIA_STATES,
|
|
8
|
+
assertMediaDocument,
|
|
9
|
+
checkMediaDocument,
|
|
10
|
+
isMediaId,
|
|
11
|
+
isMediaType,
|
|
12
|
+
isMediaUrl,
|
|
13
|
+
MediaDocumentError,
|
|
14
|
+
type MediaDocument,
|
|
15
|
+
type MediaEntry,
|
|
16
|
+
type MediaEntryBase,
|
|
17
|
+
type MediaIssue,
|
|
18
|
+
type MediaIssueCode,
|
|
19
|
+
type MediaState,
|
|
20
|
+
type MediaTable,
|
|
21
|
+
} from "./document.js";
|
|
22
|
+
export {
|
|
23
|
+
DEFAULT_MAX_EMBEDDED_BYTES,
|
|
24
|
+
addMedia,
|
|
25
|
+
embedMedia,
|
|
26
|
+
isStored,
|
|
27
|
+
linkMedia,
|
|
28
|
+
mediaIds,
|
|
29
|
+
missingIds,
|
|
30
|
+
stripMedia,
|
|
31
|
+
withReceived,
|
|
32
|
+
type EmbedOptions,
|
|
33
|
+
type NewMedia,
|
|
34
|
+
type StrippedMedia,
|
|
35
|
+
} from "./transfer.js";
|
|
36
|
+
export { addRange, isByteRange, missingRanges, normalizeRanges, planChunks, rangeBytes, type ByteRange } from "./ranges.js";
|
|
37
|
+
export { base64Size, decodeBase64, encodeBase64 } from "./base64.js";
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import fc from "fast-check";
|
|
3
|
+
import {
|
|
4
|
+
addMedia,
|
|
5
|
+
checkMediaDocument,
|
|
6
|
+
encodeBase64,
|
|
7
|
+
embedMedia,
|
|
8
|
+
linkMedia,
|
|
9
|
+
mediaIds,
|
|
10
|
+
missingIds,
|
|
11
|
+
stripMedia,
|
|
12
|
+
withReceived,
|
|
13
|
+
type MediaDocument,
|
|
14
|
+
type MediaIssueCode,
|
|
15
|
+
} from "./index.js";
|
|
16
|
+
|
|
17
|
+
const RUNS = { numRuns: 200 };
|
|
18
|
+
|
|
19
|
+
const hex = (bytes: Uint8Array): string => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
20
|
+
|
|
21
|
+
/** A file with random bytes and a random id. The core has no hash, so the id need not be the hash of the bytes. */
|
|
22
|
+
const fileArb = fc.record({
|
|
23
|
+
id: fc.uint8Array({ minLength: 32, maxLength: 32 }).map(hex),
|
|
24
|
+
bytes: fc.uint8Array({ maxLength: 96 }),
|
|
25
|
+
type: fc.constantFrom("image/jpeg", "image/png", "application/pdf", "text/plain; charset=utf-8", "application/vnd.example+json"),
|
|
26
|
+
// A name with "~" and "/" makes the escapes of the pointer (RFC 6901) part of the test.
|
|
27
|
+
name: fc.option(fc.string({ unit: fc.constantFrom("a", "b", "~", "/", "0", "1", " "), minLength: 1, maxLength: 6 }), { nil: undefined }),
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
type FileValue = { readonly id: string; readonly bytes: Uint8Array; readonly type: string; readonly name: string | undefined };
|
|
31
|
+
|
|
32
|
+
const escape = (token: string): string => token.replace(/~/g, "~0").replace(/\//g, "~1");
|
|
33
|
+
|
|
34
|
+
/** A list of files with distinct ids and distinct names. */
|
|
35
|
+
const filesArb = fc.uniqueArray(fileArb, { maxLength: 8, selector: (file) => file.id }).map((files) => {
|
|
36
|
+
const names = new Set<string>();
|
|
37
|
+
return files.map((file) => {
|
|
38
|
+
if (file.name === undefined || names.has(file.name)) return { ...file, name: undefined };
|
|
39
|
+
names.add(file.name);
|
|
40
|
+
return file;
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
function build(files: readonly FileValue[]): MediaDocument {
|
|
45
|
+
let document: MediaDocument = { $media: {}, $data: { title: "a record", list: [], byName: {} } };
|
|
46
|
+
for (const file of files) {
|
|
47
|
+
const path = file.name === undefined ? "/list/-" : `/byName/${escape(file.name)}`;
|
|
48
|
+
document = addMedia(document, { path, type: file.type, size: file.bytes.length, sha256: file.id });
|
|
49
|
+
}
|
|
50
|
+
return document;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function codes(value: unknown): MediaIssueCode[] {
|
|
54
|
+
const result = checkMediaDocument(value);
|
|
55
|
+
return result.tag === "ok" ? [] : result.error.map((issue) => issue.code);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
describe("media documents", () => {
|
|
59
|
+
it("a built document passes the check, also after a JSON round trip", () => {
|
|
60
|
+
fc.assert(
|
|
61
|
+
fc.property(filesArb, (files) => {
|
|
62
|
+
const document = build(files);
|
|
63
|
+
expect(codes(document)).toEqual([]);
|
|
64
|
+
const copy: unknown = JSON.parse(JSON.stringify(document));
|
|
65
|
+
expect(codes(copy)).toEqual([]);
|
|
66
|
+
expect(mediaIds(document)).toEqual(files.map((file) => file.id).sort());
|
|
67
|
+
}),
|
|
68
|
+
RUNS,
|
|
69
|
+
);
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
it("strip after embed gives the pending document and the bytes of each small file", () => {
|
|
73
|
+
fc.assert(
|
|
74
|
+
fc.property(filesArb, fc.integer({ min: 0, max: 100 }), (files, maxBytes) => {
|
|
75
|
+
const document = build(files);
|
|
76
|
+
const bytes = new Map(files.map((file) => [file.id, file.bytes]));
|
|
77
|
+
const embedded = embedMedia(document, bytes, { maxBytes });
|
|
78
|
+
expect(codes(embedded)).toEqual([]);
|
|
79
|
+
const small = files.filter((file) => file.bytes.length <= maxBytes);
|
|
80
|
+
for (const file of files) expect(embedded.$media[file.id]!.state).toBe(file.bytes.length <= maxBytes ? "embedded" : "pending");
|
|
81
|
+
const stripped = stripMedia(embedded);
|
|
82
|
+
expect(stripped.document).toEqual(document);
|
|
83
|
+
expect([...stripped.files.keys()].sort()).toEqual(small.map((file) => file.id).sort());
|
|
84
|
+
for (const file of small) expect(Array.from(stripped.files.get(file.id)!)).toEqual(Array.from(file.bytes));
|
|
85
|
+
}),
|
|
86
|
+
RUNS,
|
|
87
|
+
);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it("the missing ids are the stored files that the store does not have, in sorted order", () => {
|
|
91
|
+
fc.assert(
|
|
92
|
+
fc.property(filesArb, fc.func(fc.boolean()), fc.func(fc.constantFrom("embed", "link", "keep")), (files, has, kind) => {
|
|
93
|
+
let document = build(files);
|
|
94
|
+
const stored = new Set<string>();
|
|
95
|
+
for (const file of files) {
|
|
96
|
+
const choice = kind(file.id);
|
|
97
|
+
if (choice === "embed") document = embedMedia(document, new Map([[file.id, file.bytes]]), { maxBytes: 1000 });
|
|
98
|
+
else if (choice === "link") document = linkMedia(document, file.id, `https://example.com/${file.id}`);
|
|
99
|
+
else stored.add(file.id);
|
|
100
|
+
}
|
|
101
|
+
expect(codes(document)).toEqual([]);
|
|
102
|
+
const missing = missingIds(document, (id) => has(id));
|
|
103
|
+
expect(missing).toEqual([...stored].filter((id) => !has(id)).sort());
|
|
104
|
+
expect(missingIds(document, (id) => stored.has(id))).toEqual([]);
|
|
105
|
+
}),
|
|
106
|
+
RUNS,
|
|
107
|
+
);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it("the count of received bytes sets the state, and the last count wins", () => {
|
|
111
|
+
fc.assert(
|
|
112
|
+
fc.property(
|
|
113
|
+
filesArb.filter((files) => files.length > 0),
|
|
114
|
+
fc.array(fc.double({ min: 0, max: 1, noNaN: true }), { minLength: 1, maxLength: 5 }),
|
|
115
|
+
(files, shares) => {
|
|
116
|
+
const file = files[0]!;
|
|
117
|
+
const size = file.bytes.length;
|
|
118
|
+
let document = build(files);
|
|
119
|
+
let count = 0;
|
|
120
|
+
for (const share of shares) {
|
|
121
|
+
count = Math.round(share * size);
|
|
122
|
+
document = withReceived(document, file.id, count);
|
|
123
|
+
expect(codes(document)).toEqual([]);
|
|
124
|
+
}
|
|
125
|
+
const entry = document.$media[file.id]!;
|
|
126
|
+
expect(entry.state).toBe(count === 0 ? "pending" : count === size ? "complete" : "partial");
|
|
127
|
+
if (entry.state === "partial") expect(entry.received).toBe(count);
|
|
128
|
+
},
|
|
129
|
+
),
|
|
130
|
+
RUNS,
|
|
131
|
+
);
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
it("the check finds each kind of damage", () => {
|
|
135
|
+
fc.assert(
|
|
136
|
+
fc.property(filesArb.filter((files) => files.length > 0), (files) => {
|
|
137
|
+
const document = build(files);
|
|
138
|
+
const id = files[0]!.id;
|
|
139
|
+
const entry = document.$media[id]!;
|
|
140
|
+
const damage = (change: (copy: { $media: Record<string, Record<string, unknown>>; $data: unknown }) => void): MediaIssueCode[] => {
|
|
141
|
+
const copy = JSON.parse(JSON.stringify(document)) as { $media: Record<string, Record<string, unknown>>; $data: unknown };
|
|
142
|
+
change(copy);
|
|
143
|
+
return codes(copy);
|
|
144
|
+
};
|
|
145
|
+
expect(damage((copy) => (copy.$media[id]!["sha256"] = "0".repeat(64)))).toContain("ID_MISMATCH");
|
|
146
|
+
expect(damage((copy) => (copy.$media[id]!["size"] = -1))).toContain("BAD_SIZE");
|
|
147
|
+
expect(damage((copy) => (copy.$media[id]!["type"] = "Image/JPEG"))).toContain("BAD_TYPE");
|
|
148
|
+
expect(damage((copy) => (copy.$media[id]!["state"] = "done"))).toContain("BAD_STATE");
|
|
149
|
+
expect(damage((copy) => (copy.$media[id]!["url"] = "https://example.com/"))).toContain("UNKNOWN_FIELD");
|
|
150
|
+
expect(damage((copy) => (copy.$media[id]!["path"] = "/nowhere/at/all"))).toContain("PATH_NOT_FOUND");
|
|
151
|
+
expect(damage((copy) => (copy.$media[id]!["path"] = "no-slash"))).toContain("BAD_PATH");
|
|
152
|
+
expect(damage((copy) => (copy.$data = JSON.parse(JSON.stringify(copy.$data).split(id).join("f".repeat(64)))))).toContain("PATH_NOT_ID");
|
|
153
|
+
expect(damage((copy) => {
|
|
154
|
+
copy.$media[id.toUpperCase()] = copy.$media[id]!;
|
|
155
|
+
delete copy.$media[id];
|
|
156
|
+
})).toContain("BAD_ID");
|
|
157
|
+
expect(damage((copy) => (copy.$media[id] = { ...copy.$media[id]!, state: "partial", received: entry.size }))).toContain("BAD_RECEIVED");
|
|
158
|
+
expect(damage((copy) => (copy.$media[id] = { ...copy.$media[id]!, state: "linked", url: "javascript:alert(1)" }))).toContain("BAD_URL");
|
|
159
|
+
expect(damage((copy) => (copy.$media[id] = { ...copy.$media[id]!, state: "embedded", base64: "A" }))).toContain("BAD_BASE64");
|
|
160
|
+
expect(damage((copy) => (copy.$media[id] = { ...copy.$media[id]!, state: "embedded", base64: encodeBase64(new Uint8Array(entry.size + 1)) }))).toContain("SIZE_MISMATCH");
|
|
161
|
+
}),
|
|
162
|
+
RUNS,
|
|
163
|
+
);
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it("two files at one path, a non-JSON $data and other fields are refused", () => {
|
|
167
|
+
const one = "a".repeat(64);
|
|
168
|
+
const two = "b".repeat(64);
|
|
169
|
+
const entry = { type: "image/png", size: 1, state: "pending" };
|
|
170
|
+
expect(codes({ $media: { [one]: { ...entry, path: "/x", sha256: one }, [two]: { ...entry, path: "/x", sha256: two } }, $data: { x: one } })).toContain("PATH_SHARED");
|
|
171
|
+
expect(codes({ $media: {}, $data: { when: new Date(0) } })).toContain("NOT_JSON");
|
|
172
|
+
expect(codes({ $media: {}, $data: {}, extra: 1 })).toEqual(["UNKNOWN_FIELD"]);
|
|
173
|
+
expect(codes({ $data: {} })).toEqual(["MISSING_FIELD"]);
|
|
174
|
+
expect(codes([])).toEqual(["NOT_OBJECT"]);
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
it("an add at an array index that exists replaces the value, so the other paths stay true", () => {
|
|
178
|
+
const one = "1".repeat(64);
|
|
179
|
+
const two = "2".repeat(64);
|
|
180
|
+
let document: MediaDocument = { $media: {}, $data: { list: ["old", "keep"] } };
|
|
181
|
+
document = addMedia(document, { path: "/list/0", type: "image/png", size: 3, sha256: one });
|
|
182
|
+
document = addMedia(document, { path: "/list/-", type: "image/png", size: 4, sha256: two });
|
|
183
|
+
expect(document.$data).toEqual({ list: [one, "keep", two] });
|
|
184
|
+
expect(document.$media[two]!.path).toBe("/list/2");
|
|
185
|
+
expect(() => addMedia(document, { path: "/list/9", type: "image/png", size: 1, sha256: "3".repeat(64) })).toThrow(RangeError);
|
|
186
|
+
// A new file over the path of a file makes that file lose its path, and the check refuses it.
|
|
187
|
+
expect(() => addMedia(document, { path: "/list/2", type: "image/png", size: 1, sha256: "3".repeat(64) })).toThrow(/holds/);
|
|
188
|
+
});
|
|
189
|
+
});
|
package/src/module.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The procedures of @procedures/media as data. Importing this file registers nothing.
|
|
3
|
+
* The package has no procedures yet, so it has no ./register entry. The store and the procedures of the peer come in MD1 PR 2.
|
|
4
|
+
*
|
|
5
|
+
* Scaffold a procedure with: mark procedure new <name> --path packages/media
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { defineModule, registerModules, PROCEDURE_REGISTRY, type ProcedureModule, type ProcedureRegistry } from "@procedures/client";
|
|
9
|
+
|
|
10
|
+
export const mediaModule: ProcedureModule = defineModule("@procedures/media", []);
|
|
11
|
+
|
|
12
|
+
export default mediaModule;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* This function registers the procedures of @procedures/media in a registry. The default is the
|
|
16
|
+
* global registry.
|
|
17
|
+
*/
|
|
18
|
+
export function registerMediaProcedures(registry: ProcedureRegistry = PROCEDURE_REGISTRY): void {
|
|
19
|
+
registerModules(registry, [mediaModule]);
|
|
20
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import fc from "fast-check";
|
|
3
|
+
import { addRange, base64Size, decodeBase64, encodeBase64, missingRanges, normalizeRanges, planChunks, rangeBytes, type ByteRange } from "./index.js";
|
|
4
|
+
|
|
5
|
+
const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
6
|
+
|
|
7
|
+
/** A second encoder of RFC 4648, bit by bit, as the oracle of the tests. It uses no `btoa`. */
|
|
8
|
+
function referenceBase64(bytes: Uint8Array): string {
|
|
9
|
+
let bits = "";
|
|
10
|
+
for (const byte of bytes) bits += byte.toString(2).padStart(8, "0");
|
|
11
|
+
let text = "";
|
|
12
|
+
for (let at = 0; at < bits.length; at += 6) text += ALPHABET[Number.parseInt(bits.slice(at, at + 6).padEnd(6, "0"), 2)];
|
|
13
|
+
return text + "=".repeat((4 - (text.length % 4)) % 4);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
const RUNS = { numRuns: 300 };
|
|
18
|
+
|
|
19
|
+
const rangeArb = fc.tuple(fc.nat(500), fc.nat(500)).map(([a, b]): ByteRange => ({ start: Math.min(a, b), end: Math.max(a, b) }));
|
|
20
|
+
|
|
21
|
+
/** The set of bytes of a list of ranges, as the reference model. */
|
|
22
|
+
function bytesOf(ranges: readonly ByteRange[], size = Infinity): Set<number> {
|
|
23
|
+
const set = new Set<number>();
|
|
24
|
+
for (const range of ranges) for (let at = range.start; at < Math.min(range.end, size); at += 1) set.add(at);
|
|
25
|
+
return set;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function isNormal(ranges: readonly ByteRange[]): boolean {
|
|
29
|
+
return ranges.every((range, at) => range.end > range.start && (at === 0 || range.start > ranges[at - 1]!.end));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
describe("byte ranges", () => {
|
|
33
|
+
it("the normal form has the same bytes, and the order of the input does not count", () => {
|
|
34
|
+
fc.assert(
|
|
35
|
+
fc.property(fc.array(rangeArb, { maxLength: 12 }), fc.nat(), (ranges, seed) => {
|
|
36
|
+
const normal = normalizeRanges(ranges);
|
|
37
|
+
expect(isNormal(normal)).toBe(true);
|
|
38
|
+
expect(bytesOf(normal)).toEqual(bytesOf(ranges));
|
|
39
|
+
expect(normalizeRanges(normal)).toEqual(normal);
|
|
40
|
+
const turned = [...ranges.slice(seed % (ranges.length + 1)), ...ranges.slice(0, seed % (ranges.length + 1))].reverse();
|
|
41
|
+
expect(normalizeRanges(turned)).toEqual(normal);
|
|
42
|
+
expect(rangeBytes(ranges)).toBe(bytesOf(ranges).size);
|
|
43
|
+
}),
|
|
44
|
+
RUNS,
|
|
45
|
+
);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it("the missing ranges are the bytes of 0 to size that the set does not have", () => {
|
|
49
|
+
fc.assert(
|
|
50
|
+
fc.property(fc.nat(600), fc.array(rangeArb, { maxLength: 12 }), (size, ranges) => {
|
|
51
|
+
const missing = missingRanges(size, ranges);
|
|
52
|
+
expect(isNormal(missing)).toBe(true);
|
|
53
|
+
const have = bytesOf(ranges, size);
|
|
54
|
+
const gaps = bytesOf(missing);
|
|
55
|
+
for (let at = 0; at < size; at += 1) expect(gaps.has(at)).toBe(!have.has(at));
|
|
56
|
+
expect(gaps.size + have.size).toBe(size);
|
|
57
|
+
}),
|
|
58
|
+
RUNS,
|
|
59
|
+
);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it("the chunks cover the missing bytes once, each in one cell of the grid", () => {
|
|
63
|
+
fc.assert(
|
|
64
|
+
fc.property(fc.nat(600), fc.integer({ min: 1, max: 64 }), fc.array(rangeArb, { maxLength: 6 }), (size, chunkSize, received) => {
|
|
65
|
+
const chunks = planChunks(size, chunkSize, received);
|
|
66
|
+
expect(bytesOf(chunks)).toEqual(bytesOf(missingRanges(size, received)));
|
|
67
|
+
expect(rangeBytes(chunks)).toBe(chunks.reduce((total, chunk) => total + chunk.end - chunk.start, 0));
|
|
68
|
+
for (const chunk of chunks) {
|
|
69
|
+
expect(chunk.end - chunk.start).toBeGreaterThan(0);
|
|
70
|
+
expect(Math.floor(chunk.start / chunkSize)).toBe(Math.floor((chunk.end - 1) / chunkSize));
|
|
71
|
+
}
|
|
72
|
+
}),
|
|
73
|
+
RUNS,
|
|
74
|
+
);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it("after a cut, the plan is the chunks that did not arrive, with the same bounds", () => {
|
|
78
|
+
fc.assert(
|
|
79
|
+
fc.property(fc.nat(600), fc.integer({ min: 1, max: 64 }), fc.func(fc.boolean()), fc.nat(), (size, chunkSize, arrived, seed) => {
|
|
80
|
+
const plan = planChunks(size, chunkSize);
|
|
81
|
+
// The chunks arrive in an order that is not the plan order.
|
|
82
|
+
const order = [...plan.slice(seed % (plan.length + 1)), ...plan.slice(0, seed % (plan.length + 1))].reverse();
|
|
83
|
+
const got = order.filter((chunk) => arrived(chunk.start));
|
|
84
|
+
const received = got.reduce<ByteRange[]>((set, chunk) => addRange(set, chunk), []);
|
|
85
|
+
const key = (chunk: ByteRange): string => `${chunk.start}-${chunk.end}`;
|
|
86
|
+
const done = new Set(got.map(key));
|
|
87
|
+
expect(planChunks(size, chunkSize, received)).toEqual(plan.filter((chunk) => !done.has(key(chunk))));
|
|
88
|
+
const all = plan.reduce<ByteRange[]>((set, chunk) => addRange(set, chunk), []);
|
|
89
|
+
expect(missingRanges(size, all)).toEqual([]);
|
|
90
|
+
expect(rangeBytes(all)).toBe(size);
|
|
91
|
+
}),
|
|
92
|
+
RUNS,
|
|
93
|
+
);
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
it("refuses a bad range, size or chunk size", () => {
|
|
97
|
+
expect(() => normalizeRanges([{ start: 3, end: 2 }])).toThrow(RangeError);
|
|
98
|
+
expect(() => normalizeRanges([{ start: -1, end: 2 }])).toThrow(RangeError);
|
|
99
|
+
expect(() => missingRanges(1.5, [])).toThrow(RangeError);
|
|
100
|
+
expect(() => planChunks(10, 0)).toThrow(RangeError);
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
describe("base64", () => {
|
|
105
|
+
it("the decode of the encode gives the bytes, and the size needs no decode", () => {
|
|
106
|
+
fc.assert(
|
|
107
|
+
fc.property(fc.uint8Array({ maxLength: 300 }), (bytes) => {
|
|
108
|
+
const text = encodeBase64(bytes);
|
|
109
|
+
expect(Array.from(decodeBase64(text)!)).toEqual(Array.from(bytes));
|
|
110
|
+
expect(base64Size(text)).toBe(bytes.length);
|
|
111
|
+
expect(text).toBe(referenceBase64(bytes));
|
|
112
|
+
}),
|
|
113
|
+
RUNS,
|
|
114
|
+
);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it("refuses each text that is not canonical", () => {
|
|
118
|
+
for (const text of ["A", "AB", "ABC", "AB=", "A===", "AB==AB==", "ab-_", "AB C", "AB\n==", "QR==", "QUJ="]) {
|
|
119
|
+
expect(decodeBase64(text)).toBeUndefined();
|
|
120
|
+
}
|
|
121
|
+
expect(Array.from(decodeBase64("QQ==")!)).toEqual([65]);
|
|
122
|
+
expect(decodeBase64("")!.length).toBe(0);
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
it("encodes a file larger than one block of String.fromCharCode", () => {
|
|
126
|
+
const bytes = new Uint8Array(0x8000 * 2 + 5).map((_, at) => at % 251);
|
|
127
|
+
expect(encodeBase64(bytes)).toBe(referenceBase64(bytes));
|
|
128
|
+
});
|
|
129
|
+
});
|