@procedures/media 0.0.0-stage → 0.68.17

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/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,130 @@
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
+ // A fixed seed: each run draws the same ranges, so a change of the coverage is a change of the code (11-28).
18
+ const RUNS = { numRuns: 300, seed: 20_261_129 };
19
+
20
+ const rangeArb = fc.tuple(fc.nat(500), fc.nat(500)).map(([a, b]): ByteRange => ({ start: Math.min(a, b), end: Math.max(a, b) }));
21
+
22
+ /** The set of bytes of a list of ranges, as the reference model. */
23
+ function bytesOf(ranges: readonly ByteRange[], size = Infinity): Set<number> {
24
+ const set = new Set<number>();
25
+ for (const range of ranges) for (let at = range.start; at < Math.min(range.end, size); at += 1) set.add(at);
26
+ return set;
27
+ }
28
+
29
+ function isNormal(ranges: readonly ByteRange[]): boolean {
30
+ return ranges.every((range, at) => range.end > range.start && (at === 0 || range.start > ranges[at - 1]!.end));
31
+ }
32
+
33
+ describe("byte ranges", () => {
34
+ it("the normal form has the same bytes, and the order of the input does not count", () => {
35
+ fc.assert(
36
+ fc.property(fc.array(rangeArb, { maxLength: 12 }), fc.nat(), (ranges, seed) => {
37
+ const normal = normalizeRanges(ranges);
38
+ expect(isNormal(normal)).toBe(true);
39
+ expect(bytesOf(normal)).toEqual(bytesOf(ranges));
40
+ expect(normalizeRanges(normal)).toEqual(normal);
41
+ const turned = [...ranges.slice(seed % (ranges.length + 1)), ...ranges.slice(0, seed % (ranges.length + 1))].reverse();
42
+ expect(normalizeRanges(turned)).toEqual(normal);
43
+ expect(rangeBytes(ranges)).toBe(bytesOf(ranges).size);
44
+ }),
45
+ RUNS,
46
+ );
47
+ });
48
+
49
+ it("the missing ranges are the bytes of 0 to size that the set does not have", () => {
50
+ fc.assert(
51
+ fc.property(fc.nat(600), fc.array(rangeArb, { maxLength: 12 }), (size, ranges) => {
52
+ const missing = missingRanges(size, ranges);
53
+ expect(isNormal(missing)).toBe(true);
54
+ const have = bytesOf(ranges, size);
55
+ const gaps = bytesOf(missing);
56
+ for (let at = 0; at < size; at += 1) expect(gaps.has(at)).toBe(!have.has(at));
57
+ expect(gaps.size + have.size).toBe(size);
58
+ }),
59
+ RUNS,
60
+ );
61
+ });
62
+
63
+ it("the chunks cover the missing bytes once, each in one cell of the grid", () => {
64
+ fc.assert(
65
+ fc.property(fc.nat(600), fc.integer({ min: 1, max: 64 }), fc.array(rangeArb, { maxLength: 6 }), (size, chunkSize, received) => {
66
+ const chunks = planChunks(size, chunkSize, received);
67
+ expect(bytesOf(chunks)).toEqual(bytesOf(missingRanges(size, received)));
68
+ expect(rangeBytes(chunks)).toBe(chunks.reduce((total, chunk) => total + chunk.end - chunk.start, 0));
69
+ for (const chunk of chunks) {
70
+ expect(chunk.end - chunk.start).toBeGreaterThan(0);
71
+ expect(Math.floor(chunk.start / chunkSize)).toBe(Math.floor((chunk.end - 1) / chunkSize));
72
+ }
73
+ }),
74
+ RUNS,
75
+ );
76
+ });
77
+
78
+ it("after a cut, the plan is the chunks that did not arrive, with the same bounds", () => {
79
+ fc.assert(
80
+ fc.property(fc.nat(600), fc.integer({ min: 1, max: 64 }), fc.func(fc.boolean()), fc.nat(), (size, chunkSize, arrived, seed) => {
81
+ const plan = planChunks(size, chunkSize);
82
+ // The chunks arrive in an order that is not the plan order.
83
+ const order = [...plan.slice(seed % (plan.length + 1)), ...plan.slice(0, seed % (plan.length + 1))].reverse();
84
+ const got = order.filter((chunk) => arrived(chunk.start));
85
+ const received = got.reduce<ByteRange[]>((set, chunk) => addRange(set, chunk), []);
86
+ const key = (chunk: ByteRange): string => `${chunk.start}-${chunk.end}`;
87
+ const done = new Set(got.map(key));
88
+ expect(planChunks(size, chunkSize, received)).toEqual(plan.filter((chunk) => !done.has(key(chunk))));
89
+ const all = plan.reduce<ByteRange[]>((set, chunk) => addRange(set, chunk), []);
90
+ expect(missingRanges(size, all)).toEqual([]);
91
+ expect(rangeBytes(all)).toBe(size);
92
+ }),
93
+ RUNS,
94
+ );
95
+ });
96
+
97
+ it("refuses a bad range, size or chunk size", () => {
98
+ expect(() => normalizeRanges([{ start: 3, end: 2 }])).toThrow(RangeError);
99
+ expect(() => normalizeRanges([{ start: -1, end: 2 }])).toThrow(RangeError);
100
+ expect(() => missingRanges(1.5, [])).toThrow(RangeError);
101
+ expect(() => planChunks(10, 0)).toThrow(RangeError);
102
+ });
103
+ });
104
+
105
+ describe("base64", () => {
106
+ it("the decode of the encode gives the bytes, and the size needs no decode", () => {
107
+ fc.assert(
108
+ fc.property(fc.uint8Array({ maxLength: 300 }), (bytes) => {
109
+ const text = encodeBase64(bytes);
110
+ expect(Array.from(decodeBase64(text)!)).toEqual(Array.from(bytes));
111
+ expect(base64Size(text)).toBe(bytes.length);
112
+ expect(text).toBe(referenceBase64(bytes));
113
+ }),
114
+ RUNS,
115
+ );
116
+ });
117
+
118
+ it("refuses each text that is not canonical", () => {
119
+ for (const text of ["A", "AB", "ABC", "AB=", "A===", "AB==AB==", "ab-_", "AB C", "AB\n==", "QR==", "QUJ="]) {
120
+ expect(decodeBase64(text)).toBeUndefined();
121
+ }
122
+ expect(Array.from(decodeBase64("QQ==")!)).toEqual([65]);
123
+ expect(decodeBase64("")!.length).toBe(0);
124
+ });
125
+
126
+ it("encodes a file larger than one block of String.fromCharCode", () => {
127
+ const bytes = new Uint8Array(0x8000 * 2 + 5).map((_, at) => at % 251);
128
+ expect(encodeBase64(bytes)).toBe(referenceBase64(bytes));
129
+ });
130
+ });
package/src/ranges.ts ADDED
@@ -0,0 +1,92 @@
1
+ /**
2
+ * The byte ranges of a file that a store has, and the chunk plan of the bytes that it does not have.
3
+ *
4
+ * Chunks go in parallel, so they arrive in any order. Thus the store keeps a set of ranges, not one count. A range is
5
+ * half-open: `start` is the first byte, and `end` is the byte after the last. A range set is in its normal form when
6
+ * its ranges are sorted, not empty, and have a gap between each two. Each function here gives the normal form.
7
+ *
8
+ * This copy is temporary. Its home is `RangeSet` of `@mark1russell7/collections`, a set of integer intervals. When
9
+ * that set is on npm, this package imports it, and this file goes.
10
+ */
11
+
12
+ /** A half-open range of bytes: from `start` to `end - 1`. */
13
+ export interface ByteRange {
14
+ readonly start: number;
15
+ readonly end: number;
16
+ }
17
+
18
+ /** This function tells if a value is a range with two safe integers and `0 <= start <= end`. */
19
+ export function isByteRange(value: unknown): value is ByteRange {
20
+ if (value === null || typeof value !== "object") return false;
21
+ const { start, end } = value as { start?: unknown; end?: unknown };
22
+ return Number.isSafeInteger(start) && Number.isSafeInteger(end) && (start as number) >= 0 && (start as number) <= (end as number);
23
+ }
24
+
25
+ function requireRange(range: ByteRange): void {
26
+ if (!isByteRange(range)) {
27
+ throw new RangeError(`The range ${JSON.stringify(range)} is not a byte range: it needs safe integers with 0 <= start <= end`);
28
+ }
29
+ }
30
+
31
+ /** This function gives the normal form of a list of ranges. The ranges that touch or overlap become one range. */
32
+ export function normalizeRanges(ranges: readonly ByteRange[]): ByteRange[] {
33
+ ranges.forEach(requireRange);
34
+ const sorted = ranges.filter((range) => range.end > range.start).sort((a, b) => a.start - b.start || a.end - b.end);
35
+ const merged: ByteRange[] = [];
36
+ for (const range of sorted) {
37
+ const last = merged[merged.length - 1];
38
+ if (last !== undefined && range.start <= last.end) {
39
+ if (range.end > last.end) merged[merged.length - 1] = { start: last.start, end: range.end };
40
+ } else {
41
+ merged.push({ start: range.start, end: range.end });
42
+ }
43
+ }
44
+ return merged;
45
+ }
46
+
47
+ /** This function adds one range to a range set, and gives the normal form. */
48
+ export function addRange(ranges: readonly ByteRange[], range: ByteRange): ByteRange[] {
49
+ return normalizeRanges([...ranges, range]);
50
+ }
51
+
52
+ /** This function gives the number of bytes in a range set. An overlap counts once. */
53
+ export function rangeBytes(ranges: readonly ByteRange[]): number {
54
+ return normalizeRanges(ranges).reduce((total, range) => total + range.end - range.start, 0);
55
+ }
56
+
57
+ function requireSize(size: number): void {
58
+ if (!Number.isSafeInteger(size) || size < 0) throw new RangeError(`The size ${size} is not a safe integer of 0 or more`);
59
+ }
60
+
61
+ /** This function gives the ranges of `0` to `size` that are not in the range set. A byte at `size` or after is ignored. */
62
+ export function missingRanges(size: number, ranges: readonly ByteRange[]): ByteRange[] {
63
+ requireSize(size);
64
+ const gaps: ByteRange[] = [];
65
+ let at = 0;
66
+ for (const range of normalizeRanges(ranges)) {
67
+ if (range.start >= size) break;
68
+ if (range.start > at) gaps.push({ start: at, end: range.start });
69
+ at = Math.max(at, range.end);
70
+ }
71
+ if (at < size) gaps.push({ start: at, end: size });
72
+ return gaps;
73
+ }
74
+
75
+ /**
76
+ * This function gives the chunks that send the missing bytes of a file. Each chunk is in one cell of the grid of
77
+ * `chunkSize`, so a chunk after a cut has the same bounds as before the cut. Each chunk has `chunkSize` bytes or fewer.
78
+ */
79
+ export function planChunks(size: number, chunkSize: number, received: readonly ByteRange[] = []): ByteRange[] {
80
+ requireSize(size);
81
+ if (!Number.isSafeInteger(chunkSize) || chunkSize < 1) throw new RangeError(`The chunk size ${chunkSize} is not a safe integer of 1 or more`);
82
+ const chunks: ByteRange[] = [];
83
+ for (const gap of missingRanges(size, received)) {
84
+ let start = gap.start;
85
+ while (start < gap.end) {
86
+ const end = Math.min(gap.end, (Math.floor(start / chunkSize) + 1) * chunkSize);
87
+ chunks.push({ start, end });
88
+ start = end;
89
+ }
90
+ }
91
+ return chunks;
92
+ }
@@ -0,0 +1,170 @@
1
+ /**
2
+ * The steps of an upload, as pure functions on a media document.
3
+ *
4
+ * 1. The client adds each file to its document (`addMedia`), with its id at its path in `$data`.
5
+ * 2. The client strips the embedded bytes (`stripMedia`) and sends the small document. The server stores it.
6
+ * 3. The server answers with the ids that its store does not have (`missingIds`).
7
+ * 4. The client sends each missing file in chunks (`planChunks`). The server sets the count of each file (`withReceived`).
8
+ *
9
+ * A small file can stay in the document (`embedMedia`), or it can be at a URL (`linkMedia`). Each function gives a
10
+ * new document and does not change its input.
11
+ */
12
+
13
+ import { applyPatch, arrayIndex, formatPointer, lookup, parsePointer } from "@procedures/json";
14
+ import { decodeBase64, encodeBase64 } from "./base64.js";
15
+ import { assertMediaDocument, isMediaId, isMediaUrl, type MediaDocument, type MediaEntry, type MediaEntryBase, type MediaTable } from "./document.js";
16
+
17
+ /** The ids of a document, in sorted order. */
18
+ export function mediaIds(document: MediaDocument): string[] {
19
+ return Object.keys(document.$media).sort();
20
+ }
21
+
22
+ /** This function tells if the store must get the bytes of an entry: its bytes are not in the document and not at a URL. */
23
+ export function isStored(entry: MediaEntry): boolean {
24
+ return entry.state !== "embedded" && entry.state !== "linked";
25
+ }
26
+
27
+ /**
28
+ * This function gives the ids of the files that the store must get, in sorted order. Each such file is not embedded
29
+ * and not linked, and `has` does not have it. The state in the document does not count, because a server does not
30
+ * trust the state from a client.
31
+ */
32
+ export function missingIds(document: MediaDocument, has: (id: string) => boolean): string[] {
33
+ return mediaIds(document).filter((id) => isStored(document.$media[id]!) && !has(id));
34
+ }
35
+
36
+ function base(entry: MediaEntry): MediaEntryBase {
37
+ return { path: entry.path, type: entry.type, size: entry.size, sha256: entry.sha256 };
38
+ }
39
+
40
+ function withEntry(document: MediaDocument, id: string, entry: MediaEntry): MediaDocument {
41
+ const $media: MediaTable = { ...document.$media, [id]: entry };
42
+ return { $media, $data: document.$data };
43
+ }
44
+
45
+ function entryOf(document: MediaDocument, id: string): MediaEntry {
46
+ if (!Object.hasOwn(document.$media, id)) throw new RangeError(`The document has no file with the id ${id}`);
47
+ return document.$media[id]!;
48
+ }
49
+
50
+ /** The result of `stripMedia`: the small document and the bytes that left it. */
51
+ export interface StrippedMedia {
52
+ readonly document: MediaDocument;
53
+ /** The bytes of each file that was embedded, by id. */
54
+ readonly files: ReadonlyMap<string, Uint8Array>;
55
+ }
56
+
57
+ /**
58
+ * This function moves the bytes of each embedded file out of the document. Each of these files becomes `pending`.
59
+ * The other entries do not change.
60
+ */
61
+ export function stripMedia(document: MediaDocument): StrippedMedia {
62
+ const files = new Map<string, Uint8Array>();
63
+ const $media: Record<string, MediaEntry> = {};
64
+ for (const id of mediaIds(document)) {
65
+ const entry = document.$media[id]!;
66
+ if (entry.state === "embedded") {
67
+ files.set(id, decodeEmbedded(id, entry.base64));
68
+ $media[id] = { ...base(entry), state: "pending" };
69
+ } else {
70
+ $media[id] = entry;
71
+ }
72
+ }
73
+ return { document: { $media, $data: document.$data }, files };
74
+ }
75
+
76
+ function decodeEmbedded(id: string, text: string): Uint8Array {
77
+ const bytes = decodeBase64(text);
78
+ if (bytes === undefined) throw new RangeError(`The file ${id} has a base64 text that is not canonical`);
79
+ return bytes;
80
+ }
81
+
82
+ /** The options of `embedMedia`. */
83
+ export interface EmbedOptions {
84
+ /** The largest file that the document holds, in bytes. The default is 65536 (64 KiB). */
85
+ readonly maxBytes?: number;
86
+ }
87
+
88
+ /** The default largest size of an embedded file: 64 KiB. */
89
+ export const DEFAULT_MAX_EMBEDDED_BYTES = 65536;
90
+
91
+ /**
92
+ * This function puts the bytes of the small files into the document. A file becomes `embedded` when `files` has its
93
+ * bytes, its size is `maxBytes` or less, and it is not linked. The caller makes sure that the bytes have the id as their
94
+ * hash: this function has no hash. A list of bytes with a different size than its entry throws a `RangeError`.
95
+ */
96
+ export function embedMedia(document: MediaDocument, files: ReadonlyMap<string, Uint8Array>, options: EmbedOptions = {}): MediaDocument {
97
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_EMBEDDED_BYTES;
98
+ let next = document;
99
+ for (const [id, bytes] of files) {
100
+ if (!Object.hasOwn(document.$media, id)) continue;
101
+ const entry = document.$media[id]!;
102
+ if (entry.state === "linked" || entry.state === "embedded" || entry.size > maxBytes) continue;
103
+ if (bytes.length !== entry.size) throw new RangeError(`The file ${id} has ${entry.size} bytes, but the bytes to embed are ${bytes.length}`);
104
+ next = withEntry(next, id, { ...base(entry), state: "embedded", base64: encodeBase64(bytes) });
105
+ }
106
+ return next;
107
+ }
108
+
109
+ /** This function sets a file to `linked`: its bytes are at the http or https URL `url`. */
110
+ export function linkMedia(document: MediaDocument, id: string, url: string): MediaDocument {
111
+ const entry = entryOf(document, id);
112
+ if (!isMediaUrl(url)) throw new RangeError(`The url ${JSON.stringify(url)} is not an absolute http or https URL`);
113
+ return withEntry(document, id, { ...base(entry), state: "linked", url });
114
+ }
115
+
116
+ /**
117
+ * This function sets the state of a stored file from the number of its bytes in the store. 0 gives `pending`, the
118
+ * size gives `complete`, and a number between them gives `partial`. An embedded or linked file throws a `RangeError`.
119
+ */
120
+ export function withReceived(document: MediaDocument, id: string, received: number): MediaDocument {
121
+ const entry = entryOf(document, id);
122
+ if (!isStored(entry)) throw new RangeError(`The file ${id} is ${entry.state}, so the store does not count its bytes`);
123
+ if (!Number.isSafeInteger(received) || received < 0 || received > entry.size) {
124
+ throw new RangeError(`The count ${received} of the file ${id} is not an integer from 0 to its size ${entry.size}`);
125
+ }
126
+ const next: MediaEntry =
127
+ received === 0
128
+ ? { ...base(entry), state: "pending" }
129
+ : received === entry.size
130
+ ? { ...base(entry), state: "complete" }
131
+ : { ...base(entry), state: "partial", received };
132
+ return withEntry(document, id, next);
133
+ }
134
+
135
+ /** A new file for `addMedia`. The caller gives the hash of its bytes: this package has no hash. */
136
+ export interface NewMedia {
137
+ /** The JSON Pointer of the file in `$data`. The parent of the pointer exists. */
138
+ readonly path: string;
139
+ readonly type: string;
140
+ readonly size: number;
141
+ readonly sha256: string;
142
+ }
143
+
144
+ /**
145
+ * This function adds a file to the document as `pending`, and puts its id at its path in `$data`. A value at the path
146
+ * is replaced. In an array, the index of the end or `-` adds the id at the end. The result is a checked
147
+ * document: a bad entry throws a `MediaDocumentError`.
148
+ */
149
+ export function addMedia(document: MediaDocument, file: NewMedia): MediaDocument {
150
+ if (!isMediaId(file.sha256)) throw new RangeError(`The hash ${JSON.stringify(file.sha256)} is not a SHA-256 in 64 lowercase hex characters`);
151
+ const tokens = parsePointer(file.path, "path");
152
+ const last = tokens[tokens.length - 1];
153
+ let path = file.path;
154
+ let op: "add" | "replace" = "add";
155
+ if (last !== undefined) {
156
+ const parent = lookup(document.$data, tokens.slice(0, -1));
157
+ if (!parent.found) throw new RangeError(`The parent of the path ${JSON.stringify(file.path)} is not in $data`);
158
+ if (Array.isArray(parent.value)) {
159
+ // An add at an index inserts and moves the files after it, so an index that exists is replaced.
160
+ const length = parent.value.length;
161
+ const index = last === "-" ? length : arrayIndex(last);
162
+ if (index === undefined || index > length) throw new RangeError(`The path ${JSON.stringify(file.path)} is not an index of its array, or "-"`);
163
+ path = formatPointer([...tokens.slice(0, -1), index]);
164
+ op = index < length ? "replace" : "add";
165
+ }
166
+ }
167
+ const $data = applyPatch(document.$data, [{ op, path, value: file.sha256 }]);
168
+ const entry: MediaEntry = { path, type: file.type, size: file.size, sha256: file.sha256, state: "pending" };
169
+ return assertMediaDocument({ $media: { ...document.$media, [file.sha256]: entry }, $data });
170
+ }
package/src/types.ts ADDED
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Type definitions of the procedures of this package
3
+ *
4
+ * mark procedure new adds the types of each new procedure here.
5
+ */
6
+
7
+ export {};
package/src/web.ts ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * This file gives a typed view of three standard globals: `btoa`, `atob` and `URL`. Node.js 22 and each browser have them.
3
+ *
4
+ * The package compiles with no library of the DOM or of Node.js. Thus the compiler finds each other API of a platform,
5
+ * and the core stays portable. The package root does not export this file.
6
+ */
7
+
8
+ interface WebGlobals {
9
+ btoa(binary: string): string;
10
+ atob(text: string): string;
11
+ readonly URL: new (text: string) => { readonly protocol: string };
12
+ }
13
+
14
+ const web = globalThis as unknown as WebGlobals;
15
+
16
+ /** This function gives the base64 text of a binary string (one character for each byte). */
17
+ export function toBase64(binary: string): string {
18
+ return web.btoa(binary);
19
+ }
20
+
21
+ /** This function gives the binary string of a base64 text. It throws for a text that is not base64. */
22
+ export function fromBase64(text: string): string {
23
+ return web.atob(text);
24
+ }
25
+
26
+ /** This function gives the protocol of an absolute URL, with its colon. It throws for a text that is not an absolute URL. */
27
+ export function urlProtocol(text: string): string {
28
+ return new web.URL(text).protocol;
29
+ }