@stowage/adapter-memory 0.0.0 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +92 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +470 -0
- package/package.json +41 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Alexander Kaufmann
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# @stowage/adapter-memory
|
|
2
|
+
|
|
3
|
+
A storage held in process memory, and the implementation a third-party adapter is read against.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install @stowage/adapter-memory
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Example
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { memoryStorage } from "@stowage/adapter-memory";
|
|
15
|
+
|
|
16
|
+
const storage = memoryStorage();
|
|
17
|
+
|
|
18
|
+
await storage.put("greeting.txt", "Hello", {
|
|
19
|
+
contentType: "text/plain",
|
|
20
|
+
userMetadata: { author: "stowage" },
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
const object = await storage.get("greeting.txt");
|
|
24
|
+
console.log(object.stat.contentType, object.stat.userMetadata, await object.text());
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Runtimes
|
|
28
|
+
|
|
29
|
+
Node 24 and later, Bun, Deno and `workerd` at the compatibility date `2026-09-01`. CI last ran green on Bun 1.4.2 and Deno 2.9.6.
|
|
30
|
+
|
|
31
|
+
The bundle measures 3.3 kB minified and gzipped, `@stowage/core` included.
|
|
32
|
+
|
|
33
|
+
## Limits
|
|
34
|
+
|
|
35
|
+
- `presignedUrls` is not declared: `MemoryStorage` has neither `presignGet` nor `presignPut`
|
|
36
|
+
([spec 4.9](https://github.com/stowage-js/stowage/blob/@stowage/adapter-memory@0.1.0/docs/spec.md#49-capabilities)).
|
|
37
|
+
- Every object is held whole in memory, with no size limit of its own, so memory grows with what
|
|
38
|
+
the storage holds ([spec 5](https://github.com/stowage-js/stowage/blob/@stowage/adapter-memory@0.1.0/docs/spec.md#5-stowageadapter-memory)).
|
|
39
|
+
|
|
40
|
+
## Notes
|
|
41
|
+
|
|
42
|
+
`put` takes no `Blob`. A caller holding one passes its stream
|
|
43
|
+
([spec 4.2](https://github.com/stowage-js/stowage/blob/@stowage/adapter-memory@0.1.0/docs/spec.md#42-bodies)):
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
import { memoryStorage } from "@stowage/adapter-memory";
|
|
47
|
+
|
|
48
|
+
const storage = memoryStorage();
|
|
49
|
+
const blob = new Blob(["region,revenue\n"], { type: "text/csv" });
|
|
50
|
+
|
|
51
|
+
await storage.put("report.csv", blob.stream(), { contentType: blob.type });
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
stowage reports no progress
|
|
55
|
+
([spec 11](https://github.com/stowage-js/stowage/blob/@stowage/adapter-memory@0.1.0/docs/spec.md#11-non-goals)).
|
|
56
|
+
A caller who wants it counts the bytes on their way into `put`:
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
import { memoryStorage } from "@stowage/adapter-memory";
|
|
60
|
+
|
|
61
|
+
const storage = memoryStorage();
|
|
62
|
+
|
|
63
|
+
function countBytes(report: (bytes: number) => void): TransformStream<Uint8Array, Uint8Array> {
|
|
64
|
+
let bytes = 0;
|
|
65
|
+
|
|
66
|
+
return new TransformStream({
|
|
67
|
+
transform(chunk, controller) {
|
|
68
|
+
bytes += chunk.byteLength;
|
|
69
|
+
report(bytes);
|
|
70
|
+
controller.enqueue(chunk);
|
|
71
|
+
},
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const response = await fetch("https://example.com/fixture.json");
|
|
76
|
+
|
|
77
|
+
if (response.body === null) throw new Error("The response carries no body");
|
|
78
|
+
|
|
79
|
+
await storage.put("fixture.json", response.body.pipeThrough(countBytes(console.log)));
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Specification
|
|
83
|
+
|
|
84
|
+
[`docs/spec.md` at `@stowage/adapter-memory@0.1.0`](https://github.com/stowage-js/stowage/blob/@stowage/adapter-memory@0.1.0/docs/spec.md#5-stowageadapter-memory)
|
|
85
|
+
is the contract: a caller may rely on what it states and on nothing else this package happens to
|
|
86
|
+
export. The [terms it uses](https://github.com/stowage-js/stowage/blob/@stowage/adapter-memory@0.1.0/CONTEXT.md)
|
|
87
|
+
and the [decisions behind it](https://github.com/stowage-js/stowage/tree/@stowage/adapter-memory@0.1.0/docs/adr)
|
|
88
|
+
are at the same tag.
|
|
89
|
+
|
|
90
|
+
## License
|
|
91
|
+
|
|
92
|
+
MIT
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,470 @@
|
|
|
1
|
+
import { StorageError, invalidKeyReason } from "@stowage/core";
|
|
2
|
+
//#region src/bytes.ts
|
|
3
|
+
async function readBody(body, signal) {
|
|
4
|
+
if (isStream(body)) return await readStream(body, signal);
|
|
5
|
+
signal?.throwIfAborted();
|
|
6
|
+
return typeof body === "string" ? new TextEncoder().encode(body) : new Uint8Array(body);
|
|
7
|
+
}
|
|
8
|
+
/** Spec 4.2 leaves a stream at its end or canceled once `put` settled, read or not. */
|
|
9
|
+
async function cancelBody(body, reason) {
|
|
10
|
+
if (isStream(body)) await body.cancel(reason);
|
|
11
|
+
}
|
|
12
|
+
function isStream(body) {
|
|
13
|
+
return typeof body !== "string" && !(body instanceof Uint8Array);
|
|
14
|
+
}
|
|
15
|
+
async function readStream(stream, signal) {
|
|
16
|
+
const chunks = [];
|
|
17
|
+
await stream.pipeTo(new WritableStream({ write(chunk) {
|
|
18
|
+
chunks.push(chunk.slice());
|
|
19
|
+
} }), { signal });
|
|
20
|
+
return join(chunks);
|
|
21
|
+
}
|
|
22
|
+
function join(chunks) {
|
|
23
|
+
const bytes = new Uint8Array(chunks.reduce((size, chunk) => size + chunk.byteLength, 0));
|
|
24
|
+
let offset = 0;
|
|
25
|
+
for (const chunk of chunks) {
|
|
26
|
+
bytes.set(chunk, offset);
|
|
27
|
+
offset += chunk.byteLength;
|
|
28
|
+
}
|
|
29
|
+
return bytes;
|
|
30
|
+
}
|
|
31
|
+
//#endregion
|
|
32
|
+
//#region src/etag.ts
|
|
33
|
+
async function etagOf(bytes) {
|
|
34
|
+
const digest = await crypto.subtle.digest("SHA-256", bytes);
|
|
35
|
+
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
36
|
+
}
|
|
37
|
+
//#endregion
|
|
38
|
+
//#region src/storage-error.ts
|
|
39
|
+
function memoryError(fields) {
|
|
40
|
+
return new StorageError({
|
|
41
|
+
...fields,
|
|
42
|
+
bucket: "memory",
|
|
43
|
+
provider: "memory"
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
//#endregion
|
|
47
|
+
//#region src/key.ts
|
|
48
|
+
/** The error the key violating the rule is reported as, or `undefined` where it holds. */
|
|
49
|
+
function keyError(key, rule, operation) {
|
|
50
|
+
const reason = invalidKeyReason(key, rule);
|
|
51
|
+
if (reason === void 0) return void 0;
|
|
52
|
+
return memoryError({
|
|
53
|
+
code: "InvalidKey",
|
|
54
|
+
message: `The key ${JSON.stringify(key)} ${reason}`,
|
|
55
|
+
operation,
|
|
56
|
+
key,
|
|
57
|
+
attempts: 0
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
function requireKey(key, rule, operation) {
|
|
61
|
+
const error = keyError(key, rule, operation);
|
|
62
|
+
if (error !== void 0) throw error;
|
|
63
|
+
}
|
|
64
|
+
//#endregion
|
|
65
|
+
//#region src/cursor.ts
|
|
66
|
+
const cursorTag = "stowage-memory-1:";
|
|
67
|
+
const unitDigits = 4;
|
|
68
|
+
const hexPosition = new RegExp(`^(?:[\\da-f]{${unitDigits}})*$`);
|
|
69
|
+
/** The key a page ended on, as the opaque string that continues from there. */
|
|
70
|
+
function encodeCursor(after) {
|
|
71
|
+
return btoa(`${cursorTag}${hexOf(after)}`);
|
|
72
|
+
}
|
|
73
|
+
/** The key the cursor continues from, or `undefined` for one this adapter did not produce. */
|
|
74
|
+
function decodeCursor(cursor) {
|
|
75
|
+
let decoded;
|
|
76
|
+
try {
|
|
77
|
+
decoded = atob(cursor);
|
|
78
|
+
} catch {
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
if (!decoded.startsWith(cursorTag)) return void 0;
|
|
82
|
+
const position = decoded.slice(17);
|
|
83
|
+
return position.length > 0 && hexPosition.test(position) ? keyOf(position) : void 0;
|
|
84
|
+
}
|
|
85
|
+
function hexOf(key) {
|
|
86
|
+
const units = [];
|
|
87
|
+
for (let index = 0; index < key.length; index += 1) units.push(key.charCodeAt(index).toString(16).padStart(unitDigits, "0"));
|
|
88
|
+
return units.join("");
|
|
89
|
+
}
|
|
90
|
+
function keyOf(position) {
|
|
91
|
+
const units = [];
|
|
92
|
+
for (let index = 0; index < position.length; index += unitDigits) units.push(String.fromCharCode(Number.parseInt(position.slice(index, index + unitDigits), 16)));
|
|
93
|
+
return units.join("");
|
|
94
|
+
}
|
|
95
|
+
//#endregion
|
|
96
|
+
//#region src/options.ts
|
|
97
|
+
const operationOptionKeys = ["signal"];
|
|
98
|
+
const putOptionKeys = [
|
|
99
|
+
...operationOptionKeys,
|
|
100
|
+
"contentType",
|
|
101
|
+
"userMetadata"
|
|
102
|
+
];
|
|
103
|
+
const getOptionKeys = [...operationOptionKeys, "range"];
|
|
104
|
+
const listOptionKeys = [
|
|
105
|
+
...operationOptionKeys,
|
|
106
|
+
"prefix",
|
|
107
|
+
"delimiter",
|
|
108
|
+
"pageSize",
|
|
109
|
+
"cursor"
|
|
110
|
+
];
|
|
111
|
+
/**
|
|
112
|
+
* Refuses an option key the spec does not list (spec 4.3). TypeScript catches one at the
|
|
113
|
+
* call site; this catches the rest.
|
|
114
|
+
*/
|
|
115
|
+
function requireKnownOptions(options, known, operation) {
|
|
116
|
+
if (options === void 0) return;
|
|
117
|
+
for (const key of Object.keys(options)) {
|
|
118
|
+
if (known.includes(key)) continue;
|
|
119
|
+
throw optionError(key, "is not one this storage takes", operation);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
function optionError(option, expectation, operation) {
|
|
123
|
+
return memoryError({
|
|
124
|
+
code: "InvalidOption",
|
|
125
|
+
message: `The option \`${option}\` ${expectation}`,
|
|
126
|
+
operation,
|
|
127
|
+
attempts: 0
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
//#endregion
|
|
131
|
+
//#region src/listing.ts
|
|
132
|
+
const defaultPageSize = 1e3;
|
|
133
|
+
const maxPageSize = 1e3;
|
|
134
|
+
/** `readEntries` hands over the whole storage sorted by key, afresh for every page. */
|
|
135
|
+
function createListing(readEntries, options) {
|
|
136
|
+
return {
|
|
137
|
+
async page() {
|
|
138
|
+
const request = read(options);
|
|
139
|
+
options?.signal?.throwIfAborted();
|
|
140
|
+
const slice = take(readEntries(), request);
|
|
141
|
+
return {
|
|
142
|
+
objects: slice.objects,
|
|
143
|
+
prefixes: slice.prefixes,
|
|
144
|
+
cursor: slice.after === void 0 ? void 0 : encodeCursor(slice.after)
|
|
145
|
+
};
|
|
146
|
+
},
|
|
147
|
+
async *[Symbol.asyncIterator]() {
|
|
148
|
+
const request = read(options);
|
|
149
|
+
for (let after = request.after;;) {
|
|
150
|
+
options?.signal?.throwIfAborted();
|
|
151
|
+
const slice = take(readEntries(), {
|
|
152
|
+
...request,
|
|
153
|
+
after
|
|
154
|
+
});
|
|
155
|
+
yield* slice.objects;
|
|
156
|
+
if (slice.after === void 0) return;
|
|
157
|
+
after = slice.after;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
function read(options) {
|
|
163
|
+
requireKnownOptions(options, listOptionKeys, "list");
|
|
164
|
+
const prefix = options?.prefix ?? "";
|
|
165
|
+
requireKey(prefix, "prefix", "list");
|
|
166
|
+
const pageSize = options?.pageSize ?? defaultPageSize;
|
|
167
|
+
if (!Number.isInteger(pageSize) || pageSize < 1 || pageSize > maxPageSize) throw optionError("pageSize", `takes a whole number from 1 to ${maxPageSize}`, "list");
|
|
168
|
+
if (options?.delimiter === "") throw optionError("delimiter", "takes at least one character", "list");
|
|
169
|
+
const after = options?.cursor === void 0 ? void 0 : decodeCursor(options.cursor);
|
|
170
|
+
if (options?.cursor !== void 0 && after === void 0) throw optionError("cursor", "takes a cursor this storage handed out", "list");
|
|
171
|
+
return {
|
|
172
|
+
prefix,
|
|
173
|
+
delimiter: options?.delimiter,
|
|
174
|
+
pageSize,
|
|
175
|
+
after
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
function take(entries, request) {
|
|
179
|
+
const objects = [];
|
|
180
|
+
const prefixes = [];
|
|
181
|
+
let after;
|
|
182
|
+
for (const entry of entries) {
|
|
183
|
+
if (!entry.key.startsWith(request.prefix)) continue;
|
|
184
|
+
if (request.after !== void 0 && entry.key <= request.after) continue;
|
|
185
|
+
const pseudoDirectory = pseudoDirectoryOf(entry.key, request);
|
|
186
|
+
if (pseudoDirectory !== void 0 && prefixes.at(-1) === pseudoDirectory) {
|
|
187
|
+
after = entry.key;
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
if (objects.length + prefixes.length === request.pageSize) return {
|
|
191
|
+
objects,
|
|
192
|
+
prefixes,
|
|
193
|
+
after
|
|
194
|
+
};
|
|
195
|
+
if (pseudoDirectory === void 0) objects.push(entry);
|
|
196
|
+
else prefixes.push(pseudoDirectory);
|
|
197
|
+
after = entry.key;
|
|
198
|
+
}
|
|
199
|
+
return {
|
|
200
|
+
objects,
|
|
201
|
+
prefixes
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
function pseudoDirectoryOf(key, { prefix, delimiter }) {
|
|
205
|
+
if (delimiter === void 0) return void 0;
|
|
206
|
+
const end = key.indexOf(delimiter, prefix.length);
|
|
207
|
+
return end === -1 ? void 0 : key.slice(0, end + delimiter.length);
|
|
208
|
+
}
|
|
209
|
+
//#endregion
|
|
210
|
+
//#region src/range.ts
|
|
211
|
+
/** Refuses bounds the spec does not allow, before the key is looked up (spec 4.3). */
|
|
212
|
+
function requireRange(range) {
|
|
213
|
+
if (range === void 0) return;
|
|
214
|
+
const { start, end } = range;
|
|
215
|
+
if (!isOffset(start) || end !== void 0 && (!isOffset(end) || end < start)) throw optionError("range", "takes two whole numbers from zero up, `start` at most `end`", "get");
|
|
216
|
+
}
|
|
217
|
+
/** The bytes the range names, both ends inclusive, clipped to what the object holds. */
|
|
218
|
+
function sliceRange(bytes, range, key) {
|
|
219
|
+
if (range === void 0) return bytes;
|
|
220
|
+
if (range.start >= bytes.byteLength) throw memoryError({
|
|
221
|
+
code: "InvalidRequest",
|
|
222
|
+
message: `The range starts beyond the ${bytes.byteLength} bytes under the key ${JSON.stringify(key)}`,
|
|
223
|
+
operation: "get",
|
|
224
|
+
key,
|
|
225
|
+
attempts: 1
|
|
226
|
+
});
|
|
227
|
+
const end = Math.min(range.end ?? bytes.byteLength - 1, bytes.byteLength - 1);
|
|
228
|
+
return bytes.subarray(range.start, end + 1);
|
|
229
|
+
}
|
|
230
|
+
function isOffset(value) {
|
|
231
|
+
return Number.isInteger(value) && value >= 0;
|
|
232
|
+
}
|
|
233
|
+
//#endregion
|
|
234
|
+
//#region src/stored-object.ts
|
|
235
|
+
function createStoredObject(stat, bytes) {
|
|
236
|
+
let read = false;
|
|
237
|
+
const take = () => {
|
|
238
|
+
if (read) throw memoryError({
|
|
239
|
+
code: "InvalidRequest",
|
|
240
|
+
message: "The body of this stored object has already been read",
|
|
241
|
+
operation: "get",
|
|
242
|
+
key: stat.key,
|
|
243
|
+
attempts: 0
|
|
244
|
+
});
|
|
245
|
+
read = true;
|
|
246
|
+
return bytes;
|
|
247
|
+
};
|
|
248
|
+
const decoder = new TextDecoder();
|
|
249
|
+
return {
|
|
250
|
+
stat,
|
|
251
|
+
stream() {
|
|
252
|
+
let taken;
|
|
253
|
+
try {
|
|
254
|
+
taken = take();
|
|
255
|
+
} catch (error) {
|
|
256
|
+
return new ReadableStream({ start(controller) {
|
|
257
|
+
controller.error(error);
|
|
258
|
+
} });
|
|
259
|
+
}
|
|
260
|
+
return new ReadableStream({ start(controller) {
|
|
261
|
+
controller.enqueue(new Uint8Array(taken));
|
|
262
|
+
controller.close();
|
|
263
|
+
} });
|
|
264
|
+
},
|
|
265
|
+
async bytes() {
|
|
266
|
+
return new Uint8Array(take());
|
|
267
|
+
},
|
|
268
|
+
async text() {
|
|
269
|
+
return decoder.decode(take());
|
|
270
|
+
},
|
|
271
|
+
async json() {
|
|
272
|
+
return JSON.parse(decoder.decode(take()));
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
//#endregion
|
|
277
|
+
//#region src/user-metadata.ts
|
|
278
|
+
/** Spec 4.3 bounds the set at 2 KB of the header bytes it costs once it is encoded. */
|
|
279
|
+
const headerByteLimit = 2048;
|
|
280
|
+
/** The characters RFC 9110 allows in a field name, which is what a metadata key is. */
|
|
281
|
+
const httpToken = /^[!#$%&'*+.^_`|~\dA-Za-z-]+$/;
|
|
282
|
+
/** What travels in a header field as it stands, so it costs one byte per character. */
|
|
283
|
+
const printableAscii = /^[\x20-\x7e]*$/;
|
|
284
|
+
/** `=?UTF-8?B?` and the `?=` that closes it. */
|
|
285
|
+
const encodedWordOverhead = 12;
|
|
286
|
+
const utf8 = new TextEncoder();
|
|
287
|
+
/**
|
|
288
|
+
* The metadata as it is held: keys folded to lower case, as a header field name is.
|
|
289
|
+
* Rejects with `InvalidRequest` before anything is written (spec 4.3).
|
|
290
|
+
*/
|
|
291
|
+
function readUserMetadata(userMetadata, key) {
|
|
292
|
+
const held = Object.create(null);
|
|
293
|
+
let headerBytes = 0;
|
|
294
|
+
for (const [name, value] of Object.entries(userMetadata ?? {})) {
|
|
295
|
+
if (!httpToken.test(name)) throw refusal(`The user metadata key ${JSON.stringify(name)} is no ASCII HTTP token`, key);
|
|
296
|
+
const folded = name.toLowerCase();
|
|
297
|
+
if (folded in held) throw refusal(`The user metadata key ${JSON.stringify(folded)} is given more than once`, key);
|
|
298
|
+
held[folded] = value;
|
|
299
|
+
headerBytes += folded.length + encodedValueBytes(value);
|
|
300
|
+
}
|
|
301
|
+
if (headerBytes > headerByteLimit) throw refusal(`The user metadata is ${headerBytes} encoded header bytes, above the limit of ${headerByteLimit}`, key);
|
|
302
|
+
return Object.freeze(held);
|
|
303
|
+
}
|
|
304
|
+
function encodedValueBytes(value) {
|
|
305
|
+
if (printableAscii.test(value)) return value.length;
|
|
306
|
+
return encodedWordOverhead + 4 * Math.ceil(utf8.encode(value).length / 3);
|
|
307
|
+
}
|
|
308
|
+
function refusal(message, key) {
|
|
309
|
+
return memoryError({
|
|
310
|
+
code: "InvalidRequest",
|
|
311
|
+
message,
|
|
312
|
+
operation: "put",
|
|
313
|
+
key,
|
|
314
|
+
attempts: 0
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
//#endregion
|
|
318
|
+
//#region src/index.ts
|
|
319
|
+
function memoryStorage() {
|
|
320
|
+
return new InMemoryStorage();
|
|
321
|
+
}
|
|
322
|
+
const defaultContentType = "application/octet-stream";
|
|
323
|
+
const memoryCapabilities = Object.freeze([
|
|
324
|
+
"keyBytesPreserved",
|
|
325
|
+
"rangeReads",
|
|
326
|
+
"userMetadata"
|
|
327
|
+
]);
|
|
328
|
+
var InMemoryStorage = class {
|
|
329
|
+
provider = "memory";
|
|
330
|
+
bucket = "memory";
|
|
331
|
+
capabilities = memoryCapabilities;
|
|
332
|
+
#objects = /* @__PURE__ */ new Map();
|
|
333
|
+
async put(key, body, options) {
|
|
334
|
+
const userMetadata = await this.#accept(key, body, options);
|
|
335
|
+
const bytes = await readBody(body, options?.signal);
|
|
336
|
+
const object = {
|
|
337
|
+
key,
|
|
338
|
+
bytes,
|
|
339
|
+
contentType: options?.contentType ?? defaultContentType,
|
|
340
|
+
userMetadata,
|
|
341
|
+
etag: await etagOf(bytes),
|
|
342
|
+
lastModified: /* @__PURE__ */ new Date()
|
|
343
|
+
};
|
|
344
|
+
this.#objects.set(key, object);
|
|
345
|
+
return describe(object);
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* What `put` checks in front of the body, answering with the metadata to hold. Spec 4.2
|
|
349
|
+
* leaves a stream at its end or canceled once `put` settled, so a refusal here cancels
|
|
350
|
+
* the body it is not going to read.
|
|
351
|
+
*/
|
|
352
|
+
async #accept(key, body, options) {
|
|
353
|
+
try {
|
|
354
|
+
requireKey(key, "writable", "put");
|
|
355
|
+
requireKnownOptions(options, putOptionKeys, "put");
|
|
356
|
+
return readUserMetadata(options?.userMetadata, key);
|
|
357
|
+
} catch (refusal) {
|
|
358
|
+
try {
|
|
359
|
+
await cancelBody(body, refusal);
|
|
360
|
+
} finally {
|
|
361
|
+
throw refusal;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
async get(key, options) {
|
|
366
|
+
requireKey(key, "addressable", "get");
|
|
367
|
+
requireKnownOptions(options, getOptionKeys, "get");
|
|
368
|
+
requireRange(options?.range);
|
|
369
|
+
options?.signal?.throwIfAborted();
|
|
370
|
+
const object = this.#require(key, "get");
|
|
371
|
+
return createStoredObject(describe(object), sliceRange(object.bytes, options?.range, key));
|
|
372
|
+
}
|
|
373
|
+
async stat(key, options) {
|
|
374
|
+
requireKey(key, "addressable", "stat");
|
|
375
|
+
requireKnownOptions(options, operationOptionKeys, "stat");
|
|
376
|
+
options?.signal?.throwIfAborted();
|
|
377
|
+
return describe(this.#require(key, "stat"));
|
|
378
|
+
}
|
|
379
|
+
async exists(key, options) {
|
|
380
|
+
requireKey(key, "addressable", "exists");
|
|
381
|
+
requireKnownOptions(options, operationOptionKeys, "exists");
|
|
382
|
+
options?.signal?.throwIfAborted();
|
|
383
|
+
return this.#objects.has(key);
|
|
384
|
+
}
|
|
385
|
+
list(options) {
|
|
386
|
+
return createListing(() => this.#entries(), options);
|
|
387
|
+
}
|
|
388
|
+
async delete(...keys) {
|
|
389
|
+
const failed = [];
|
|
390
|
+
for (const key of keys) {
|
|
391
|
+
const error = keyError(key, "addressable", "delete");
|
|
392
|
+
if (error === void 0) this.#objects.delete(key);
|
|
393
|
+
else failed.push(error);
|
|
394
|
+
}
|
|
395
|
+
return {
|
|
396
|
+
requested: keys.length,
|
|
397
|
+
failed
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
async deleteAll(prefix, options) {
|
|
401
|
+
requireKey(prefix, "prefix", "deleteAll");
|
|
402
|
+
requireKnownOptions(options, operationOptionKeys, "deleteAll");
|
|
403
|
+
options?.signal?.throwIfAborted();
|
|
404
|
+
const keys = [...this.#objects.keys()].filter((key) => key.startsWith(prefix));
|
|
405
|
+
for (const key of keys) this.#objects.delete(key);
|
|
406
|
+
return {
|
|
407
|
+
requested: keys.length,
|
|
408
|
+
failed: []
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
async copy(from, to, options) {
|
|
412
|
+
return this.#copy(from, to, "copy", options);
|
|
413
|
+
}
|
|
414
|
+
async move(from, to, options) {
|
|
415
|
+
const destination = this.#copy(from, to, "move", options);
|
|
416
|
+
this.#objects.delete(from);
|
|
417
|
+
return destination;
|
|
418
|
+
}
|
|
419
|
+
#copy(from, to, operation, options) {
|
|
420
|
+
requireKey(from, "addressable", operation);
|
|
421
|
+
requireKey(to, "writable", operation);
|
|
422
|
+
requireKnownOptions(options, operationOptionKeys, operation);
|
|
423
|
+
options?.signal?.throwIfAborted();
|
|
424
|
+
if (from === to) throw memoryError({
|
|
425
|
+
code: "InvalidRequest",
|
|
426
|
+
message: `The key ${JSON.stringify(from)} is both the source and the destination`,
|
|
427
|
+
operation,
|
|
428
|
+
key: from,
|
|
429
|
+
attempts: 0
|
|
430
|
+
});
|
|
431
|
+
const object = {
|
|
432
|
+
...this.#require(from, operation),
|
|
433
|
+
key: to,
|
|
434
|
+
lastModified: /* @__PURE__ */ new Date()
|
|
435
|
+
};
|
|
436
|
+
this.#objects.set(to, object);
|
|
437
|
+
return describe(object);
|
|
438
|
+
}
|
|
439
|
+
#entries() {
|
|
440
|
+
return Array.from(this.#objects.values(), entryOf).toSorted((one, other) => one.key < other.key ? -1 : one.key > other.key ? 1 : 0);
|
|
441
|
+
}
|
|
442
|
+
#require(key, operation) {
|
|
443
|
+
const object = this.#objects.get(key);
|
|
444
|
+
if (object === void 0) throw memoryError({
|
|
445
|
+
code: "NotFound",
|
|
446
|
+
message: `No object under the key ${JSON.stringify(key)}`,
|
|
447
|
+
operation,
|
|
448
|
+
key,
|
|
449
|
+
attempts: 1
|
|
450
|
+
});
|
|
451
|
+
return object;
|
|
452
|
+
}
|
|
453
|
+
};
|
|
454
|
+
function describe(object) {
|
|
455
|
+
return {
|
|
456
|
+
...entryOf(object),
|
|
457
|
+
contentType: object.contentType,
|
|
458
|
+
userMetadata: object.userMetadata
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
function entryOf(object) {
|
|
462
|
+
return {
|
|
463
|
+
key: object.key,
|
|
464
|
+
size: object.bytes.byteLength,
|
|
465
|
+
lastModified: new Date(object.lastModified),
|
|
466
|
+
etag: object.etag
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
//#endregion
|
|
470
|
+
export { memoryStorage };
|
package/package.json
CHANGED
|
@@ -1 +1,41 @@
|
|
|
1
|
-
{
|
|
1
|
+
{
|
|
2
|
+
"name": "@stowage/adapter-memory",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "stowage adapter holding a storage in process memory, and the implementation a third-party adapter is read against.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"adapter",
|
|
7
|
+
"memory",
|
|
8
|
+
"object-storage",
|
|
9
|
+
"storage",
|
|
10
|
+
"stowage",
|
|
11
|
+
"testing"
|
|
12
|
+
],
|
|
13
|
+
"homepage": "https://github.com/stowage-js/stowage/tree/main/packages/adapter-memory#readme",
|
|
14
|
+
"bugs": "https://github.com/stowage-js/stowage/issues",
|
|
15
|
+
"license": "MIT",
|
|
16
|
+
"author": "Alexander Kaufmann",
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/stowage-js/stowage.git",
|
|
20
|
+
"directory": "packages/adapter-memory"
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"dist"
|
|
24
|
+
],
|
|
25
|
+
"type": "module",
|
|
26
|
+
"sideEffects": false,
|
|
27
|
+
"exports": {
|
|
28
|
+
".": "./dist/index.js",
|
|
29
|
+
"./package.json": "./package.json"
|
|
30
|
+
},
|
|
31
|
+
"publishConfig": {
|
|
32
|
+
"access": "public",
|
|
33
|
+
"provenance": true
|
|
34
|
+
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"@stowage/core": "^0.1.0"
|
|
37
|
+
},
|
|
38
|
+
"engines": {
|
|
39
|
+
"node": ">=24"
|
|
40
|
+
}
|
|
41
|
+
}
|