foldkit-media 0.2.0 → 0.3.1
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/README.md +92 -28
- package/dist/{asset-Dlkss5qp.d.mts → asset-BLo8VWmd.d.mts} +1 -3
- package/dist/asset-BLo8VWmd.d.mts.map +1 -0
- package/dist/browser/index.d.mts +86 -4
- package/dist/browser/index.d.mts.map +1 -1
- package/dist/browser/index.mjs +88 -7
- package/dist/browser/index.mjs.map +1 -1
- package/dist/cloudflare/index.d.mts +9 -6
- package/dist/cloudflare/index.d.mts.map +1 -1
- package/dist/cloudflare/index.mjs +19 -9
- package/dist/cloudflare/index.mjs.map +1 -1
- package/dist/{describe-CivKHl4x.d.mts → describe-BOgc0xbR.d.mts} +2 -6
- package/dist/describe-BOgc0xbR.d.mts.map +1 -0
- package/dist/{describe-h9F5stgR.mjs → describe-C6sWA_8p.mjs} +6 -9
- package/dist/{describe-h9F5stgR.mjs.map → describe-C6sWA_8p.mjs.map} +1 -1
- package/dist/{errors-qETj7Pgi.mjs → errors-BhEgXJ4m.mjs} +2 -3
- package/dist/{errors-qETj7Pgi.mjs.map → errors-BhEgXJ4m.mjs.map} +1 -1
- package/dist/{format-BmfnR4jg.mjs → format-BCRTFU9j.mjs} +2 -3
- package/dist/{format-BmfnR4jg.mjs.map → format-BCRTFU9j.mjs.map} +1 -1
- package/dist/{icon-CowP8fQ0.mjs → icon-0A2dBtqj.mjs} +3 -4
- package/dist/{icon-CowP8fQ0.mjs.map → icon-0A2dBtqj.mjs.map} +1 -1
- package/dist/{icon-ClqtprHT.d.mts → icon-BGtxExTN.d.mts} +1 -2
- package/dist/{icon-ClqtprHT.d.mts.map → icon-BGtxExTN.d.mts.map} +1 -1
- package/dist/icons/index.d.mts +1 -3
- package/dist/icons/index.d.mts.map +1 -1
- package/dist/icons/index.mjs +2 -3
- package/dist/index.d.mts +6 -9
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +9 -13
- package/dist/index.mjs.map +1 -1
- package/dist/{limits-B6C9OOLl.mjs → limits-B4hHpyfE.mjs} +2 -3
- package/dist/{limits-B6C9OOLl.mjs.map → limits-B4hHpyfE.mjs.map} +1 -1
- package/dist/{provider-g0Vlvlrb.d.mts → provider-CB0nqu0m.d.mts} +4 -5
- package/dist/{provider-g0Vlvlrb.d.mts.map → provider-CB0nqu0m.d.mts.map} +1 -1
- package/dist/{rolldown-runtime-8H4AJuhK.mjs → rolldown-runtime-BJohB4LM.mjs} +1 -2
- package/dist/server/index.d.mts +8 -19
- package/dist/server/index.d.mts.map +1 -1
- package/dist/server/index.mjs +11 -15
- package/dist/server/index.mjs.map +1 -1
- package/dist/{services-BeakQl7F.mjs → services-7B4hsQM7.mjs} +3 -4
- package/dist/{services-BeakQl7F.mjs.map → services-7B4hsQM7.mjs.map} +1 -1
- package/dist/{services-8_h0ubLB.d.mts → services-BZoK2VOY.d.mts} +3 -5
- package/dist/services-BZoK2VOY.d.mts.map +1 -0
- package/dist/sharp/index.d.mts +2 -4
- package/dist/sharp/index.d.mts.map +1 -1
- package/dist/sharp/index.mjs +5 -6
- package/dist/{stores-BtmSl8X3.mjs → stores-CxraN3kt.mjs} +73 -31
- package/dist/stores-CxraN3kt.mjs.map +1 -0
- package/dist/unpic/index.d.mts +2 -4
- package/dist/unpic/index.d.mts.map +1 -1
- package/dist/unpic/index.mjs +2 -3
- package/dist/{upload-kp0_oK76.d.mts → upload-lVLMRJoC.d.mts} +47 -18
- package/dist/upload-lVLMRJoC.d.mts.map +1 -0
- package/dist/{variant-BOg1M0Wj.d.mts → variant-B-vyMmFB.d.mts} +2 -3
- package/dist/{variant-BOg1M0Wj.d.mts.map → variant-B-vyMmFB.d.mts.map} +1 -1
- package/dist/vite/index.d.mts +1 -5
- package/dist/vite/index.d.mts.map +1 -1
- package/dist/vite/index.mjs +20 -11
- package/dist/vite/index.mjs.map +1 -1
- package/dist/{widths-BEa9odY6.mjs → widths-qp3jshiF.mjs} +3 -4
- package/dist/{widths-BEa9odY6.mjs.map → widths-qp3jshiF.mjs.map} +1 -1
- package/dist/{widths-Cg7-x89y.d.mts → widths-upkgLdek.d.mts} +1 -3
- package/dist/widths-upkgLdek.d.mts.map +1 -0
- package/package.json +6 -6
- package/dist/asset-Dlkss5qp.d.mts.map +0 -1
- package/dist/describe-CivKHl4x.d.mts.map +0 -1
- package/dist/services-8_h0ubLB.d.mts.map +0 -1
- package/dist/stores-BtmSl8X3.mjs.map +0 -1
- package/dist/upload-kp0_oK76.d.mts.map +0 -1
- package/dist/widths-Cg7-x89y.d.mts.map +0 -1
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { n as mimeType, t as Format } from "./format-
|
|
2
|
-
import { a as ImageAsset, n as describe } from "./describe-
|
|
3
|
-
import { t as nonNegativeInteger } from "./limits-
|
|
4
|
-
import { n as OriginalTooLarge, t as OriginalNotFound } from "./errors-
|
|
5
|
-
import { r as Variants, t as Originals } from "./services-
|
|
1
|
+
import { n as mimeType, t as Format } from "./format-BCRTFU9j.mjs";
|
|
2
|
+
import { a as ImageAsset, i as HashedAsset, n as describe } from "./describe-C6sWA_8p.mjs";
|
|
3
|
+
import { t as nonNegativeInteger } from "./limits-B4hHpyfE.mjs";
|
|
4
|
+
import { n as OriginalTooLarge, t as OriginalNotFound } from "./errors-BhEgXJ4m.mjs";
|
|
5
|
+
import { r as Variants, t as Originals } from "./services-7B4hsQM7.mjs";
|
|
6
6
|
import { Context, Duration, Effect, Layer, Match, Option, Schema, Stream } from "effect";
|
|
7
7
|
import { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiGroup } from "effect/http-api";
|
|
8
8
|
import { HttpServerResponse } from "effect/http";
|
|
9
9
|
import { KeyValueStore, RateLimiter } from "effect/persistence";
|
|
10
|
-
|
|
10
|
+
// src/server/headers.ts
|
|
11
11
|
/** Where a variant came from: the edge's cache, the server's store, or made for this request. */
|
|
12
12
|
const From = Schema.Literals([
|
|
13
13
|
"edge",
|
|
@@ -51,8 +51,10 @@ const Answer = Schema.TaggedUnion({
|
|
|
51
51
|
Exhausted: {},
|
|
52
52
|
/** An upload kept; its facts are the body. */
|
|
53
53
|
Uploaded: {},
|
|
54
|
-
/** The upload policy refused
|
|
54
|
+
/** The upload policy refused who is asking. */
|
|
55
55
|
Forbidden: {},
|
|
56
|
+
/** The upload policy could not tell who is asking: an untrusted origin, a session ended. */
|
|
57
|
+
Unauthenticated: {},
|
|
56
58
|
/** An upload that is not an image the server reads. */
|
|
57
59
|
Unsupported: {},
|
|
58
60
|
/** The facts of an image named by URL; the facts are the body. */
|
|
@@ -80,14 +82,15 @@ const statusOf = Answer.match({
|
|
|
80
82
|
Exhausted: () => 503,
|
|
81
83
|
Uploaded: () => 201,
|
|
82
84
|
Forbidden: () => 403,
|
|
85
|
+
Unauthenticated: () => 401,
|
|
83
86
|
Unsupported: () => 415,
|
|
84
87
|
Described: () => 200,
|
|
85
88
|
Unavailable: () => 422
|
|
86
89
|
});
|
|
87
90
|
/**
|
|
88
91
|
* Every response's headers, decided in one place, so the server, the edge
|
|
89
|
-
* and a static host cannot disagree. A variant's URL names
|
|
90
|
-
* is kept for a year. A refusal of a variant is not: another release, or the
|
|
92
|
+
* and a static host cannot disagree. A variant's URL names the variant, and
|
|
93
|
+
* a new way of making it is a new revision, so it is kept for a year. A refusal of a variant is not: another release, or the
|
|
91
94
|
* same one configured otherwise, may answer it, so only a CDN keeps it,
|
|
92
95
|
* briefly; a failure is never kept. Every image may be read by a canvas on
|
|
93
96
|
* another origin, and its type is never sniffed.
|
|
@@ -126,6 +129,7 @@ const headersFor = (answer) => ({
|
|
|
126
129
|
}),
|
|
127
130
|
Uploaded: () => ({ "cache-control": "no-store" }),
|
|
128
131
|
Forbidden: () => ({ "cache-control": "no-store" }),
|
|
132
|
+
Unauthenticated: () => ({ "cache-control": "no-store" }),
|
|
129
133
|
Unsupported: () => ({ "cache-control": "no-store" }),
|
|
130
134
|
Described: () => ({ "cache-control": "no-store" }),
|
|
131
135
|
Unavailable: () => ({ "cache-control": "no-store" })
|
|
@@ -133,8 +137,7 @@ const headersFor = (answer) => ({
|
|
|
133
137
|
});
|
|
134
138
|
/** Whether an `If-None-Match` names `etag` (weakly, as a GET compares, or `*`). */
|
|
135
139
|
const matches = (ifNoneMatch, etag) => ifNoneMatch !== void 0 && ifNoneMatch.split(",").map((tag) => tag.trim().replace(/^W\//, "")).some((tag) => tag === "*" || tag === etag);
|
|
136
|
-
|
|
137
|
-
//#region src/server/admission.ts
|
|
140
|
+
// src/server/admission.ts
|
|
138
141
|
/** The client has made too many variants lately; it may try again after `retryAfterSeconds`. */
|
|
139
142
|
var RateLimited = class extends Schema.TaggedError()("RateLimited", { retryAfterSeconds: Schema.Number }, { httpApiStatus: 429 }) {};
|
|
140
143
|
/**
|
|
@@ -163,8 +166,7 @@ const admissionRateLimiter = (options) => Layer.effect(Admission, Effect.gen(fun
|
|
|
163
166
|
RateLimitStoreError: () => Effect.logWarning("Media: the rate limiter failed; admitting", error)
|
|
164
167
|
}))) };
|
|
165
168
|
}));
|
|
166
|
-
|
|
167
|
-
//#region src/server/facts.ts
|
|
169
|
+
// src/server/facts.ts
|
|
168
170
|
/** No facts could be read for the image at `url`; `reason` says why, for the build's report. */
|
|
169
171
|
var FactsUnavailable = class extends Schema.TaggedError()("FactsUnavailable", {
|
|
170
172
|
url: Schema.String,
|
|
@@ -271,8 +273,7 @@ const factsOf = (url, options) => {
|
|
|
271
273
|
return asset;
|
|
272
274
|
});
|
|
273
275
|
};
|
|
274
|
-
|
|
275
|
-
//#region src/server/upload.ts
|
|
276
|
+
// src/server/upload.ts
|
|
276
277
|
/**
|
|
277
278
|
* Where an original enters: `POST /_media/upload` takes an image's bytes,
|
|
278
279
|
* reads its facts (`describe`, through the `Inspector`), keeps the bytes
|
|
@@ -285,15 +286,34 @@ const factsOf = (url, options) => {
|
|
|
285
286
|
* its services: an upload, and the facts of an image named by URL.
|
|
286
287
|
*/
|
|
287
288
|
const UploadApi = HttpApi.make("foldkit-media-upload").add(HttpApiGroup.make("uploads").add(HttpApiEndpoint.post("upload", "/_media/upload"), HttpApiEndpoint.get("facts", "/_media/facts")));
|
|
288
|
-
/**
|
|
289
|
+
/**
|
|
290
|
+
* Keeps an uploaded original under its content hash, and the facts the
|
|
291
|
+
* server read from it beside it: the one writer of what `Originals` and
|
|
292
|
+
* `StoredFacts` read. The bytes are kept first, so kept facts mean kept bytes.
|
|
293
|
+
*/
|
|
289
294
|
var Uploads = class extends Context.Service()("foldkit-media/Uploads") {};
|
|
295
|
+
/**
|
|
296
|
+
* The facts the upload route read from an original, by its hash: what an
|
|
297
|
+
* application stores, rather than facts a client sends back. None for a hash
|
|
298
|
+
* nobody uploaded, or one kept before facts were.
|
|
299
|
+
*/
|
|
300
|
+
var StoredFacts = class extends Context.Service()("foldkit-media/StoredFacts") {};
|
|
301
|
+
/** Where an upload's facts are kept, beside its bytes under the same prefix. */
|
|
302
|
+
const factsKey = (hash) => `facts/${hash}`;
|
|
303
|
+
const encodeFacts = (facts) => JSON.stringify(Schema.encodeSync(ImageAsset)(facts));
|
|
304
|
+
const decodeFacts = (stored) => Schema.decodeUnknownSync(Schema.fromJsonString(HashedAsset))(stored);
|
|
290
305
|
/** The request may not upload. Why stays with the policy: the answer says only no. */
|
|
291
306
|
var UploadForbidden = class extends Schema.TaggedError()("UploadForbidden", {}, { httpApiStatus: 403 }) {};
|
|
292
307
|
/**
|
|
293
|
-
*
|
|
294
|
-
*
|
|
295
|
-
|
|
296
|
-
|
|
308
|
+
* The policy could not tell who is asking (an untrusted origin, a session
|
|
309
|
+
* that ended), so the client should sign in again rather than give up.
|
|
310
|
+
*/
|
|
311
|
+
var UploadUnauthenticated = class extends Schema.TaggedError()("UploadUnauthenticated", {}, { httpApiStatus: 401 }) {};
|
|
312
|
+
/**
|
|
313
|
+
* Who may upload, asked of every request before its body is read, with the
|
|
314
|
+
* route it is for. The route has no default: an application that serves
|
|
315
|
+
* uploads says who may (`foldkit-guard/media` over the session, a secret), so
|
|
316
|
+
* a server is never open to every upload by omission.
|
|
297
317
|
*/
|
|
298
318
|
var UploadPolicy = class extends Context.Service()("foldkit-media/UploadPolicy") {};
|
|
299
319
|
/** The Cloudflare Images binding reads at most 20 MB; so does the variant server by default. */
|
|
@@ -345,28 +365,31 @@ const uploadHandlers = (options = {}) => {
|
|
|
345
365
|
allow: options.facts?.allow ?? []
|
|
346
366
|
};
|
|
347
367
|
return group.handle("upload", ({ request }) => Effect.gen(function* () {
|
|
348
|
-
yield* policy.admit(request);
|
|
368
|
+
yield* policy.admit(request, "Upload");
|
|
349
369
|
if (!(request.headers["content-type"] ?? "").startsWith("image/")) return refused(Answer.cases.Unsupported.make({}));
|
|
350
370
|
const bytes = yield* bodyOf(request, maxBytes);
|
|
351
371
|
const described = yield* describe("upload", bytes);
|
|
352
372
|
const hash = Option.getOrThrow(described.hash);
|
|
353
|
-
|
|
354
|
-
return answered(Answer.cases.Uploaded.make({}), encode({
|
|
373
|
+
const facts = {
|
|
355
374
|
...described,
|
|
356
375
|
key: hash
|
|
357
|
-
}
|
|
376
|
+
};
|
|
377
|
+
yield* uploads.put(hash, bytes, facts);
|
|
378
|
+
return answered(Answer.cases.Uploaded.make({}), encode(facts));
|
|
358
379
|
}).pipe(Effect.provide(services), Effect.catchTags({
|
|
359
380
|
UploadForbidden: () => Effect.succeed(refused(Answer.cases.Forbidden.make({}))),
|
|
381
|
+
UploadUnauthenticated: () => Effect.succeed(refused(Answer.cases.Unauthenticated.make({}))),
|
|
360
382
|
OriginalTooLarge: () => Effect.succeed(refused(Answer.cases.TooLarge.make({}))),
|
|
361
383
|
TransformFailed: () => Effect.succeed(refused(Answer.cases.Unsupported.make({}))),
|
|
362
384
|
HttpServerError: () => Effect.succeed(refused(Answer.cases.Malformed.make({})))
|
|
363
385
|
}), Effect.withSpan("Media.upload"))).handle("facts", ({ request }) => Effect.gen(function* () {
|
|
364
|
-
yield* policy.admit(request);
|
|
386
|
+
yield* policy.admit(request, "DescribeUrl");
|
|
365
387
|
const url = new URL(request.url, "http://media.invalid").searchParams.get("url");
|
|
366
388
|
if (url === null) return refused(Answer.cases.Malformed.make({}));
|
|
367
389
|
return answered(Answer.cases.Described.make({}), encode(yield* factsOf(url, facts)));
|
|
368
390
|
}).pipe(Effect.provide(services), Effect.catchTags({
|
|
369
391
|
UploadForbidden: () => Effect.succeed(refused(Answer.cases.Forbidden.make({}))),
|
|
392
|
+
UploadUnauthenticated: () => Effect.succeed(refused(Answer.cases.Unauthenticated.make({}))),
|
|
370
393
|
FactsUnavailable: () => Effect.succeed(refused(Answer.cases.Unavailable.make({})))
|
|
371
394
|
}), Effect.withSpan("Media.facts")));
|
|
372
395
|
}));
|
|
@@ -377,6 +400,19 @@ const uploadHandlers = (options = {}) => {
|
|
|
377
400
|
* `Inspector` and the `UploadPolicy`.
|
|
378
401
|
*/
|
|
379
402
|
const uploadLayer = (options = {}) => HttpApiBuilder.layer(UploadApi).pipe(Layer.provide(uploadHandlers(options)));
|
|
403
|
+
/**
|
|
404
|
+
* Policies tried in turn, the first to admit winning: a deployment's secret
|
|
405
|
+
* for scripts beside sessions for editors. A refusal tries the next; when
|
|
406
|
+
* every one refuses, the last refusal is the answer. Each is built once, with
|
|
407
|
+
* the combined layer, and closes with it.
|
|
408
|
+
*/
|
|
409
|
+
const uploadPolicyAny = (...policies) => Layer.effect(UploadPolicy, Effect.gen(function* () {
|
|
410
|
+
const [head, ...tail] = policies;
|
|
411
|
+
const first = Context.get(yield* Layer.build(head), UploadPolicy);
|
|
412
|
+
const rest = [];
|
|
413
|
+
for (const policy of tail) rest.push(Context.get(yield* Layer.build(policy), UploadPolicy));
|
|
414
|
+
return { admit: (request, route) => rest.reduce((asked, next) => Effect.catch(asked, () => next.admit(request, route)), first.admit(request, route)) };
|
|
415
|
+
}));
|
|
380
416
|
const digestOf = (text) => Effect.promise(() => crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))).pipe(Effect.map((digest) => new Uint8Array(digest)));
|
|
381
417
|
/**
|
|
382
418
|
* Admits a request whose `Authorization` is `Bearer <token>`, and with no
|
|
@@ -397,10 +433,17 @@ const uploadPolicyBearer = (token) => Layer.succeed(UploadPolicy, { admit: (requ
|
|
|
397
433
|
*/
|
|
398
434
|
const uploadsKeyValueStore = (options = {}) => Layer.effect(Uploads, Effect.gen(function* () {
|
|
399
435
|
const store = KeyValueStore.prefix(yield* KeyValueStore.KeyValueStore, options.prefix ?? "");
|
|
400
|
-
return { put: (hash, bytes) => store.set(hash, bytes).pipe(Effect.orDie) };
|
|
436
|
+
return { put: (hash, bytes, facts) => store.set(hash, bytes).pipe(Effect.andThen(store.set(factsKey(hash), encodeFacts(facts))), Effect.orDie) };
|
|
437
|
+
}));
|
|
438
|
+
/**
|
|
439
|
+
* Upload facts read back from the application's `KeyValueStore`, under the
|
|
440
|
+
* same `prefix` as `uploadsKeyValueStore`. A store that fails is a defect.
|
|
441
|
+
*/
|
|
442
|
+
const storedFactsKeyValueStore = (options = {}) => Layer.effect(StoredFacts, Effect.gen(function* () {
|
|
443
|
+
const store = KeyValueStore.prefix(yield* KeyValueStore.KeyValueStore, options.prefix ?? "");
|
|
444
|
+
return { get: (hash) => store.get(factsKey(hash)).pipe(Effect.map((found) => Option.map(Option.fromNullishOr(found), decodeFacts)), Effect.orDie) };
|
|
401
445
|
}));
|
|
402
|
-
|
|
403
|
-
//#region src/server/stores.ts
|
|
446
|
+
// src/server/stores.ts
|
|
404
447
|
const mediaTypeOf = (key) => {
|
|
405
448
|
const extension = key.slice(key.lastIndexOf(".") + 1);
|
|
406
449
|
return Schema.is(Format)(extension) ? mimeType(extension) : "application/octet-stream";
|
|
@@ -442,7 +485,6 @@ const originalsKeyValueStore = (options = {}) => Layer.effect(Originals, Effect.
|
|
|
442
485
|
size: bytes.byteLength
|
|
443
486
|
}))) };
|
|
444
487
|
}));
|
|
445
|
-
|
|
446
|
-
export { Answer as _, UploadForbidden as a, statusOf as b, uploadHandlers as c, uploadsKeyValueStore as d, FactsUnavailable as f, admissionRateLimiter as g, RateLimited as h, UploadApi as i, uploadLayer as l, Admission as m, originalsKeyValueStore as n, UploadPolicy as o, factsOf as p, variantsKeyValueStore as r, Uploads as s, makeVariants as t, uploadPolicyBearer as u, headersFor as v, matches as y };
|
|
488
|
+
export { admissionRateLimiter as C, statusOf as D, matches as E, RateLimited as S, headersFor as T, uploadPolicyBearer as _, UploadApi as a, factsOf as b, UploadUnauthenticated as c, encodeFacts as d, factsKey as f, uploadPolicyAny as g, uploadLayer as h, StoredFacts as i, Uploads as l, uploadHandlers as m, originalsKeyValueStore as n, UploadForbidden as o, storedFactsKeyValueStore as p, variantsKeyValueStore as r, UploadPolicy as s, makeVariants as t, decodeFacts as u, uploadsKeyValueStore as v, Answer as w, Admission as x, FactsUnavailable as y };
|
|
447
489
|
|
|
448
|
-
//# sourceMappingURL=stores-
|
|
490
|
+
//# sourceMappingURL=stores-CxraN3kt.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stores-CxraN3kt.mjs","names":["DEFAULT_MAX_BYTES"],"sources":["../src/server/headers.ts","../src/server/admission.ts","../src/server/facts.ts","../src/server/upload.ts","../src/server/stores.ts"],"sourcesContent":["import { Schema } from 'effect'\n\n/** Where a variant came from: the edge's cache, the server's store, or made for this request. */\nexport const From = Schema.Literals(['edge', 'store', 'made'])\nexport type From = typeof From.Type\n\n/** Every answer the media server gives, and nothing else: each has its status and its headers. */\nexport const Answer = Schema.TaggedUnion({\n /** A variant's bytes. */\n Variant: { etag: Schema.String, from: From },\n /** The variant the request's `If-None-Match` already holds. */\n NotModified: { etag: Schema.String },\n /**\n * No URL of this server's grammar. A later release may read it (a new format\n * or parameter, in a rollout), so it is kept as briefly as `NotFound`.\n */\n Malformed: {},\n /** No original under the hash: an upload may yet put one there. */\n NotFound: {},\n /**\n * A spelling of the grammar outside this space: another release (the next\n * one, in a rollout) may offer it, so it is kept as briefly as `NotFound`.\n */\n Unoffered: {},\n /**\n * A variant of an earlier revision, made no longer and not kept: its URL now names the\n * current revision's, at `location`. A 302 kept briefly, since a rollback to that revision,\n * or a server of it still in the rollout, answers the old URL again.\n */\n Moved: { location: Schema.String },\n /** The original is larger than the server reads: a server configured to read more may. */\n TooLarge: {},\n /** The transformer failed: perhaps not for good. */\n Failed: {},\n /** The client has had too many variants made lately. */\n RateLimited: { retryAfterSeconds: Schema.Number },\n /** The host's allowance is spent. */\n Exhausted: {},\n /** An upload kept; its facts are the body. */\n Uploaded: {},\n /** The upload policy refused who is asking. */\n Forbidden: {},\n /** The upload policy could not tell who is asking: an untrusted origin, a session ended. */\n Unauthenticated: {},\n /** An upload that is not an image the server reads. */\n Unsupported: {},\n /** The facts of an image named by URL; the facts are the body. */\n Described: {},\n /** No facts could be read for that URL: a host not allowed, a read that failed, no image. */\n Unavailable: {},\n})\nexport type Answer = typeof Answer.Type\n\nconst YEAR = 'public, max-age=31536000, immutable'\n\n// What may yet be answered: the browser keeps nothing, and the edge a minute, to blunt a crawler.\nconst BRIEFLY: Readonly<Record<string, string>> = {\n 'cache-control': 'no-store',\n 'cdn-cache-control': 'public, max-age=60',\n}\n\n// Retry a spent allowance after an hour: the host's window is not known here.\nconst EXHAUSTED_RETRY_SECONDS = '3600'\n\n/** The status of each answer. */\nexport const statusOf: (answer: Answer) => number = Answer.match({\n Variant: () => 200,\n NotModified: () => 304,\n Malformed: () => 400,\n NotFound: () => 404,\n Unoffered: () => 404,\n Moved: () => 302,\n TooLarge: () => 413,\n Failed: () => 502,\n RateLimited: () => 429,\n Exhausted: () => 503,\n Uploaded: () => 201,\n Forbidden: () => 403,\n Unauthenticated: () => 401,\n Unsupported: () => 415,\n Described: () => 200,\n Unavailable: () => 422,\n})\n\n/**\n * Every response's headers, decided in one place, so the server, the edge\n * and a static host cannot disagree. A variant's URL names the variant, and\n * a new way of making it is a new revision, so it is kept for a year. A refusal of a variant is not: another release, or the\n * same one configured otherwise, may answer it, so only a CDN keeps it,\n * briefly; a failure is never kept. Every image may be read by a canvas on\n * another origin, and its type is never sniffed.\n */\nexport const headersFor = (answer: Answer): Readonly<Record<string, string>> => ({\n 'x-content-type-options': 'nosniff',\n 'access-control-allow-origin': '*',\n 'cross-origin-resource-policy': 'cross-origin',\n 'timing-allow-origin': '*',\n ...Answer.match(answer, {\n Variant: ({ etag, from }): Record<string, string> => ({\n 'cache-control': YEAR,\n etag,\n 'server-timing': `media;desc=\"${from}\"`,\n }),\n NotModified: ({ etag }): Record<string, string> => ({ 'cache-control': YEAR, etag }),\n Malformed: (): Record<string, string> => BRIEFLY,\n NotFound: (): Record<string, string> => BRIEFLY,\n Unoffered: (): Record<string, string> => BRIEFLY,\n Moved: ({ location }): Record<string, string> => ({ ...BRIEFLY, location }),\n TooLarge: (): Record<string, string> => BRIEFLY,\n Failed: (): Record<string, string> => ({ 'cache-control': 'no-store' }),\n RateLimited: ({ retryAfterSeconds }): Record<string, string> => ({\n 'cache-control': 'no-store',\n 'retry-after': String(retryAfterSeconds),\n }),\n Exhausted: (): Record<string, string> => ({\n 'cache-control': 'no-store',\n 'retry-after': EXHAUSTED_RETRY_SECONDS,\n }),\n // An upload's answers are about one request, and are never kept.\n Uploaded: (): Record<string, string> => ({ 'cache-control': 'no-store' }),\n Forbidden: (): Record<string, string> => ({ 'cache-control': 'no-store' }),\n Unauthenticated: (): Record<string, string> => ({ 'cache-control': 'no-store' }),\n Unsupported: (): Record<string, string> => ({ 'cache-control': 'no-store' }),\n Described: (): Record<string, string> => ({ 'cache-control': 'no-store' }),\n Unavailable: (): Record<string, string> => ({ 'cache-control': 'no-store' }),\n }),\n})\n\n/** Whether an `If-None-Match` names `etag` (weakly, as a GET compares, or `*`). */\nexport const matches = (ifNoneMatch: string | undefined, etag: string): boolean =>\n ifNoneMatch !== undefined &&\n ifNoneMatch\n .split(',')\n .map(tag => tag.trim().replace(/^W\\//, ''))\n .some(tag => tag === '*' || tag === etag)\n","import { Context, Duration, Effect, Layer, Match, Schema } from 'effect'\nimport { RateLimiter } from 'effect/persistence'\n\n/** The client has made too many variants lately; it may try again after `retryAfterSeconds`. */\nexport class RateLimited extends Schema.TaggedError<RateLimited>()(\n 'RateLimited',\n { retryAfterSeconds: Schema.Number },\n { httpApiStatus: 429 },\n) {}\n\n/**\n * Whether a client may have a variant made now. Asked only on a miss, after\n * the store and before the original is read: a variant already made costs a\n * read, and only making one costs work. Optional: without it, every miss is\n * admitted.\n */\nexport class Admission extends Context.Service<\n Admission,\n { readonly admit: (client: string) => Effect.Effect<void, RateLimited> }\n>()('foldkit-media/Admission') {}\n\n/**\n * Admission through Effect's `RateLimiter`, `limit` misses a client per\n * `window`, over the limiter's store (`RateLimiter.layerStoreMemory` for one\n * process, Redis for several). A store that fails admits the request, logged:\n * a limiter that is down should not take the images down with it.\n */\nexport const admissionRateLimiter = (options: {\n readonly limit: number\n readonly window: Duration.Input\n readonly algorithm?: 'fixed-window' | 'token-bucket'\n}): Layer.Layer<Admission, never, RateLimiter.RateLimiter> =>\n Layer.effect(\n Admission,\n Effect.gen(function* () {\n const limiter = yield* RateLimiter.RateLimiter\n return {\n admit: (client: string) =>\n limiter\n .consume({\n key: `foldkit-media:${client}`,\n limit: options.limit,\n window: options.window,\n algorithm: options.algorithm ?? 'token-bucket',\n onExceeded: 'fail',\n })\n .pipe(\n Effect.asVoid,\n Effect.catch(error =>\n Match.valueTags(error.reason, {\n RateLimitExceeded: ({ retryAfter }) =>\n Effect.fail(\n new RateLimited({\n retryAfterSeconds: Math.max(1, Math.ceil(Duration.toSeconds(retryAfter))),\n }),\n ),\n RateLimitStoreError: () =>\n Effect.logWarning('Media: the rate limiter failed; admitting', error),\n }),\n ),\n ),\n }\n }),\n )\n","import { Effect, Option, Schema } from 'effect'\nimport type { KeyValueStore } from 'effect/persistence'\nimport { ImageAsset } from '../asset.js'\nimport { describe, type Inspector } from '../describe.js'\nimport { nonNegativeInteger } from '../limits.js'\n\n/** No facts could be read for the image at `url`; `reason` says why, for the build's report. */\nexport class FactsUnavailable extends Schema.TaggedError<FactsUnavailable>()('FactsUnavailable', {\n url: Schema.String,\n reason: Schema.String,\n}) {}\n\nconst Cached = Schema.Struct({\n target: Schema.String,\n etag: Schema.OptionFromNullOr(Schema.String),\n asset: ImageAsset,\n})\nconst CachedJson = Schema.fromJsonString(Cached)\n\n// A redirect chain longer than this is refused, not followed.\nconst MAX_REDIRECTS = 3\n\nconst DEFAULT_MAX_BYTES = 20 * 1024 * 1024\n\nexport interface FactsOptions {\n /** The hosts an original may be read from, matched exactly: `cdn.example.com`, not a suffix. */\n readonly allow: ReadonlyArray<string>\n /** The largest original read, in bytes, counted as it streams. */\n readonly maxBytes?: number\n /** Facts kept by URL and revalidated with the original's `ETag`. */\n readonly cache?: KeyValueStore.KeyValueStore\n /** How to fetch; the platform's `fetch` by default. */\n readonly fetch?: (request: Request) => Promise<Response>\n}\n\n/**\n * The facts of an image a page names only by URL (a rich-text image, a CMS\n * block), so it is drawn with its box and placeholder like any other: its\n * original read from an allowed host and described (`describe`), with the\n * URL as its key. Only `https` on a host in `allow`, at its default port, is read, and every\n * redirect is checked again, so content cannot point the build at an\n * internal address. Kept in `cache`, an unchanged original is asked for\n * with its `ETag` and not read or inspected again.\n */\nexport const factsOf = (\n url: string,\n options: FactsOptions,\n): Effect.Effect<ImageAsset, FactsUnavailable, Inspector> => {\n const unavailable = (reason: string) => new FactsUnavailable({ url, reason })\n const fetchOne = options.fetch ?? ((request: Request) => fetch(request))\n const maxBytes = nonNegativeInteger('maxBytes', options.maxBytes ?? DEFAULT_MAX_BYTES)\n // An allowed host on its own port alone: another port of it is another service.\n const allowed = (target: URL) =>\n target.protocol === 'https:' && target.port === '' && options.allow.includes(target.hostname)\n const cacheKey = `facts/${url}`\n\n const readCached = Option.match(Option.fromNullishOr(options.cache), {\n onNone: () => Effect.succeed(Option.none<typeof Cached.Type>()),\n onSome: store =>\n store.get(cacheKey).pipe(\n Effect.map(text =>\n Option.flatMap(Option.fromNullishOr(text), Schema.decodeUnknownOption(CachedJson)),\n ),\n Effect.catch(() => Effect.succeed(Option.none<typeof Cached.Type>())),\n ),\n })\n\n const request = (cached: Option.Option<typeof Cached.Type>) =>\n Effect.tryPromise({\n try: async () => {\n let target = new URL(url)\n for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {\n if (!allowed(target))\n return { refused: `${target.origin} is not an allowed host` } as const\n const etag = Option.flatMap(cached, entry =>\n entry.target === target.href ? entry.etag : Option.none(),\n )\n const headers = Option.match(etag, {\n onNone: () => ({}),\n onSome: tag => ({ 'if-none-match': tag }),\n })\n const response = await fetchOne(new Request(target, { headers, redirect: 'manual' }))\n const location = response.headers.get('location')\n if (\n response.status < 300 ||\n response.status >= 400 ||\n response.status === 304 ||\n location === null\n ) {\n return { response, target: target.href } as const\n }\n target = new URL(location, target)\n }\n return { refused: `more than ${MAX_REDIRECTS} redirects` } as const\n },\n catch: cause => unavailable(`the fetch failed: ${String(cause)}`),\n })\n\n // Counted as it streams: a missing or false Content-Length does not let a larger body through.\n const bytesOf = (response: Response) =>\n Effect.tryPromise({\n try: async () => {\n const chunks: Array<Uint8Array> = []\n let size = 0\n const reader = response.body?.getReader()\n for (\n let read = await reader?.read();\n read !== undefined && !read.done;\n read = await reader?.read()\n ) {\n size += read.value.byteLength\n if (size > maxBytes) {\n await reader?.cancel()\n return undefined\n }\n chunks.push(read.value)\n }\n const bytes = new Uint8Array(size)\n let at = 0\n for (const chunk of chunks) {\n bytes.set(chunk, at)\n at += chunk.byteLength\n }\n return bytes\n },\n catch: cause => unavailable(`the body could not be read: ${String(cause)}`),\n })\n\n return Effect.gen(function* () {\n const cached = yield* readCached\n const answer = yield* request(cached)\n if ('refused' in answer) return yield* unavailable(answer.refused)\n const { response, target } = answer\n const unchanged = Option.filter(cached, entry => entry.target === target)\n if (response.status === 304 && Option.isSome(unchanged)) return unchanged.value.asset\n if (response.status !== 200)\n return yield* unavailable(`the original answered ${response.status}`)\n const bytes = yield* bytesOf(response)\n if (bytes === undefined)\n return yield* unavailable(`the original is larger than ${maxBytes} bytes`)\n const asset = yield* describe(url, bytes).pipe(\n Effect.mapError(error => unavailable(`the original could not be inspected: ${error._tag}`)),\n )\n const store = options.cache\n if (store !== undefined) {\n const entry = Schema.encodeSync(CachedJson)({\n target,\n etag: Option.fromNullishOr(response.headers.get('etag')),\n asset,\n })\n yield* store.set(cacheKey, entry).pipe(Effect.ignore)\n }\n return asset\n })\n}\n","/**\n * Where an original enters: `POST /_media/upload` takes an image's bytes,\n * reads its facts (`describe`, through the `Inspector`), keeps the bytes\n * under their content hash (`Uploads`), and answers the facts as an\n * `ImageAsset`, for whoever registers them (a CMS's asset row). The bytes\n * travel once, over HTTP; only the facts go on to the application's data.\n */\nimport { Context, Effect, Layer, Option, Schema, Stream } from 'effect'\nimport { HttpServerResponse, type HttpServerRequest } from 'effect/http'\nimport { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiGroup } from 'effect/http-api'\nimport { KeyValueStore } from 'effect/persistence'\nimport { HashedAsset, ImageAsset } from '../asset.js'\nimport { describe, type Inspector } from '../describe.js'\nimport { nonNegativeInteger } from '../limits.js'\nimport { OriginalTooLarge } from './errors.js'\nimport { factsOf, type FactsOptions } from './facts.js'\nimport { Answer, headersFor, statusOf } from './headers.js'\n\n/**\n * Where an original's facts enter, apart from `MediaApi`, so the variant server needs none of\n * its services: an upload, and the facts of an image named by URL.\n */\nexport const UploadApi = HttpApi.make('foldkit-media-upload').add(\n HttpApiGroup.make('uploads').add(\n HttpApiEndpoint.post('upload', '/_media/upload'),\n HttpApiEndpoint.get('facts', '/_media/facts'),\n ),\n)\n\n/**\n * Keeps an uploaded original under its content hash, and the facts the\n * server read from it beside it: the one writer of what `Originals` and\n * `StoredFacts` read. The bytes are kept first, so kept facts mean kept bytes.\n */\nexport class Uploads extends Context.Service<\n Uploads,\n {\n readonly put: (\n hash: string,\n bytes: Uint8Array<ArrayBuffer>,\n facts: ImageAsset,\n ) => Effect.Effect<void>\n }\n>()('foldkit-media/Uploads') {}\n\n/**\n * The facts the upload route read from an original, by its hash: what an\n * application stores, rather than facts a client sends back. None for a hash\n * nobody uploaded, or one kept before facts were.\n */\nexport class StoredFacts extends Context.Service<\n StoredFacts,\n { readonly get: (hash: string) => Effect.Effect<Option.Option<HashedAsset>> }\n>()('foldkit-media/StoredFacts') {}\n\n/** Where an upload's facts are kept, beside its bytes under the same prefix. */\nexport const factsKey = (hash: string): string => `facts/${hash}`\n\nexport const encodeFacts = (facts: ImageAsset): string =>\n JSON.stringify(Schema.encodeSync(ImageAsset)(facts))\n\n// Facts the route wrote are hashed; any other entry is a defect, never a silent none.\nexport const decodeFacts = (stored: string): HashedAsset =>\n Schema.decodeUnknownSync(Schema.fromJsonString(HashedAsset))(stored)\n\n/** The request may not upload. Why stays with the policy: the answer says only no. */\nexport class UploadForbidden extends Schema.TaggedError<UploadForbidden>()(\n 'UploadForbidden',\n {},\n { httpApiStatus: 403 },\n) {}\n\n/**\n * The policy could not tell who is asking (an untrusted origin, a session\n * that ended), so the client should sign in again rather than give up.\n */\nexport class UploadUnauthenticated extends Schema.TaggedError<UploadUnauthenticated>()(\n 'UploadUnauthenticated',\n {},\n { httpApiStatus: 401 },\n) {}\n\n/** Which route the policy is asked about: an upload, or the facts of an image named by URL. */\nexport type UploadRoute = 'Upload' | 'DescribeUrl'\n\n/**\n * Who may upload, asked of every request before its body is read, with the\n * route it is for. The route has no default: an application that serves\n * uploads says who may (`foldkit-guard/media` over the session, a secret), so\n * a server is never open to every upload by omission.\n */\nexport class UploadPolicy extends Context.Service<\n UploadPolicy,\n {\n readonly admit: (\n request: HttpServerRequest.HttpServerRequest,\n route: UploadRoute,\n ) => Effect.Effect<void, UploadForbidden | UploadUnauthenticated>\n }\n>()('foldkit-media/UploadPolicy') {}\n\n/** The Cloudflare Images binding reads at most 20 MB; so does the variant server by default. */\nconst DEFAULT_MAX_BYTES = 20 * 1024 * 1024\n\nexport interface UploadOptions {\n /** The largest upload read, in bytes; a larger one is a 413, read no further. */\n readonly maxBytes?: number\n /**\n * How `GET /_media/facts?url=` reads an image named by URL (`factsOf`): the hosts it may\n * fetch from, and a cache. No hosts unless given, so a server names every host it reads.\n */\n readonly facts?: Omit<FactsOptions, 'allow'> & { readonly allow?: ReadonlyArray<string> }\n}\n\nconst answered = (answer: Answer, body: unknown) =>\n HttpServerResponse.jsonUnsafe(body, { status: statusOf(answer), headers: headersFor(answer) })\n\nconst refused = (answer: Answer) => answered(answer, { error: answer._tag })\n\n/** The body, refused past `maxBytes` as it streams: a declared length is the client's to write, so it is not read. */\nconst bodyOf = (request: HttpServerRequest.HttpServerRequest, maxBytes: number) =>\n Effect.gen(function* () {\n const chunks: Array<Uint8Array> = []\n let size = 0\n yield* request.stream.pipe(\n Stream.runForEach(chunk =>\n Effect.suspend(() => {\n size += chunk.byteLength\n if (size > maxBytes) {\n return Effect.fail(new OriginalTooLarge({ size, limit: maxBytes, unit: 'bytes' }))\n }\n chunks.push(chunk)\n return Effect.void\n }),\n ),\n )\n const bytes = new Uint8Array(size)\n let at = 0\n for (const chunk of chunks) {\n bytes.set(chunk, at)\n at += chunk.byteLength\n }\n return bytes\n })\n\n/**\n * The upload route's handler. It asks the `UploadPolicy` first; takes only\n * an `image/*` body, which a browser cannot send to another origin without a\n * preflight this route never answers, so a cookie alone cannot upload from\n * another site; reads at most `maxBytes`; and refuses what the `Inspector`\n * cannot read as an image (415). Its answer is the facts, with the hash as\n * the key, `201`.\n */\nexport const uploadHandlers = (options: UploadOptions = {}) => {\n const maxBytes = nonNegativeInteger('maxBytes', options.maxBytes ?? DEFAULT_MAX_BYTES)\n const encode = Schema.encodeSync(ImageAsset)\n return HttpApiBuilder.group(UploadApi, 'uploads', group =>\n Effect.gen(function* () {\n const uploads = yield* Uploads\n const policy = yield* UploadPolicy\n const services = yield* Effect.context<Inspector>()\n const facts = { ...options.facts, allow: options.facts?.allow ?? [] }\n return group\n .handle('upload', ({ request }) =>\n Effect.gen(function* () {\n yield* policy.admit(request, 'Upload')\n if (!(request.headers['content-type'] ?? '').startsWith('image/')) {\n return refused(Answer.cases.Unsupported.make({}))\n }\n const bytes = yield* bodyOf(request, maxBytes)\n const described = yield* describe('upload', bytes)\n const hash = Option.getOrThrow(described.hash)\n const facts = { ...described, key: hash }\n yield* uploads.put(hash, bytes, facts)\n return answered(Answer.cases.Uploaded.make({}), encode(facts))\n }).pipe(\n Effect.provide(services),\n Effect.catchTags({\n UploadForbidden: () => Effect.succeed(refused(Answer.cases.Forbidden.make({}))),\n UploadUnauthenticated: () =>\n Effect.succeed(refused(Answer.cases.Unauthenticated.make({}))),\n OriginalTooLarge: () => Effect.succeed(refused(Answer.cases.TooLarge.make({}))),\n TransformFailed: () => Effect.succeed(refused(Answer.cases.Unsupported.make({}))),\n // The body broke off or could not be read: the request's fault, not the server's.\n HttpServerError: () => Effect.succeed(refused(Answer.cases.Malformed.make({}))),\n }),\n Effect.withSpan('Media.upload'),\n ),\n )\n .handle('facts', ({ request }) =>\n Effect.gen(function* () {\n yield* policy.admit(request, 'DescribeUrl')\n const url = new URL(request.url, 'http://media.invalid').searchParams.get('url')\n if (url === null) return refused(Answer.cases.Malformed.make({}))\n return answered(Answer.cases.Described.make({}), encode(yield* factsOf(url, facts)))\n }).pipe(\n Effect.provide(services),\n Effect.catchTags({\n UploadForbidden: () => Effect.succeed(refused(Answer.cases.Forbidden.make({}))),\n UploadUnauthenticated: () =>\n Effect.succeed(refused(Answer.cases.Unauthenticated.make({}))),\n // Why stays in the server: a host refused, a read failed, a file that is no image.\n FactsUnavailable: () => Effect.succeed(refused(Answer.cases.Unavailable.make({}))),\n }),\n Effect.withSpan('Media.facts'),\n ),\n )\n }),\n )\n}\n\n/**\n * The upload route as an Effect HTTP application, registered with the\n * `HttpRouter` beside the variant server's, needing `Uploads`, an\n * `Inspector` and the `UploadPolicy`.\n */\nexport const uploadLayer = (options: UploadOptions = {}) =>\n HttpApiBuilder.layer(UploadApi).pipe(Layer.provide(uploadHandlers(options)))\n\n/**\n * Policies tried in turn, the first to admit winning: a deployment's secret\n * for scripts beside sessions for editors. A refusal tries the next; when\n * every one refuses, the last refusal is the answer. Each is built once, with\n * the combined layer, and closes with it.\n */\nexport const uploadPolicyAny = <E, R>(\n ...policies: readonly [\n Layer.Layer<UploadPolicy, E, R>,\n Layer.Layer<UploadPolicy, E, R>,\n ...ReadonlyArray<Layer.Layer<UploadPolicy, E, R>>,\n ]\n): Layer.Layer<UploadPolicy, E, R> =>\n Layer.effect(\n UploadPolicy,\n Effect.gen(function* () {\n const [head, ...tail] = policies\n const first = Context.get(yield* Layer.build(head), UploadPolicy)\n const rest: Array<typeof UploadPolicy.Service> = []\n for (const policy of tail) rest.push(Context.get(yield* Layer.build(policy), UploadPolicy))\n return {\n admit: (request, route) =>\n rest.reduce(\n (asked, next) => Effect.catch(asked, () => next.admit(request, route)),\n first.admit(request, route),\n ),\n }\n }),\n )\n\nconst digestOf = (text: string) =>\n Effect.promise(() => crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))).pipe(\n Effect.map(digest => new Uint8Array(digest)),\n )\n\n/**\n * Admits a request whose `Authorization` is `Bearer <token>`, and with no\n * token (unset or empty) admits nobody, whatever it sends. The two are\n * compared by digest, every byte, so the time taken says nothing of the\n * token. For a deployment's secret (`wrangler secret put`); who may upload\n * by session is the application's own `UploadPolicy`.\n */\nexport const uploadPolicyBearer = (token: string | undefined): Layer.Layer<UploadPolicy> =>\n Layer.succeed(UploadPolicy, {\n admit: request =>\n Effect.all([\n digestOf(request.headers['authorization'] ?? ''),\n digestOf(`Bearer ${token}`),\n ]).pipe(\n Effect.flatMap(([given, expected]) => {\n let difference = token === undefined || token === '' ? 1 : 0\n for (let at = 0; at < expected.length; at++) difference |= given[at]! ^ expected[at]!\n return difference === 0 ? Effect.void : Effect.fail(new UploadForbidden({}))\n }),\n ),\n })\n\n/**\n * Uploads kept in the application's `KeyValueStore`, each under its content\n * hash after `prefix`: the same keys `originalsKeyValueStore` reads, with the\n * same `prefix`. A store that fails is a defect: an upload it dropped is lost.\n */\nexport const uploadsKeyValueStore = (\n options: { readonly prefix?: string } = {},\n): Layer.Layer<Uploads, never, KeyValueStore.KeyValueStore> =>\n Layer.effect(\n Uploads,\n Effect.gen(function* () {\n const store = KeyValueStore.prefix(yield* KeyValueStore.KeyValueStore, options.prefix ?? '')\n return {\n put: (hash: string, bytes: Uint8Array<ArrayBuffer>, facts: ImageAsset) =>\n store\n .set(hash, bytes)\n .pipe(Effect.andThen(store.set(factsKey(hash), encodeFacts(facts))), Effect.orDie),\n }\n }),\n )\n\n/**\n * Upload facts read back from the application's `KeyValueStore`, under the\n * same `prefix` as `uploadsKeyValueStore`. A store that fails is a defect.\n */\nexport const storedFactsKeyValueStore = (\n options: { readonly prefix?: string } = {},\n): Layer.Layer<StoredFacts, never, KeyValueStore.KeyValueStore> =>\n Layer.effect(\n StoredFacts,\n Effect.gen(function* () {\n const store = KeyValueStore.prefix(yield* KeyValueStore.KeyValueStore, options.prefix ?? '')\n return {\n get: (hash: string) =>\n store.get(factsKey(hash)).pipe(\n Effect.map(found => Option.map(Option.fromNullishOr(found), decodeFacts)),\n Effect.orDie,\n ),\n }\n }),\n )\n","import { Effect, Layer, Option, Schema } from 'effect'\nimport { KeyValueStore } from 'effect/persistence'\nimport { Format, mimeType } from '../format.js'\nimport { OriginalNotFound } from './errors.js'\nimport { Originals, Variants } from './services.js'\n\n// A key ends in its variant's spelling (`<hash>/w640.avif`), which names the format.\nconst mediaTypeOf = (key: string): string => {\n const extension = key.slice(key.lastIndexOf('.') + 1)\n return Schema.is(Format)(extension) ? mimeType(extension) : 'application/octet-stream'\n}\n\n/**\n * `Variants` over a `KeyValueStore`. A variant's bytes are its value and its\n * media type is its key's extension, so nothing else is stored. A store that\n * fails is logged and read as a miss, or a write it drops: a variant is a\n * cache, and the request is answered either way.\n */\nexport const makeVariants = (store: KeyValueStore.KeyValueStore): Variants['Service'] => ({\n get: key =>\n store.getUint8Array(key).pipe(\n Effect.map(bytes =>\n Option.map(Option.fromNullishOr(bytes), value => ({\n encoded: { bytes: new Uint8Array(value), contentType: mediaTypeOf(key) },\n from: 'store' as const,\n })),\n ),\n Effect.catch(error =>\n Effect.logWarning('Media: the variant store failed a read', error).pipe(\n Effect.as(Option.none()),\n ),\n ),\n ),\n put: (key, encoded) =>\n store\n .set(key, encoded.bytes)\n .pipe(\n Effect.catch(error => Effect.logWarning('Media: the variant store failed a write', error)),\n ),\n})\n\n/**\n * Variants kept in the application's `KeyValueStore`, under `prefix`:\n * `KeyValueStore.layerMemory` for tests, `layerFileSystem` on a disk,\n * `layerSql` over SQLite or D1.\n */\nexport const variantsKeyValueStore = (\n options: { readonly prefix?: string } = {},\n): Layer.Layer<Variants, never, KeyValueStore.KeyValueStore> =>\n Layer.effect(\n Variants,\n Effect.gen(function* () {\n const store = yield* KeyValueStore.KeyValueStore\n return makeVariants(KeyValueStore.prefix(store, options.prefix ?? 'variants/'))\n }),\n )\n\n/**\n * Originals in the application's `KeyValueStore`, each under its content\n * hash after `prefix`. A store that fails is a defect, not a missing\n * original: the original is the data, and a 404 would say it is gone.\n */\nexport const originalsKeyValueStore = (\n options: { readonly prefix?: string } = {},\n): Layer.Layer<Originals, never, KeyValueStore.KeyValueStore> =>\n Layer.effect(\n Originals,\n Effect.gen(function* () {\n const store = KeyValueStore.prefix(yield* KeyValueStore.KeyValueStore, options.prefix ?? '')\n return {\n get: (hash: string) =>\n store.getUint8Array(hash).pipe(\n Effect.orDie,\n Effect.flatMap(bytes =>\n bytes === undefined\n ? Effect.fail(new OriginalNotFound({ hash }))\n : Effect.succeed({\n body: new Blob([new Uint8Array(bytes)]).stream(),\n size: bytes.byteLength,\n }),\n ),\n ),\n }\n }),\n )\n"],"mappings":";;;;;;;;;;;AAGA,MAAa,OAAO,OAAO,SAAS;CAAC;CAAQ;CAAS;AAAM,CAAC;;AAI7D,MAAa,SAAS,OAAO,YAAY;;CAEvC,SAAS;EAAE,MAAM,OAAO;EAAQ,MAAM;CAAK;;CAE3C,aAAa,EAAE,MAAM,OAAO,OAAO;;;;;CAKnC,WAAW,CAAC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SACJ,MAAM,cAAc,IAAI,CAAC,CAAC,KACxB,OAAO,OACP,OAAO,SAAQ,UACb,UAAU,KAAA,IACN,OAAO,KAAK,IAAI,iBAAiB,EAAE,KAAK,CAAC,CAAC,IAC1C,OAAO,QAAQ;EACb,MAAM,IAAI,KAAK,CAAC,IAAI,WAAW,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO;EAC/C,MAAM,MAAM;CACd,CAAC,CACP,CACF,EACJ;AACF,CAAC,CACH"}
|
package/dist/unpic/index.d.mts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { i as Format, r as Encoding, t as Widths } from "../widths-
|
|
2
|
-
import { n as Provider } from "../provider-
|
|
1
|
+
import { i as Format, r as Encoding, t as Widths } from "../widths-upkgLdek.mjs";
|
|
2
|
+
import { n as Provider } from "../provider-CB0nqu0m.mjs";
|
|
3
3
|
import { Option } from "effect";
|
|
4
|
-
//#region src/unpic/index.d.ts
|
|
5
4
|
export interface DetectOptions {
|
|
6
5
|
/** The widths offered: `Widths.standard` unless given. */
|
|
7
6
|
readonly widths?: Widths | undefined;
|
|
@@ -23,5 +22,4 @@ export interface DetectOptions {
|
|
|
23
22
|
* naming AVIF over a JPEG would be a lie.
|
|
24
23
|
*/
|
|
25
24
|
export declare const detect: (url: string, options?: DetectOptions) => Option.Option<Provider>;
|
|
26
|
-
//#endregion
|
|
27
25
|
//# sourceMappingURL=index.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":["Widths.Widths"],"sources":["../../src/unpic/index.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":["Widths.Widths"],"sources":["../../src/unpic/index.ts"],"mappings":";;;iBAYiB;;WAEN,SAASA;;;;;WAKT,UAAU,cAAc;;WAExB,WAAW;;WAEX;;;;;;;;;qBAUE,SAAM,aAAe,UAAW,kBAAqB,OAAO,OAAO"}
|
package/dist/unpic/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { r as standard } from "../widths-
|
|
1
|
+
import { r as standard } from "../widths-qp3jshiF.mjs";
|
|
2
2
|
import { Option } from "effect";
|
|
3
3
|
import { getProviderForUrl, transformUrl } from "unpic";
|
|
4
|
-
|
|
4
|
+
// src/unpic/index.ts
|
|
5
5
|
/**
|
|
6
6
|
* Images on a host that resizes them itself (Shopify, Cloudinary, imgix,
|
|
7
7
|
* Contentful, and the rest unpic knows), as a `Provider`: each candidate is
|
|
@@ -38,7 +38,6 @@ const detect = (url, options = {}) => {
|
|
|
38
38
|
}
|
|
39
39
|
});
|
|
40
40
|
};
|
|
41
|
-
//#endregion
|
|
42
41
|
export { detect };
|
|
43
42
|
|
|
44
43
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import { r as ImageAsset } from "./asset-
|
|
2
|
-
import { n as Inspector } from "./describe-
|
|
3
|
-
import { Context, Duration, Effect, Layer, Schema } from "effect";
|
|
1
|
+
import { n as HashedAsset, r as ImageAsset } from "./asset-BLo8VWmd.mjs";
|
|
2
|
+
import { n as Inspector } from "./describe-BOgc0xbR.mjs";
|
|
3
|
+
import { Context, Duration, Effect, Layer, Option, Schema } from "effect";
|
|
4
4
|
import { HttpApi, HttpApiEndpoint, HttpApiGroup } from "effect/http-api";
|
|
5
5
|
import { HttpServerRequest } from "effect/http";
|
|
6
6
|
import { KeyValueStore, RateLimiter } from "effect/persistence";
|
|
7
|
-
//#region src/server/admission.d.ts
|
|
8
7
|
declare const RateLimited_base: Schema.Class<RateLimited, Schema.TaggedStruct<"RateLimited", {
|
|
9
8
|
readonly retryAfterSeconds: Schema.Number;
|
|
10
9
|
}>, import("effect/Cause").YieldableError>;
|
|
@@ -31,8 +30,6 @@ declare const admissionRateLimiter: (options: {
|
|
|
31
30
|
readonly window: Duration.Input;
|
|
32
31
|
readonly algorithm?: 'fixed-window' | 'token-bucket';
|
|
33
32
|
}) => Layer.Layer<Admission, never, RateLimiter.RateLimiter>;
|
|
34
|
-
//#endregion
|
|
35
|
-
//#region src/server/facts.d.ts
|
|
36
33
|
declare const FactsUnavailable_base: Schema.Class<FactsUnavailable, Schema.TaggedStruct<"FactsUnavailable", {
|
|
37
34
|
readonly url: Schema.String;
|
|
38
35
|
readonly reason: Schema.String;
|
|
@@ -59,29 +56,48 @@ interface FactsOptions {
|
|
|
59
56
|
* with its `ETag` and not read or inspected again.
|
|
60
57
|
*/
|
|
61
58
|
declare const factsOf: (url: string, options: FactsOptions) => Effect.Effect<ImageAsset, FactsUnavailable, Inspector>;
|
|
62
|
-
//#endregion
|
|
63
|
-
//#region src/server/upload.d.ts
|
|
64
59
|
/**
|
|
65
60
|
* Where an original's facts enter, apart from `MediaApi`, so the variant server needs none of
|
|
66
61
|
* its services: an upload, and the facts of an image named by URL.
|
|
67
62
|
*/
|
|
68
63
|
declare const UploadApi: HttpApi.HttpApi<"foldkit-media-upload", HttpApiGroup.HttpApiGroup<"uploads", HttpApiEndpoint.HttpApiEndpoint<"facts", "GET", "/_media/facts", never, never, never, never, Schema.toCodecJson<import("effect/http-api/HttpApiSchema").NoContent>, never, never, never> | HttpApiEndpoint.HttpApiEndpoint<"upload", "POST", "/_media/upload", never, never, never, never, Schema.toCodecJson<import("effect/http-api/HttpApiSchema").NoContent>, never, never, never>, false>>;
|
|
69
64
|
declare const Uploads_base: Context.ServiceClass<Uploads, "foldkit-media/Uploads", {
|
|
70
|
-
readonly put: (hash: string, bytes: Uint8Array<ArrayBuffer
|
|
65
|
+
readonly put: (hash: string, bytes: Uint8Array<ArrayBuffer>, facts: ImageAsset) => Effect.Effect<void>;
|
|
71
66
|
}>;
|
|
72
|
-
/**
|
|
67
|
+
/**
|
|
68
|
+
* Keeps an uploaded original under its content hash, and the facts the
|
|
69
|
+
* server read from it beside it: the one writer of what `Originals` and
|
|
70
|
+
* `StoredFacts` read. The bytes are kept first, so kept facts mean kept bytes.
|
|
71
|
+
*/
|
|
73
72
|
declare class Uploads extends Uploads_base {}
|
|
73
|
+
declare const StoredFacts_base: Context.ServiceClass<StoredFacts, "foldkit-media/StoredFacts", {
|
|
74
|
+
readonly get: (hash: string) => Effect.Effect<Option.Option<HashedAsset>>;
|
|
75
|
+
}>;
|
|
76
|
+
/**
|
|
77
|
+
* The facts the upload route read from an original, by its hash: what an
|
|
78
|
+
* application stores, rather than facts a client sends back. None for a hash
|
|
79
|
+
* nobody uploaded, or one kept before facts were.
|
|
80
|
+
*/
|
|
81
|
+
declare class StoredFacts extends StoredFacts_base {}
|
|
74
82
|
declare const UploadForbidden_base: Schema.Class<UploadForbidden, Schema.TaggedStruct<"UploadForbidden", {}>, import("effect/Cause").YieldableError>;
|
|
75
83
|
/** The request may not upload. Why stays with the policy: the answer says only no. */
|
|
76
84
|
declare class UploadForbidden extends UploadForbidden_base {}
|
|
85
|
+
declare const UploadUnauthenticated_base: Schema.Class<UploadUnauthenticated, Schema.TaggedStruct<"UploadUnauthenticated", {}>, import("effect/Cause").YieldableError>;
|
|
86
|
+
/**
|
|
87
|
+
* The policy could not tell who is asking (an untrusted origin, a session
|
|
88
|
+
* that ended), so the client should sign in again rather than give up.
|
|
89
|
+
*/
|
|
90
|
+
declare class UploadUnauthenticated extends UploadUnauthenticated_base {}
|
|
91
|
+
/** Which route the policy is asked about: an upload, or the facts of an image named by URL. */
|
|
92
|
+
type UploadRoute = 'Upload' | 'DescribeUrl';
|
|
77
93
|
declare const UploadPolicy_base: Context.ServiceClass<UploadPolicy, "foldkit-media/UploadPolicy", {
|
|
78
|
-
readonly admit: (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<void, UploadForbidden>;
|
|
94
|
+
readonly admit: (request: HttpServerRequest.HttpServerRequest, route: UploadRoute) => Effect.Effect<void, UploadForbidden | UploadUnauthenticated>;
|
|
79
95
|
}>;
|
|
80
96
|
/**
|
|
81
|
-
* Who may upload, asked of every request before its body is read
|
|
82
|
-
* has no default: an application that serves
|
|
83
|
-
* `foldkit-guard`
|
|
84
|
-
* open to every upload by omission.
|
|
97
|
+
* Who may upload, asked of every request before its body is read, with the
|
|
98
|
+
* route it is for. The route has no default: an application that serves
|
|
99
|
+
* uploads says who may (`foldkit-guard/media` over the session, a secret), so
|
|
100
|
+
* a server is never open to every upload by omission.
|
|
85
101
|
*/
|
|
86
102
|
declare class UploadPolicy extends UploadPolicy_base {}
|
|
87
103
|
interface UploadOptions {
|
|
@@ -110,6 +126,13 @@ declare const uploadHandlers: (options?: UploadOptions) => Layer.Layer<HttpApiGr
|
|
|
110
126
|
* `Inspector` and the `UploadPolicy`.
|
|
111
127
|
*/
|
|
112
128
|
declare const uploadLayer: (options?: UploadOptions) => Layer.Layer<never, never, import("effect/FileSystem").FileSystem | import("effect/http/Etag").Generator | import("effect/http/HttpPlatform").HttpPlatform | import("effect/http/HttpRouter").HttpRouter | Inspector | import("effect/Path").Path | UploadPolicy | Uploads>;
|
|
129
|
+
/**
|
|
130
|
+
* Policies tried in turn, the first to admit winning: a deployment's secret
|
|
131
|
+
* for scripts beside sessions for editors. A refusal tries the next; when
|
|
132
|
+
* every one refuses, the last refusal is the answer. Each is built once, with
|
|
133
|
+
* the combined layer, and closes with it.
|
|
134
|
+
*/
|
|
135
|
+
declare const uploadPolicyAny: <E, R>(...policies: readonly [Layer.Layer<UploadPolicy, E, R>, Layer.Layer<UploadPolicy, E, R>, ...ReadonlyArray<Layer.Layer<UploadPolicy, E, R>>]) => Layer.Layer<UploadPolicy, E, R>;
|
|
113
136
|
/**
|
|
114
137
|
* Admits a request whose `Authorization` is `Bearer <token>`, and with no
|
|
115
138
|
* token (unset or empty) admits nobody, whatever it sends. The two are
|
|
@@ -126,6 +149,12 @@ declare const uploadPolicyBearer: (token: string | undefined) => Layer.Layer<Upl
|
|
|
126
149
|
declare const uploadsKeyValueStore: (options?: {
|
|
127
150
|
readonly prefix?: string;
|
|
128
151
|
}) => Layer.Layer<Uploads, never, KeyValueStore.KeyValueStore>;
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
152
|
+
/**
|
|
153
|
+
* Upload facts read back from the application's `KeyValueStore`, under the
|
|
154
|
+
* same `prefix` as `uploadsKeyValueStore`. A store that fails is a defect.
|
|
155
|
+
*/
|
|
156
|
+
declare const storedFactsKeyValueStore: (options?: {
|
|
157
|
+
readonly prefix?: string;
|
|
158
|
+
}) => Layer.Layer<StoredFacts, never, KeyValueStore.KeyValueStore>;
|
|
159
|
+
export { factsOf as _, UploadPolicy as a, admissionRateLimiter as b, Uploads as c, uploadLayer as d, uploadPolicyAny as f, FactsUnavailable as g, FactsOptions as h, UploadOptions as i, storedFactsKeyValueStore as l, uploadsKeyValueStore as m, UploadApi as n, UploadRoute as o, uploadPolicyBearer as p, UploadForbidden as r, UploadUnauthenticated as s, StoredFacts as t, uploadHandlers as u, Admission as v, RateLimited as y };
|
|
160
|
+
//# sourceMappingURL=upload-lVLMRJoC.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"upload-lVLMRJoC.d.mts","names":[],"sources":["../src/server/admission.ts","../src/server/facts.ts","../src/server/upload.ts"],"mappings":";;;;;;;;;;cAIa,oBAAoB;;WAcb,QAAC,mBAAmB,OAAO,aAAa;;;;;;;;cAF/C,kBAAkB;;;;;;;cAWlB,uBAAoB;WACtB;WACA,QAAQ,SAAS;WACjB;MACP,MAAM,MAAM,kBAAkB,YAAY;;;;;;cCxBjC,yBAAyB;UAiBrB;;WAEN,OAAO;;WAEP;;WAEA,QAAQ,cAAc;;WAEtB,SAAS,SAAS,YAAY,QAAQ;;;;;;;;;;;cAYpC,UAAO,aACP,SACF,iBACR,OAAO,OAAO,YAAY,kBAAkB;;;;;cCzBlC,WAAS,QAAA,gCAAA,aAAA,wBAAA,gBAAA,6EAAA,OAAA,oDAAA,mCAAA,gBAAA,gFAAA,OAAA,oDAAA;;WAeJ,MACZ,cACA,OAAO,WAAW,cAClB,OAAO,eACJ,OAAO;;;;;;;cAPH,gBAAgB;;WAkBX,MAAC,iBAAiB,OAAO,OAAO,OAAO,OAAO;;;;;;;cAFnD,oBAAoB;;;cAgBpB,wBAAwB;;;;;;cAUxB,8BAA8B;;KAO/B;;WAWQ,QACd,SAAS,kBAAkB,mBAC3B,OAAO,gBACJ,OAAO,aAAa,kBAAkB;;;;;;;;cANlC,qBAAqB;UAajB;;WAEN;;;;;WAKA,QAAQ,KAAK;aAAoC,QAAQ;;;;;;;;;;;cA0CvD,iBAAc,UAAa,kBAAa,MAAA,MAAA,aAAA,mDAAA,YAAA,eAAA;;;;;;cA+DxC,cAAW,UAAa,kBAAa,MAAA,gDAAA,wCAAA,+CAAA,gDAAA,aAAA,kCAAA,OAAA,eAAA;;;;;;;cASrC,kBAAmB,GAAG,MAAC,oBAEhC,MAAM,MAAM,cAAc,GAAG,IAC7B,MAAM,MAAM,cAAc,GAAG,OAC1B,cAAc,MAAM,MAAM,cAAc,GAAG,SAE/C,MAAM,MAAM,cAAc,GAAG;;;;;;;;cA8BnB,qBAAkB,8BAAgC,MAAM,MAAM;;;;;;cAoB9D,uBAAoB;WACX;MACnB,MAAM,MAAM,gBAAgB,cAAc;;;;;cAkBhC,2BAAwB;WACf;MACnB,MAAM,MAAM,oBAAoB,cAAc"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as Format, t as Widths } from "./widths-
|
|
1
|
+
import { i as Format, t as Widths } from "./widths-upkgLdek.mjs";
|
|
2
2
|
import { Option, Schema } from "effect";
|
|
3
3
|
declare namespace variant_d_exports {
|
|
4
4
|
export { ContentHash, PATH, Quality, Space, Spelling, Variant, respell, revisionOf, space, standard };
|
|
@@ -64,6 +64,5 @@ declare const space: (options?: {
|
|
|
64
64
|
}) => Space;
|
|
65
65
|
/** The standard ladder, AVIF and WebP, and no quality in any URL: 16 variants an original. */
|
|
66
66
|
declare const standard: Space;
|
|
67
|
-
//#endregion
|
|
68
67
|
export { Variant as n, variant_d_exports as r, Space as t };
|
|
69
|
-
//# sourceMappingURL=variant-
|
|
68
|
+
//# sourceMappingURL=variant-B-vyMmFB.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"variant-
|
|
1
|
+
{"version":3,"file":"variant-B-vyMmFB.d.mts","names":["Widths.Widths"],"sources":["../src/variant.ts"],"mappings":";;;;;;;;;;;cAUa;;cAGA,aAAW,OAAA;;cAGX,SAAO,OAAA;;;;;cAUP,UAAQ,OAAA;;cAGR,aAAU;;cAGV,UAAO,kBAAoB;;UAIvB;WACN;WACA,QAAQ;;WAER,SAAS,OAAO;;;;;;;;UASV;WACN,QAAQA;WACR,SAAS,cAAc;;WAEvB,WAAW;;;;;;WAMX;;WAEA,QAAQ,OAAO,MAAM;;WAErB;;;;;;cAYE,QAAK;WAEL,SAASA;WACT,UAAU,cAAc;WACxB,YAAY;WACZ;MAEV;;cA2DU,UAAU"}
|
package/dist/vite/index.d.mts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { i as Format, t as Widths } from "../widths-
|
|
1
|
+
import { i as Format, t as Widths } from "../widths-upkgLdek.mjs";
|
|
2
2
|
import { Plugin } from "vite";
|
|
3
|
-
//#region src/vite/images.d.ts
|
|
4
3
|
interface ImagesOptions {
|
|
5
4
|
/** The widths offered, up to each original's own: `Widths.standard` unless given. */
|
|
6
5
|
readonly widths?: Widths | undefined;
|
|
@@ -17,8 +16,6 @@ interface ImagesOptions {
|
|
|
17
16
|
* application that imports none needs no sharp.
|
|
18
17
|
*/
|
|
19
18
|
export declare const images: (options?: ImagesOptions) => Plugin;
|
|
20
|
-
//#endregion
|
|
21
|
-
//#region src/vite/index.d.ts
|
|
22
19
|
export interface IconsOptions {
|
|
23
20
|
/** Iconify sets by prefix (`lucide`, `uil`), each read from the application's `@iconify-json/<prefix>`. */
|
|
24
21
|
readonly iconify?: ReadonlyArray<string> | undefined;
|
|
@@ -36,6 +33,5 @@ export declare const exportName: (name: string) => string;
|
|
|
36
33
|
* says why, so only importing that icon fails.
|
|
37
34
|
*/
|
|
38
35
|
export declare const icons: (options?: IconsOptions) => Plugin;
|
|
39
|
-
//#endregion
|
|
40
36
|
export type { ImagesOptions };
|
|
41
37
|
//# sourceMappingURL=index.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":["Widths.Widths"],"sources":["../../src/vite/images.ts","../../src/vite/index.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":["Widths.Widths"],"sources":["../../src/vite/images.ts","../../src/vite/index.ts"],"mappings":";;UA8BiB;;WAEN,SAASA;;WAET,UAAU,cAAc;;WAExB,WAAW;;WAEX;;;;;;;qBAoCE,SAAM,UAAa,kBAAqB;iBCtDpC;;WAEN,UAAU;;WAEV,UAAU,SAAS;;WAEnB;;;qBAWE,aAAU;;;;;;;qBAwDV,QAAK,UAAa,iBAAoB"}
|
package/dist/vite/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { r as standard } from "../widths-
|
|
2
|
-
import { a as ImageAsset, n as describe } from "../describe-
|
|
1
|
+
import { r as standard } from "../widths-qp3jshiF.mjs";
|
|
2
|
+
import { a as ImageAsset, n as describe } from "../describe-C6sWA_8p.mjs";
|
|
3
3
|
import { IconifySet, fromIconify, namesOf, parse } from "../icons/index.mjs";
|
|
4
|
-
import { n as Transformer } from "../services-
|
|
4
|
+
import { n as Transformer } from "../services-7B4hsQM7.mjs";
|
|
5
5
|
import { createRequire } from "node:module";
|
|
6
6
|
import { Cause, Exit, Layer, ManagedRuntime, Option, Schema, Semaphore } from "effect";
|
|
7
7
|
import { availableParallelism } from "node:os";
|
|
@@ -9,7 +9,7 @@ import { readFileSync, readdirSync, writeFileSync } from "node:fs";
|
|
|
9
9
|
import { extname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
10
10
|
import { createHash, randomUUID } from "node:crypto";
|
|
11
11
|
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
12
|
-
|
|
12
|
+
// src/vite/images.ts
|
|
13
13
|
/**
|
|
14
14
|
* Images as imports: `import hero from './hero.jpg?image'` gives `{ asset,
|
|
15
15
|
* provider }`, ready for `Picture.derive` or `foldkit-mixins-ui`'s `Image.view`.
|
|
@@ -164,8 +164,7 @@ const images = (options = {}) => {
|
|
|
164
164
|
}
|
|
165
165
|
};
|
|
166
166
|
};
|
|
167
|
-
|
|
168
|
-
//#region src/vite/index.ts
|
|
167
|
+
// src/vite/index.ts
|
|
169
168
|
/**
|
|
170
169
|
* Icons as imports: `import { arrowLeft } from 'virtual:foldkit-icons/lucide'`
|
|
171
170
|
* gives the icon's `IconData`, read from an Iconify set or a folder of the
|
|
@@ -237,10 +236,21 @@ const icons = (options = {}) => {
|
|
|
237
236
|
}
|
|
238
237
|
const icons = [];
|
|
239
238
|
const refused = [];
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
239
|
+
const drawn = (name) => {
|
|
240
|
+
let current = name;
|
|
241
|
+
for (let step = 0; step < 16 && set.aliases !== void 0 && Object.hasOwn(set.aliases, current); step++) current = set.aliases[current].parent;
|
|
242
|
+
return current;
|
|
243
|
+
};
|
|
244
|
+
const exported = /* @__PURE__ */ new Map();
|
|
245
|
+
for (const name of namesOf(set)) {
|
|
246
|
+
const as = exportName(name);
|
|
247
|
+
if (exported.get(as) === drawn(name)) continue;
|
|
248
|
+
exported.set(as, drawn(name));
|
|
249
|
+
try {
|
|
250
|
+
icons.push([name, fromIconify(set, name)]);
|
|
251
|
+
} catch (error) {
|
|
252
|
+
refused.push([name, error instanceof Error ? error.message : String(error)]);
|
|
253
|
+
}
|
|
244
254
|
}
|
|
245
255
|
return {
|
|
246
256
|
icons: named(prefix, icons),
|
|
@@ -324,7 +334,6 @@ const icons = (options = {}) => {
|
|
|
324
334
|
}
|
|
325
335
|
};
|
|
326
336
|
};
|
|
327
|
-
//#endregion
|
|
328
337
|
export { exportName, icons, images };
|
|
329
338
|
|
|
330
339
|
//# sourceMappingURL=index.mjs.map
|