@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/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
|
+
}
|
package/src/transfer.ts
ADDED
|
@@ -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
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
|
+
}
|