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.
Files changed (70) hide show
  1. package/README.md +92 -28
  2. package/dist/{asset-Dlkss5qp.d.mts → asset-BLo8VWmd.d.mts} +1 -3
  3. package/dist/asset-BLo8VWmd.d.mts.map +1 -0
  4. package/dist/browser/index.d.mts +86 -4
  5. package/dist/browser/index.d.mts.map +1 -1
  6. package/dist/browser/index.mjs +88 -7
  7. package/dist/browser/index.mjs.map +1 -1
  8. package/dist/cloudflare/index.d.mts +9 -6
  9. package/dist/cloudflare/index.d.mts.map +1 -1
  10. package/dist/cloudflare/index.mjs +19 -9
  11. package/dist/cloudflare/index.mjs.map +1 -1
  12. package/dist/{describe-CivKHl4x.d.mts → describe-BOgc0xbR.d.mts} +2 -6
  13. package/dist/describe-BOgc0xbR.d.mts.map +1 -0
  14. package/dist/{describe-h9F5stgR.mjs → describe-C6sWA_8p.mjs} +6 -9
  15. package/dist/{describe-h9F5stgR.mjs.map → describe-C6sWA_8p.mjs.map} +1 -1
  16. package/dist/{errors-qETj7Pgi.mjs → errors-BhEgXJ4m.mjs} +2 -3
  17. package/dist/{errors-qETj7Pgi.mjs.map → errors-BhEgXJ4m.mjs.map} +1 -1
  18. package/dist/{format-BmfnR4jg.mjs → format-BCRTFU9j.mjs} +2 -3
  19. package/dist/{format-BmfnR4jg.mjs.map → format-BCRTFU9j.mjs.map} +1 -1
  20. package/dist/{icon-CowP8fQ0.mjs → icon-0A2dBtqj.mjs} +3 -4
  21. package/dist/{icon-CowP8fQ0.mjs.map → icon-0A2dBtqj.mjs.map} +1 -1
  22. package/dist/{icon-ClqtprHT.d.mts → icon-BGtxExTN.d.mts} +1 -2
  23. package/dist/{icon-ClqtprHT.d.mts.map → icon-BGtxExTN.d.mts.map} +1 -1
  24. package/dist/icons/index.d.mts +1 -3
  25. package/dist/icons/index.d.mts.map +1 -1
  26. package/dist/icons/index.mjs +2 -3
  27. package/dist/index.d.mts +6 -9
  28. package/dist/index.d.mts.map +1 -1
  29. package/dist/index.mjs +9 -13
  30. package/dist/index.mjs.map +1 -1
  31. package/dist/{limits-B6C9OOLl.mjs → limits-B4hHpyfE.mjs} +2 -3
  32. package/dist/{limits-B6C9OOLl.mjs.map → limits-B4hHpyfE.mjs.map} +1 -1
  33. package/dist/{provider-g0Vlvlrb.d.mts → provider-CB0nqu0m.d.mts} +4 -5
  34. package/dist/{provider-g0Vlvlrb.d.mts.map → provider-CB0nqu0m.d.mts.map} +1 -1
  35. package/dist/{rolldown-runtime-8H4AJuhK.mjs → rolldown-runtime-BJohB4LM.mjs} +1 -2
  36. package/dist/server/index.d.mts +8 -19
  37. package/dist/server/index.d.mts.map +1 -1
  38. package/dist/server/index.mjs +11 -15
  39. package/dist/server/index.mjs.map +1 -1
  40. package/dist/{services-BeakQl7F.mjs → services-7B4hsQM7.mjs} +3 -4
  41. package/dist/{services-BeakQl7F.mjs.map → services-7B4hsQM7.mjs.map} +1 -1
  42. package/dist/{services-8_h0ubLB.d.mts → services-BZoK2VOY.d.mts} +3 -5
  43. package/dist/services-BZoK2VOY.d.mts.map +1 -0
  44. package/dist/sharp/index.d.mts +2 -4
  45. package/dist/sharp/index.d.mts.map +1 -1
  46. package/dist/sharp/index.mjs +5 -6
  47. package/dist/{stores-BtmSl8X3.mjs → stores-CxraN3kt.mjs} +73 -31
  48. package/dist/stores-CxraN3kt.mjs.map +1 -0
  49. package/dist/unpic/index.d.mts +2 -4
  50. package/dist/unpic/index.d.mts.map +1 -1
  51. package/dist/unpic/index.mjs +2 -3
  52. package/dist/{upload-kp0_oK76.d.mts → upload-lVLMRJoC.d.mts} +47 -18
  53. package/dist/upload-lVLMRJoC.d.mts.map +1 -0
  54. package/dist/{variant-BOg1M0Wj.d.mts → variant-B-vyMmFB.d.mts} +2 -3
  55. package/dist/{variant-BOg1M0Wj.d.mts.map → variant-B-vyMmFB.d.mts.map} +1 -1
  56. package/dist/vite/index.d.mts +1 -5
  57. package/dist/vite/index.d.mts.map +1 -1
  58. package/dist/vite/index.mjs +20 -11
  59. package/dist/vite/index.mjs.map +1 -1
  60. package/dist/{widths-BEa9odY6.mjs → widths-qp3jshiF.mjs} +3 -4
  61. package/dist/{widths-BEa9odY6.mjs.map → widths-qp3jshiF.mjs.map} +1 -1
  62. package/dist/{widths-Cg7-x89y.d.mts → widths-upkgLdek.d.mts} +1 -3
  63. package/dist/widths-upkgLdek.d.mts.map +1 -0
  64. package/package.json +6 -6
  65. package/dist/asset-Dlkss5qp.d.mts.map +0 -1
  66. package/dist/describe-CivKHl4x.d.mts.map +0 -1
  67. package/dist/services-8_h0ubLB.d.mts.map +0 -1
  68. package/dist/stores-BtmSl8X3.mjs.map +0 -1
  69. package/dist/upload-kp0_oK76.d.mts.map +0 -1
  70. package/dist/widths-Cg7-x89y.d.mts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"provider-g0Vlvlrb.d.mts","names":["Widths.Widths","Variant.Space"],"sources":["../src/provider.ts"],"mappings":";;;;;;;;UAOiB;WACN;WACA,UAAU;;;;;;;UAQJ,YAAY,cAAc,aAAa;WAC7C,QAAQA;;WAER,SAAS,cAAc;;WAEvB,UAAU;;WAEV,MAAM,OAAO,OAAO,SAAS,YAAY,OAAO;;;UAI1C;WACN;WACA,QAAQ;WACR;;;;;;;cAQE,YAAS,OACb,cAAc,OAAK;WACN,SAAS,cAAc;WAAkB,UAAU;MACtE;;;;;;;cA2BU,SAAM;;WAGN;WACA,SAASA;;WAET;MAEV;;UA4Bc,eAAe,SAAS;WAC9B,OAAOC;;;;;;;;;;;cAYL,SAAM;;WAGN;;WAEA,QAAQA;;WAER,UAAU,cAAc;;WAExB,WAAW;WACX;MAEV"}
1
+ {"version":3,"file":"provider-CB0nqu0m.d.mts","names":["Widths.Widths","Variant.Space"],"sources":["../src/provider.ts"],"mappings":";;;;;;;;UAOiB;WACN;WACA,UAAU;;;;;;;UAQJ,YAAY,cAAc,aAAa;WAC7C,QAAQA;;WAER,SAAS,cAAc;;WAEvB,UAAU;;WAEV,MAAM,OAAO,OAAO,SAAS,YAAY,OAAO;;;UAI1C;WACN;WACA,QAAQ;WACR;;;;;;;cAQE,YAAS,OACb,cAAc,OAAK;WACN,SAAS,cAAc;WAAkB,UAAU;MACtE;;;;;;;cA2BU,SAAM;;WAGN;WACA,SAASA;;WAET;MAEV;;UA4Bc,eAAe,SAAS;WAC9B,OAAOC;;;;;;;;;;;cAYL,SAAM;;WAGN;;WAEA,QAAQA;;WAER,UAAU,cAAc;;WAExB,WAAW;WACX;MAEV"}
@@ -1,5 +1,5 @@
1
1
  import "node:module";
2
- //#region \0rolldown/runtime.js
2
+ // \0rolldown/runtime.js
3
3
  var __defProp = Object.defineProperty;
4
4
  var __exportAll = (all, no_symbols) => {
5
5
  let target = {};
@@ -10,5 +10,4 @@ var __exportAll = (all, no_symbols) => {
10
10
  if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
11
11
  return target;
12
12
  };
13
- //#endregion
14
13
  export { __exportAll as t };
@@ -1,12 +1,11 @@
1
- import { a as OriginalNotFound, c as TransformFailed, n as Inspector, o as OriginalTooLarge, s as QuotaExhausted } from "../describe-CivKHl4x.mjs";
2
- import { a as Uploads, c as uploadPolicyBearer, d as FactsUnavailable, f as factsOf, h as admissionRateLimiter, i as UploadPolicy, l as uploadsKeyValueStore, m as RateLimited, n as UploadForbidden, o as uploadHandlers, p as Admission, r as UploadOptions, s as uploadLayer, t as UploadApi, u as FactsOptions } from "../upload-kp0_oK76.mjs";
3
- import { a as Transformer, c as variantsNone, i as Originals, n as Kept, o as Variants, r as Original, s as limitTransforms, t as Encoded } from "../services-8_h0ubLB.mjs";
4
- import { t as Hosted } from "../provider-g0Vlvlrb.mjs";
1
+ import { a as OriginalNotFound, c as TransformFailed, n as Inspector, o as OriginalTooLarge, s as QuotaExhausted } from "../describe-BOgc0xbR.mjs";
2
+ import { _ as factsOf, a as UploadPolicy, b as admissionRateLimiter, c as Uploads, d as uploadLayer, f as uploadPolicyAny, g as FactsUnavailable, h as FactsOptions, i as UploadOptions, l as storedFactsKeyValueStore, m as uploadsKeyValueStore, n as UploadApi, o as UploadRoute, p as uploadPolicyBearer, r as UploadForbidden, s as UploadUnauthenticated, t as StoredFacts, u as uploadHandlers, v as Admission, y as RateLimited } from "../upload-lVLMRJoC.mjs";
3
+ import { a as Transformer, c as variantsNone, i as Originals, n as Kept, o as Variants, r as Original, s as limitTransforms, t as Encoded } from "../services-BZoK2VOY.mjs";
4
+ import { t as Hosted } from "../provider-CB0nqu0m.mjs";
5
5
  import { Layer, Schema } from "effect";
6
6
  import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiSchema } from "effect/http-api";
7
7
  import { HttpRouter, HttpServer, HttpServerRequest } from "effect/http";
8
8
  import { KeyValueStore } from "effect/persistence";
9
- //#region src/server/api.d.ts
10
9
  /**
11
10
  * The media server's HTTP API: one route, a variant of an original named by
12
11
  * its content hash. The route takes its params as text, and the handler
@@ -18,8 +17,6 @@ export declare const MediaApi: HttpApi.HttpApi<"foldkit-media", HttpApiGroup.Htt
18
17
  hash: Schema.String;
19
18
  variant: Schema.String;
20
19
  }>>, never, never, never, HttpApiSchema.StreamUint8Array, never, never, never>, false>>;
21
- //#endregion
22
- //#region src/server/headers.d.ts
23
20
  /** Every answer the media server gives, and nothing else: each has its status and its headers. */
24
21
  export declare const Answer: Schema.TaggedUnion<{
25
22
  readonly Described: Schema.TaggedStruct<"Described", {}>;
@@ -38,6 +35,7 @@ export declare const Answer: Schema.TaggedUnion<{
38
35
  readonly retryAfterSeconds: Schema.Number;
39
36
  }>;
40
37
  readonly TooLarge: Schema.TaggedStruct<"TooLarge", {}>;
38
+ readonly Unauthenticated: Schema.TaggedStruct<"Unauthenticated", {}>;
41
39
  readonly Unavailable: Schema.TaggedStruct<"Unavailable", {}>;
42
40
  readonly Unoffered: Schema.TaggedStruct<"Unoffered", {}>;
43
41
  readonly Unsupported: Schema.TaggedStruct<"Unsupported", {}>;
@@ -52,15 +50,13 @@ export type Answer = typeof Answer.Type;
52
50
  export declare const statusOf: (answer: Answer) => number;
53
51
  /**
54
52
  * Every response's headers, decided in one place, so the server, the edge
55
- * and a static host cannot disagree. A variant's URL names its bytes, so it
56
- * is kept for a year. A refusal of a variant is not: another release, or the
53
+ * and a static host cannot disagree. A variant's URL names the variant, and
54
+ * 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
57
55
  * same one configured otherwise, may answer it, so only a CDN keeps it,
58
56
  * briefly; a failure is never kept. Every image may be read by a canvas on
59
57
  * another origin, and its type is never sniffed.
60
58
  */
61
59
  export declare const headersFor: (answer: Answer) => Readonly<Record<string, string>>;
62
- //#endregion
63
- //#region src/server/handlers.d.ts
64
60
  interface Options {
65
61
  /**
66
62
  * The `Provider.hosted` the pages write URLs with: the server makes every
@@ -97,8 +93,6 @@ export declare const handlers: (options?: Options) => Layer.Layer<import("effect
97
93
  * the `HttpRouter`, needing `Originals`, `Transformer` and `Variants`.
98
94
  */
99
95
  export declare const layer: (options?: Options) => Layer.Layer<never, never, import("effect/FileSystem").FileSystem | import("effect/http/Etag").Generator | import("effect/http/HttpPlatform").HttpPlatform | HttpRouter.HttpRouter | Originals | import("effect/Path").Path | Transformer | Variants>;
100
- //#endregion
101
- //#region src/server/fetch.d.ts
102
96
  /** What `serveFetch` answers, each side's services built from the request's bindings. */
103
97
  interface FetchOptions<Env> {
104
98
  /** `GET /_image/…`: the variants. A Worker request cannot wait on another's, so nothing coalesces. */
@@ -121,8 +115,6 @@ interface FetchOptions<Env> {
121
115
  * to build answers a 500.
122
116
  */
123
117
  export declare const serveFetch: <Env extends object>(options: FetchOptions<Env>) => ((request: Request, env: Env) => Promise<Response>);
124
- //#endregion
125
- //#region src/server/stores.d.ts
126
118
  /**
127
119
  * Variants kept in the application's `KeyValueStore`, under `prefix`:
128
120
  * `KeyValueStore.layerMemory` for tests, `layerFileSystem` on a disk,
@@ -139,8 +131,6 @@ export declare const variantsKeyValueStore: (options?: {
139
131
  export declare const originalsKeyValueStore: (options?: {
140
132
  readonly prefix?: string;
141
133
  }) => Layer.Layer<Originals, never, KeyValueStore.KeyValueStore>;
142
- //#endregion
143
- //#region src/server/materialize.d.ts
144
134
  /** A variant written out as a file, at its own URL's path. */
145
135
  interface Materialized {
146
136
  readonly file: string;
@@ -176,6 +166,5 @@ export declare const materialize: (options: {
176
166
  /** Variants made at once. */
177
167
  readonly concurrency?: number;
178
168
  }) => Promise<ReadonlyArray<Materialized>>;
179
- //#endregion
180
- export { Admission, type Encoded, type FactsOptions, FactsUnavailable, type FetchOptions, type Kept, type Materialized, type Options, type Original, OriginalNotFound, OriginalTooLarge, Originals, QuotaExhausted, RateLimited, TransformFailed, Transformer, UploadApi, UploadForbidden, type UploadOptions, UploadPolicy, Uploads, Variants, admissionRateLimiter, factsOf, limitTransforms, uploadHandlers, uploadLayer, uploadPolicyBearer, uploadsKeyValueStore, variantsNone };
169
+ export { Admission, type Encoded, type FactsOptions, FactsUnavailable, type FetchOptions, type Kept, type Materialized, type Options, type Original, OriginalNotFound, OriginalTooLarge, Originals, QuotaExhausted, RateLimited, StoredFacts, TransformFailed, Transformer, UploadApi, UploadForbidden, type UploadOptions, UploadPolicy, type UploadRoute, UploadUnauthenticated, Uploads, Variants, admissionRateLimiter, factsOf, limitTransforms, storedFactsKeyValueStore, uploadHandlers, uploadLayer, uploadPolicyAny, uploadPolicyBearer, uploadsKeyValueStore, variantsNone };
181
170
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/server/api.ts","../../src/server/headers.ts","../../src/server/handlers.ts","../../src/server/fetch.ts","../../src/server/stores.ts","../../src/server/materialize.ts"],"mappings":";;;;;;;;;;;;;;;;qBAWa,UAAQ,QAAA,yBAAA,aAAA,uBAAA,gBAAA,4DAAA,OAAA,kBAAA,OAAA;;;0BAOpB,cAAA;;;;qBCXY,QAAM,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;YA0CP,gBAAgB,OAAO;;qBActB,WAAW,QAAQ;;;;;;;;;qBA0BnB,aAAU,QAAY,WAAS,SAAS;;;UC1EpC;;;;;WAKN,WAAW;;WAEX;;;;;;;WAOA;;;;;;WAMA,YAAY,SAAS,kBAAkB;;;;;;;;;;qBA6BrC,WAAQ,UAAa,YAAO,MAAA,6CAAA,2CAAA,YAAA,cAAA;;;;;qBA4H5B,QAAK,UAAa,YAAO,MAAA,gDAAA,wCAAA,+CAAA,eAAA,WAAA,aAAA,kCAAA,OAAA,cAAA;;;;UCjLrB,aAAa;;WAEnB,SAAS,KAAK;aACZ,QAAQ,KAAK,QAAQ,MAAM,MAAM,YAAY,cAAc;;;WAG7D,UAAU;aACR,QAAQ,KAAK,QAAQ,MAAM,MAAM,UAAU,YAAY;;;WAGzD,aAAa,SAAS,SAAS,KAAK,QAAQ,QAAQ;;;;;;;;;;qBAWlD,aAAc,oBAAkB,SAClC,aAAa,WACnB,SAAS,SAAS,KAAK,QAAQ,QAAQ;;;;;;;;qBCY/B,wBAAqB;WACZ;MACnB,MAAM,MAAM,iBAAiB,cAAc;;;;;;qBAcjC,yBAAsB;WACb;MACnB,MAAM,MAAM,kBAAkB,cAAc;;;;UC5D9B;WACN;WACA,UAAU;;;;;;;qBAgBR;;;;;;;;;;;;;qBAoBA,cAAW;WACb,OAAO;aAAyB;;WAChC,QAAQ,SAAS,YAAY,QAAQ;;WAErC;;WAEA;;WAEA;MACP,QAAQ,cAAc"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/server/api.ts","../../src/server/headers.ts","../../src/server/handlers.ts","../../src/server/fetch.ts","../../src/server/stores.ts","../../src/server/materialize.ts"],"mappings":";;;;;;;;;;;;;;;qBAWa,UAAQ,QAAA,yBAAA,aAAA,uBAAA,gBAAA,4DAAA,OAAA,kBAAA,OAAA;;;0BAOpB,cAAA;;qBCXY,QAAM,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;YA4CP,gBAAgB,OAAO;;qBActB,WAAW,QAAQ;;;;;;;;;qBA2BnB,aAAU,QAAY,WAAS,SAAS;UC7EpC;;;;;WAKN,WAAW;;WAEX;;;;;;;WAOA;;;;;;WAMA,YAAY,SAAS,kBAAkB;;;;;;;;;;qBA6BrC,WAAQ,UAAa,YAAO,MAAA,6CAAA,2CAAA,YAAA,cAAA;;;;;qBA4H5B,QAAK,UAAa,YAAO,MAAA,gDAAA,wCAAA,+CAAA,eAAA,WAAA,aAAA,kCAAA,OAAA,cAAA;;UCjLrB,aAAa;;WAEnB,SAAS,KAAK;aACZ,QAAQ,KAAK,QAAQ,MAAM,MAAM,YAAY,cAAc;;;WAG7D,UAAU;aACR,QAAQ,KAAK,QAAQ,MAAM,MAAM,UAAU,YAAY;;;WAGzD,aAAa,SAAS,SAAS,KAAK,QAAQ,QAAQ;;;;;;;;;;qBAWlD,aAAc,oBAAkB,SAClC,aAAa,WACnB,SAAS,SAAS,KAAK,QAAQ,QAAQ;;;;;;qBCY/B,wBAAqB;WACZ;MACnB,MAAM,MAAM,iBAAiB,cAAc;;;;;;qBAcjC,yBAAsB;WACb;MACnB,MAAM,MAAM,kBAAkB,cAAc;;UC5D9B;WACN;WACA,UAAU;;;;;;;qBAgBR;;;;;;;;;;;;;qBAoBA,cAAW;WACb,OAAO;aAAyB;;WAChC,QAAQ,SAAS,YAAY,QAAQ;;WAErC;;WAEA;;WAEA;MACP,QAAQ,cAAc"}
@@ -1,12 +1,12 @@
1
- import { c as ContentHash, d as Spelling, f as respell, l as PATH, m as standard, p as revisionOf } from "../describe-h9F5stgR.mjs";
2
- import { n as positiveInteger, t as nonNegativeInteger } from "../limits-B6C9OOLl.mjs";
3
- import { i as TransformFailed, n as OriginalTooLarge, r as QuotaExhausted, t as OriginalNotFound } from "../errors-qETj7Pgi.mjs";
4
- import { _ as Answer, a as UploadForbidden, b as statusOf, c as uploadHandlers, d as uploadsKeyValueStore, f as FactsUnavailable, g as admissionRateLimiter, h as RateLimited, i as UploadApi, l as uploadLayer, m as Admission, n as originalsKeyValueStore, o as UploadPolicy, p as factsOf, r as variantsKeyValueStore, s as Uploads, u as uploadPolicyBearer, v as headersFor, y as matches } from "../stores-BtmSl8X3.mjs";
5
- import { a as variantsNone, i as limitTransforms, n as Transformer, r as Variants, t as Originals } from "../services-BeakQl7F.mjs";
1
+ import { c as ContentHash, d as Spelling, f as respell, l as PATH, m as standard, p as revisionOf } from "../describe-C6sWA_8p.mjs";
2
+ import { n as positiveInteger, t as nonNegativeInteger } from "../limits-B4hHpyfE.mjs";
3
+ import { i as TransformFailed, n as OriginalTooLarge, r as QuotaExhausted, t as OriginalNotFound } from "../errors-BhEgXJ4m.mjs";
4
+ import { C as admissionRateLimiter, D as statusOf, E as matches, S as RateLimited, T as headersFor, _ as uploadPolicyBearer, a as UploadApi, b as factsOf, c as UploadUnauthenticated, g as uploadPolicyAny, h as uploadLayer, i as StoredFacts, l as Uploads, m as uploadHandlers, n as originalsKeyValueStore, o as UploadForbidden, p as storedFactsKeyValueStore, r as variantsKeyValueStore, s as UploadPolicy, v as uploadsKeyValueStore, w as Answer, x as Admission, y as FactsUnavailable } from "../stores-CxraN3kt.mjs";
5
+ import { a as variantsNone, i as limitTransforms, n as Transformer, r as Variants, t as Originals } from "../services-7B4hsQM7.mjs";
6
6
  import { Cache, Effect, Layer, Option, Schema } from "effect";
7
7
  import { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiGroup, HttpApiSchema } from "effect/http-api";
8
8
  import { HttpRouter, HttpServer, HttpServerResponse } from "effect/http";
9
- //#region src/server/api.ts
9
+ // src/server/api.ts
10
10
  /**
11
11
  * The media server's HTTP API: one route, a variant of an original named by
12
12
  * its content hash. The route takes its params as text, and the handler
@@ -21,8 +21,7 @@ const MediaApi = HttpApi.make("foldkit-media").add(HttpApiGroup.make("images").a
21
21
  },
22
22
  success: HttpApiSchema.StreamUint8Array()
23
23
  })));
24
- //#endregion
25
- //#region src/server/handlers.ts
24
+ // src/server/handlers.ts
26
25
  /** The Cloudflare Images binding reads at most 20 MB; a store's own limit may be lower. */
27
26
  const DEFAULT_MAX_BYTES = 20971520;
28
27
  const defaultClientOf = (request) => request.headers["cf-connecting-ip"] ?? Option.getOrElse(request.remoteAddress, () => "unknown");
@@ -146,8 +145,7 @@ const fetchOf = (app) => {
146
145
  return answer(request);
147
146
  };
148
147
  };
149
- //#endregion
150
- //#region src/server/fetch.ts
148
+ // src/server/fetch.ts
151
149
  const IMAGES = PATH.slice(0, PATH.indexOf(":"));
152
150
  const UPLOADS = "/_media/";
153
151
  /**
@@ -171,8 +169,7 @@ const serveFetch = (options) => {
171
169
  return otherwise === void 0 ? Promise.resolve(new Response(null, { status: 404 })) : otherwise(request, env);
172
170
  };
173
171
  };
174
- //#endregion
175
- //#region src/server/materialize.ts
172
+ // src/server/materialize.ts
176
173
  const VARIANT_PATH = /\/_image\/[0-9a-f]{64}\/[^\s"',)<>]+/g;
177
174
  const DEFAULT_MAX_FILES = 2e4;
178
175
  const PATTERN = "/_image/*";
@@ -225,11 +222,10 @@ const materialize = async (options) => {
225
222
  failed.push(`${path}: ${cause instanceof Error ? cause.message : String(cause)}`);
226
223
  }
227
224
  };
228
- await Promise.all(Array.from({ length: concurrency }, worker));
225
+ await Promise.all(Array.from({ length: Math.min(concurrency, paths.length) }, worker));
229
226
  if (failed.length > 0) throw new Error(`foldkit-media: ${failed.length} variants could not be made:\n${failed.sort().join("\n")}`);
230
227
  return made.sort((a, b) => a.file < b.file ? -1 : a.file > b.file ? 1 : 0);
231
228
  };
232
- //#endregion
233
- export { Admission, Answer, FactsUnavailable, MediaApi, OriginalNotFound, OriginalTooLarge, Originals, QuotaExhausted, RateLimited, TransformFailed, Transformer, UploadApi, UploadForbidden, UploadPolicy, Uploads, Variants, admissionRateLimiter, factsOf, handlers, headersFor, headersRule, layer, limitTransforms, materialize, originalsKeyValueStore, serveFetch, statusOf, uploadHandlers, uploadLayer, uploadPolicyBearer, uploadsKeyValueStore, variantsKeyValueStore, variantsNone };
229
+ export { Admission, Answer, FactsUnavailable, MediaApi, OriginalNotFound, OriginalTooLarge, Originals, QuotaExhausted, RateLimited, StoredFacts, TransformFailed, Transformer, UploadApi, UploadForbidden, UploadPolicy, UploadUnauthenticated, Uploads, Variants, admissionRateLimiter, factsOf, handlers, headersFor, headersRule, layer, limitTransforms, materialize, originalsKeyValueStore, serveFetch, statusOf, storedFactsKeyValueStore, uploadHandlers, uploadLayer, uploadPolicyAny, uploadPolicyBearer, uploadsKeyValueStore, variantsKeyValueStore, variantsNone };
234
230
 
235
231
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["Variant.PATH","Variant.standard","Variant.ContentHash","Variant.Spelling","Variant.respell","Variant.revisionOf"],"sources":["../../src/server/api.ts","../../src/server/handlers.ts","../../src/server/fetch.ts","../../src/server/materialize.ts"],"sourcesContent":["import { Schema } from 'effect'\nimport { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiSchema } from 'effect/http-api'\nimport * as Variant from '../variant.js'\n\n/**\n * The media server's HTTP API: one route, a variant of an original named by\n * its content hash. The route takes its params as text, and the handler\n * decodes them with the space's Schema, the one `Provider.hosted` encodes\n * with, so a variant outside the space is refused before any work, and that\n * refusal, like every answer, carries the headers `headersFor` decides.\n */\nexport const MediaApi = HttpApi.make('foldkit-media').add(\n HttpApiGroup.make('images').add(\n HttpApiEndpoint.get('variant', Variant.PATH, {\n params: { hash: Schema.String, variant: Schema.String },\n success: HttpApiSchema.StreamUint8Array(),\n }),\n ),\n)\n","import { Cache, Effect, Layer, Option, Schema } from 'effect'\nimport { HttpRouter, HttpServer, HttpServerResponse, type HttpServerRequest } from 'effect/http'\nimport { HttpApiBuilder } from 'effect/http-api'\nimport type { Hosted } from '../provider.js'\nimport * as Variant from '../variant.js'\nimport { nonNegativeInteger } from '../limits.js'\nimport { MediaApi } from './api.js'\nimport { Admission } from './admission.js'\nimport { OriginalTooLarge } from './errors.js'\nimport { Answer, headersFor, matches, statusOf, type From } from './headers.js'\nimport { Originals, Transformer, Variants, type Encoded } from './services.js'\n\n/** The Cloudflare Images binding reads at most 20 MB; a store's own limit may be lower. */\nconst DEFAULT_MAX_BYTES = 20 * 1024 * 1024\n\nexport interface Options {\n /**\n * The `Provider.hosted` the pages write URLs with: the server makes every\n * variant of its space and nothing else. `Provider.hosted()` when omitted.\n */\n readonly provider?: Hosted\n /** The largest original read, in bytes; larger ones are a 413. */\n readonly maxBytes?: number\n /**\n * Concurrent misses for one variant share one transform and one write.\n * Only where requests may wait on one another's work: on by default for\n * `layer` (a Node server), off in `serveFetch`, since a Worker request\n * cannot wake another's.\n */\n readonly coalesce?: boolean\n /**\n * Who is asking, for `Admission`: by default Cloudflare's `CF-Connecting-IP`,\n * else the connection's address. `X-Forwarded-For` is the client's to write,\n * so read it here only behind a proxy that sets it.\n */\n readonly clientOf?: (request: HttpServerRequest.HttpServerRequest) => string\n}\n\nconst defaultClientOf = (request: HttpServerRequest.HttpServerRequest): string =>\n request.headers['cf-connecting-ip'] ?? Option.getOrElse(request.remoteAddress, () => 'unknown')\n\nconst optionsOf = (answer: Answer) => ({ status: statusOf(answer), headers: headersFor(answer) })\n\nconst served = (etag: string, from: From, encoded: Encoded) =>\n HttpServerResponse.uint8Array(encoded.bytes, {\n ...optionsOf(Answer.cases.Variant.make({ etag, from })),\n contentType: encoded.contentType,\n })\n\nconst notModified = (etag: string) =>\n HttpServerResponse.empty(optionsOf(Answer.cases.NotModified.make({ etag })))\n\n// A refusal names its kind, and nothing of the server's internals.\nconst refused = (answer: Answer) =>\n HttpServerResponse.jsonUnsafe({ error: answer._tag }, optionsOf(answer))\n\n/**\n * The handlers of `MediaApi`'s one route. The path is decoded against the\n * space; a variant kept is served as kept, and one the request already holds\n * (`If-None-Match`) is a 304 before the store is read; otherwise the original\n * is read, transformed, kept and served. Every answer, a refusal included,\n * goes through `headersFor`, and a failure is never the original in the\n * variant's place.\n */\nexport const handlers = (options: Options = {}) => {\n const {\n maxBytes: requestedMaxBytes = DEFAULT_MAX_BYTES,\n coalesce = false,\n clientOf = defaultClientOf,\n } = options\n const space = options.provider?.space ?? Variant.standard\n const maxBytes = nonNegativeInteger('maxBytes', requestedMaxBytes)\n const decodeHash = Schema.decodeUnknownOption(Variant.ContentHash)\n const decodeVariant = Schema.decodeUnknownOption(space.schema)\n const isSpelling = Schema.is(Variant.Spelling)\n const spell = Schema.encodeSync(space.schema)\n return HttpApiBuilder.group(MediaApi, 'images', group =>\n Effect.gen(function* () {\n // Resolved once, when the route is built, so a store kept in memory lives as long as the server.\n const originals = yield* Originals\n const transformer = yield* Transformer\n const variants = yield* Variants\n const admit = Option.match(yield* Effect.serviceOption(Admission), {\n onNone: () => (_client: string) => Effect.void,\n onSome: admission => admission.admit,\n })\n const make = Effect.fn('Media.make')(function* (hash: string, variant: Variant.Variant) {\n const original = yield* originals.get(hash)\n if (original.size > maxBytes) {\n return yield* new OriginalTooLarge({\n size: original.size,\n limit: maxBytes,\n unit: 'bytes',\n })\n }\n return yield* transformer.transform(original, variant)\n })\n const makeAndKeep = (key: string, hash: string, variant: Variant.Variant) =>\n make(hash, variant).pipe(Effect.tap(made => variants.put(key, made)))\n // In flight only: an entry expires as it settles, so nothing is kept here and no failure is remembered.\n const shared = yield* Cache.make({\n capacity: 10_000,\n timeToLive: 0,\n lookup: (key: string) => {\n // The key is the hash, a slash, and the spelling: neither holds a slash of its own.\n const at = key.indexOf('/')\n const variant = Schema.decodeUnknownSync(space.schema)(key.slice(at + 1))\n return makeAndKeep(key, key.slice(0, at), variant)\n },\n })\n const serve = Effect.fn('Media.serve')(function* (\n hash: string,\n variant: Variant.Variant,\n ifNoneMatch: string | undefined,\n client: string,\n ) {\n // The decoded request spelled again: one request, one key, one ETag.\n const key = `${hash}/${spell(variant)}`\n const etag = `\"${key}\"`\n if (matches(ifNoneMatch, etag)) return notModified(etag)\n return yield* Option.match(yield* variants.get(key), {\n onSome: ({ encoded, from }) => Effect.succeed(served(etag, from, encoded)),\n onNone: () =>\n admit(client).pipe(\n Effect.andThen(coalesce ? Cache.get(shared, key) : makeAndKeep(key, hash, variant)),\n Effect.map(made => served(etag, 'made', made)),\n Effect.catchTags({\n OriginalNotFound: () => Effect.succeed(refused(Answer.cases.NotFound.make({}))),\n OriginalTooLarge: () => Effect.succeed(refused(Answer.cases.TooLarge.make({}))),\n TransformFailed: () => Effect.succeed(refused(Answer.cases.Failed.make({}))),\n QuotaExhausted: () => Effect.succeed(refused(Answer.cases.Exhausted.make({}))),\n RateLimited: ({ retryAfterSeconds }) =>\n Effect.succeed(refused(Answer.cases.RateLimited.make({ retryAfterSeconds }))),\n }),\n ),\n })\n })\n /**\n * A spelling of the grammar this space does not read. An earlier revision of a variant\n * it makes is served while kept and else sent to its current URL; anything else (a later\n * revision, a width another release offers) is `Unoffered`, kept briefly.\n */\n const elsewhere = (hash: string, spelling: string, ifNoneMatch: string | undefined) => {\n const current = Variant.respell(spelling, space.revision)\n if (\n Variant.revisionOf(spelling) >= space.revision ||\n Option.isNone(decodeVariant(current))\n ) {\n return Effect.succeed(refused(Answer.cases.Unoffered.make({})))\n }\n const key = `${hash}/${spelling}`\n const etag = `\"${key}\"`\n if (matches(ifNoneMatch, etag)) return Effect.succeed(notModified(etag))\n return Effect.map(variants.get(key), kept =>\n Option.match(kept, {\n onSome: ({ encoded, from }) => served(etag, from, encoded),\n onNone: () =>\n refused(\n Answer.cases.Moved.make({\n location: Variant.PATH.replace(':hash', hash).replace(':variant', current),\n }),\n ),\n }),\n )\n }\n return group.handle('variant', ({ params, request }) =>\n Option.match(Option.all([decodeHash(params.hash), decodeVariant(params.variant)]), {\n // Kept a year only when no release could spell it; anything else is answered above.\n onNone: () =>\n Option.match(decodeHash(params.hash), {\n onNone: () => Effect.succeed(refused(Answer.cases.Malformed.make({}))),\n onSome: hash =>\n isSpelling(params.variant)\n ? elsewhere(hash, params.variant, request.headers['if-none-match'])\n : Effect.succeed(refused(Answer.cases.Malformed.make({}))),\n }),\n onSome: ([hash, variant]) =>\n serve(hash, variant, request.headers['if-none-match'], clientOf(request)),\n }),\n )\n }),\n )\n}\n\n/**\n * The media server as an Effect HTTP application: its route registered with\n * the `HttpRouter`, needing `Originals`, `Transformer` and `Variants`.\n */\nexport const layer = (options: Options = {}) =>\n HttpApiBuilder.layer(MediaApi).pipe(Layer.provide(handlers({ coalesce: true, ...options })))\n\n/**\n * A Worker's fetch handler over `app`, built from each environment's bindings\n * once and kept, since a Worker hands every request the same bindings. A\n * layer that fails to build answers a 500.\n */\nexport const fetchOf = <Env extends object>(\n app: (\n env: Env,\n ) => Layer.Layer<\n never,\n unknown,\n HttpRouter.HttpRouter | Layer.Success<typeof HttpServer.layerServices>\n >,\n): ((request: Request, env: Env) => Promise<Response>) => {\n const built = new WeakMap<Env, (request: Request) => Promise<Response>>()\n return (request, env) => {\n const known = built.get(env)\n if (known !== undefined) return known(request)\n const { handler } = HttpRouter.toWebHandler(\n app(env).pipe(Layer.provide(HttpServer.layerServices)),\n { disableLogger: true },\n )\n const answer = (incoming: Request) => handler(incoming)\n built.set(env, answer)\n return answer(request)\n }\n}\n","import { Layer } from 'effect'\nimport type { Inspector } from '../describe.js'\nimport * as Variant from '../variant.js'\nimport { fetchOf, layer, type Options } from './handlers.js'\nimport type { Originals, Transformer, Variants } from './services.js'\nimport { uploadLayer, type UploadOptions, type UploadPolicy, type Uploads } from './upload.js'\n\nconst IMAGES = Variant.PATH.slice(0, Variant.PATH.indexOf(':'))\nconst UPLOADS = '/_media/'\n\n/** What `serveFetch` answers, each side's services built from the request's bindings. */\nexport interface FetchOptions<Env> {\n /** `GET /_image/…`: the variants. A Worker request cannot wait on another's, so nothing coalesces. */\n readonly images?: Omit<Options, 'coalesce'> & {\n readonly layer: (env: Env) => Layer.Layer<Originals | Transformer | Variants, unknown>\n }\n /** `POST /_media/upload` and `GET /_media/facts`: originals entering. */\n readonly uploads?: UploadOptions & {\n readonly layer: (env: Env) => Layer.Layer<Uploads | Inspector | UploadPolicy, unknown>\n }\n /** Every path outside `/_image/` and `/_media/`: the application's own routes. A 404 when omitted. */\n readonly otherwise?: (request: Request, env: Env) => Promise<Response>\n}\n\n/**\n * The media server as a Worker's fetch handler. It owns `/_image/` and\n * `/_media/`: a route of either it was not given, another method (a\n * preflight, which the upload route never answers), or another path under\n * them is a 404, and everything else goes to `otherwise`. The services are\n * built from each environment's bindings once and kept; a layer that fails\n * to build answers a 500.\n */\nexport const serveFetch = <Env extends object>(\n options: FetchOptions<Env>,\n): ((request: Request, env: Env) => Promise<Response>) => {\n const { images, uploads, otherwise } = options\n if (images === undefined && uploads === undefined) {\n throw new Error('serveFetch: give it `images`, `uploads`, or both')\n }\n const media = fetchOf<Env>(env =>\n Layer.mergeAll(\n images === undefined\n ? Layer.empty\n : layer({ ...images, coalesce: false }).pipe(Layer.provide(images.layer(env))),\n uploads === undefined\n ? Layer.empty\n : uploadLayer(uploads).pipe(Layer.provide(uploads.layer(env))),\n ),\n )\n return (request, env) => {\n const { pathname } = new URL(request.url)\n if (pathname.startsWith(IMAGES) || pathname.startsWith(UPLOADS)) return media(request, env)\n return otherwise === undefined\n ? Promise.resolve(new Response(null, { status: 404 }))\n : otherwise(request, env)\n }\n}\n","import { nonNegativeInteger, positiveInteger } from '../limits.js'\nimport { Answer, headersFor } from './headers.js'\n\n/** A variant written out as a file, at its own URL's path. */\nexport interface Materialized {\n readonly file: string\n readonly contents: Uint8Array\n}\n\n// A hosted variant's path, wherever a page names one: in a `srcset`, a `src`, a preload.\nconst VARIANT_PATH = /\\/_image\\/[0-9a-f]{64}\\/[^\\s\"',)<>]+/g\n\n// Cloudflare Pages serves at most 20,000 files a site on its free plan.\nconst DEFAULT_MAX_FILES = 20_000\n\nconst PATTERN = '/_image/*'\n\n/**\n * The `_headers` rule (Cloudflare Pages, Netlify) a host needs for variants\n * written out as files: what the server itself sends a variant, from the same\n * `headersFor`, less the `ETag` and `Server-Timing` of one answer.\n */\nexport const headersRule = (): string => {\n const headers = headersFor(Answer.cases.Variant.make({ etag: '', from: 'made' }))\n const lines = Object.entries(headers)\n .filter(([name]) => name !== 'etag' && name !== 'server-timing')\n .map(([name, value]) => ` ${name}: ${value}`)\n return [PATTERN, ...lines].join('\\n') + '\\n'\n}\n\n/**\n * Every hosted variant the built pages name, made through `fetch` (the media\n * server's own handler, `serveFetch`) and returned as files at their own\n * paths, for `foldkit-ssr`'s `emit`. `Provider.hosted` then works on a static\n * host with no server at all. With a `Variants` store on disk, a second build\n * writes without encoding.\n *\n * It fails the build, naming every one, when a variant cannot be made (a\n * page would show a broken image), when there would be more than `maxFiles`,\n * and, given the site's `_headers` text, when that file has no rule for the\n * variants, which a static host would otherwise serve uncached.\n */\nexport const materialize = async (options: {\n readonly pages: ReadonlyArray<{ readonly html: string }>\n readonly fetch: (request: Request) => Promise<Response>\n /** The most files to write. */\n readonly maxFiles?: number\n /** The site's `_headers` text, to check it has `headersRule()`'s pattern. */\n readonly headersFile?: string\n /** Variants made at once. */\n readonly concurrency?: number\n}): Promise<ReadonlyArray<Materialized>> => {\n const paths = [\n ...new Set(options.pages.flatMap(page => page.html.match(VARIANT_PATH) ?? [])),\n ].sort()\n const maxFiles = nonNegativeInteger('maxFiles', options.maxFiles ?? DEFAULT_MAX_FILES)\n const concurrency = positiveInteger(\n 'foldkit-media: materialize concurrency',\n options.concurrency ?? 4,\n )\n if (paths.length > maxFiles) {\n throw new Error(\n `foldkit-media: the pages name ${paths.length} variants, more than maxFiles (${maxFiles})`,\n )\n }\n if (\n paths.length > 0 &&\n options.headersFile !== undefined &&\n !options.headersFile.split(/\\r?\\n/).some(line => line.trim() === PATTERN)\n ) {\n throw new Error(\n `foldkit-media: _headers has no ${PATTERN} rule, so the variants would be served uncached: add Media.headersRule()`,\n )\n }\n const made: Array<Materialized> = []\n const failed: Array<string> = []\n const queue = [...paths]\n const worker = async () => {\n for (let path = queue.shift(); path !== undefined; path = queue.shift()) {\n try {\n const response = await options.fetch(new Request(`http://materialize.invalid${path}`))\n if (response.status !== 200) {\n failed.push(`${path}: ${response.status}`)\n continue\n }\n made.push({ file: path.slice(1), contents: new Uint8Array(await response.arrayBuffer()) })\n } catch (cause) {\n failed.push(`${path}: ${cause instanceof Error ? cause.message : String(cause)}`)\n }\n }\n }\n await Promise.all(Array.from({ length: concurrency }, worker))\n if (failed.length > 0) {\n throw new Error(\n `foldkit-media: ${failed.length} variants could not be made:\\n${failed.sort().join('\\n')}`,\n )\n }\n return made.sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : 0))\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAWA,MAAa,WAAW,QAAQ,KAAK,eAAe,CAAC,CAAC,IACpD,aAAa,KAAK,QAAQ,CAAC,CAAC,IAC1B,gBAAgB,IAAI,WAAWA,MAAc;CAC3C,QAAQ;EAAE,MAAM,OAAO;EAAQ,SAAS,OAAO;CAAO;CACtD,SAAS,cAAc,iBAAiB;AAC1C,CAAC,CACH,CACF;;;;ACLA,MAAM,oBAAoB;AAyB1B,MAAM,mBAAmB,YACvB,QAAQ,QAAQ,uBAAuB,OAAO,UAAU,QAAQ,qBAAqB,SAAS;AAEhG,MAAM,aAAa,YAAoB;CAAE,QAAQ,SAAS,MAAM;CAAG,SAAS,WAAW,MAAM;AAAE;AAE/F,MAAM,UAAU,MAAc,MAAY,YACxC,mBAAmB,WAAW,QAAQ,OAAO;CAC3C,GAAG,UAAU,OAAO,MAAM,QAAQ,KAAK;EAAE;EAAM;CAAK,CAAC,CAAC;CACtD,aAAa,QAAQ;AACvB,CAAC;AAEH,MAAM,eAAe,SACnB,mBAAmB,MAAM,UAAU,OAAO,MAAM,YAAY,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;AAG7E,MAAM,WAAW,WACf,mBAAmB,WAAW,EAAE,OAAO,OAAO,KAAK,GAAG,UAAU,MAAM,CAAC;;;;;;;;;AAUzE,MAAa,YAAY,UAAmB,CAAC,MAAM;CACjD,MAAM,EACJ,UAAU,oBAAoB,mBAC9B,WAAW,OACX,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Q;IACzC;GACF;GACA,KAAK,KAAK;IAAE,MAAM,KAAK,MAAM,CAAC;IAAG,UAAU,IAAI,WAAW,MAAM,SAAS,YAAY,CAAC;GAAE,CAAC;EAC3F,SAAS,OAAO;GACd,OAAO,KAAK,GAAG,KAAK,IAAI,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG;EAClF;CAEJ;CACA,MAAM,QAAQ,IAAI,MAAM,KAAK,EAAE,QAAQ,YAAY,GAAG,MAAM,CAAC;CAC7D,IAAI,OAAO,SAAS,GAClB,MAAM,IAAI,MACR,kBAAkB,OAAO,OAAO,gCAAgC,OAAO,KAAK,CAAC,CAAC,KAAK,IAAI,GACzF;CAEF,OAAO,KAAK,MAAM,GAAG,MAAO,EAAE,OAAO,EAAE,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,IAAI,CAAE;AAC7E"}
1
+ {"version":3,"file":"index.mjs","names":["Variant.PATH","Variant.standard","Variant.ContentHash","Variant.Spelling","Variant.respell","Variant.revisionOf"],"sources":["../../src/server/api.ts","../../src/server/handlers.ts","../../src/server/fetch.ts","../../src/server/materialize.ts"],"sourcesContent":["import { Schema } from 'effect'\nimport { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiSchema } from 'effect/http-api'\nimport * as Variant from '../variant.js'\n\n/**\n * The media server's HTTP API: one route, a variant of an original named by\n * its content hash. The route takes its params as text, and the handler\n * decodes them with the space's Schema, the one `Provider.hosted` encodes\n * with, so a variant outside the space is refused before any work, and that\n * refusal, like every answer, carries the headers `headersFor` decides.\n */\nexport const MediaApi = HttpApi.make('foldkit-media').add(\n HttpApiGroup.make('images').add(\n HttpApiEndpoint.get('variant', Variant.PATH, {\n params: { hash: Schema.String, variant: Schema.String },\n success: HttpApiSchema.StreamUint8Array(),\n }),\n ),\n)\n","import { Cache, Effect, Layer, Option, Schema } from 'effect'\nimport { HttpRouter, HttpServer, HttpServerResponse, type HttpServerRequest } from 'effect/http'\nimport { HttpApiBuilder } from 'effect/http-api'\nimport type { Hosted } from '../provider.js'\nimport * as Variant from '../variant.js'\nimport { nonNegativeInteger } from '../limits.js'\nimport { MediaApi } from './api.js'\nimport { Admission } from './admission.js'\nimport { OriginalTooLarge } from './errors.js'\nimport { Answer, headersFor, matches, statusOf, type From } from './headers.js'\nimport { Originals, Transformer, Variants, type Encoded } from './services.js'\n\n/** The Cloudflare Images binding reads at most 20 MB; a store's own limit may be lower. */\nconst DEFAULT_MAX_BYTES = 20 * 1024 * 1024\n\nexport interface Options {\n /**\n * The `Provider.hosted` the pages write URLs with: the server makes every\n * variant of its space and nothing else. `Provider.hosted()` when omitted.\n */\n readonly provider?: Hosted\n /** The largest original read, in bytes; larger ones are a 413. */\n readonly maxBytes?: number\n /**\n * Concurrent misses for one variant share one transform and one write.\n * Only where requests may wait on one another's work: on by default for\n * `layer` (a Node server), off in `serveFetch`, since a Worker request\n * cannot wake another's.\n */\n readonly coalesce?: boolean\n /**\n * Who is asking, for `Admission`: by default Cloudflare's `CF-Connecting-IP`,\n * else the connection's address. `X-Forwarded-For` is the client's to write,\n * so read it here only behind a proxy that sets it.\n */\n readonly clientOf?: (request: HttpServerRequest.HttpServerRequest) => string\n}\n\nconst defaultClientOf = (request: HttpServerRequest.HttpServerRequest): string =>\n request.headers['cf-connecting-ip'] ?? Option.getOrElse(request.remoteAddress, () => 'unknown')\n\nconst optionsOf = (answer: Answer) => ({ status: statusOf(answer), headers: headersFor(answer) })\n\nconst served = (etag: string, from: From, encoded: Encoded) =>\n HttpServerResponse.uint8Array(encoded.bytes, {\n ...optionsOf(Answer.cases.Variant.make({ etag, from })),\n contentType: encoded.contentType,\n })\n\nconst notModified = (etag: string) =>\n HttpServerResponse.empty(optionsOf(Answer.cases.NotModified.make({ etag })))\n\n// A refusal names its kind, and nothing of the server's internals.\nconst refused = (answer: Answer) =>\n HttpServerResponse.jsonUnsafe({ error: answer._tag }, optionsOf(answer))\n\n/**\n * The handlers of `MediaApi`'s one route. The path is decoded against the\n * space; a variant kept is served as kept, and one the request already holds\n * (`If-None-Match`) is a 304 before the store is read; otherwise the original\n * is read, transformed, kept and served. Every answer, a refusal included,\n * goes through `headersFor`, and a failure is never the original in the\n * variant's place.\n */\nexport const handlers = (options: Options = {}) => {\n const {\n maxBytes: requestedMaxBytes = DEFAULT_MAX_BYTES,\n coalesce = false,\n clientOf = defaultClientOf,\n } = options\n const space = options.provider?.space ?? Variant.standard\n const maxBytes = nonNegativeInteger('maxBytes', requestedMaxBytes)\n const decodeHash = Schema.decodeUnknownOption(Variant.ContentHash)\n const decodeVariant = Schema.decodeUnknownOption(space.schema)\n const isSpelling = Schema.is(Variant.Spelling)\n const spell = Schema.encodeSync(space.schema)\n return HttpApiBuilder.group(MediaApi, 'images', group =>\n Effect.gen(function* () {\n // Resolved once, when the route is built, so a store kept in memory lives as long as the server.\n const originals = yield* Originals\n const transformer = yield* Transformer\n const variants = yield* Variants\n const admit = Option.match(yield* Effect.serviceOption(Admission), {\n onNone: () => (_client: string) => Effect.void,\n onSome: admission => admission.admit,\n })\n const make = Effect.fn('Media.make')(function* (hash: string, variant: Variant.Variant) {\n const original = yield* originals.get(hash)\n if (original.size > maxBytes) {\n return yield* new OriginalTooLarge({\n size: original.size,\n limit: maxBytes,\n unit: 'bytes',\n })\n }\n return yield* transformer.transform(original, variant)\n })\n const makeAndKeep = (key: string, hash: string, variant: Variant.Variant) =>\n make(hash, variant).pipe(Effect.tap(made => variants.put(key, made)))\n // In flight only: an entry expires as it settles, so nothing is kept here and no failure is remembered.\n const shared = yield* Cache.make({\n capacity: 10_000,\n timeToLive: 0,\n lookup: (key: string) => {\n // The key is the hash, a slash, and the spelling: neither holds a slash of its own.\n const at = key.indexOf('/')\n const variant = Schema.decodeUnknownSync(space.schema)(key.slice(at + 1))\n return makeAndKeep(key, key.slice(0, at), variant)\n },\n })\n const serve = Effect.fn('Media.serve')(function* (\n hash: string,\n variant: Variant.Variant,\n ifNoneMatch: string | undefined,\n client: string,\n ) {\n // The decoded request spelled again: one request, one key, one ETag.\n const key = `${hash}/${spell(variant)}`\n const etag = `\"${key}\"`\n if (matches(ifNoneMatch, etag)) return notModified(etag)\n return yield* Option.match(yield* variants.get(key), {\n onSome: ({ encoded, from }) => Effect.succeed(served(etag, from, encoded)),\n onNone: () =>\n admit(client).pipe(\n Effect.andThen(coalesce ? Cache.get(shared, key) : makeAndKeep(key, hash, variant)),\n Effect.map(made => served(etag, 'made', made)),\n Effect.catchTags({\n OriginalNotFound: () => Effect.succeed(refused(Answer.cases.NotFound.make({}))),\n OriginalTooLarge: () => Effect.succeed(refused(Answer.cases.TooLarge.make({}))),\n TransformFailed: () => Effect.succeed(refused(Answer.cases.Failed.make({}))),\n QuotaExhausted: () => Effect.succeed(refused(Answer.cases.Exhausted.make({}))),\n RateLimited: ({ retryAfterSeconds }) =>\n Effect.succeed(refused(Answer.cases.RateLimited.make({ retryAfterSeconds }))),\n }),\n ),\n })\n })\n /**\n * A spelling of the grammar this space does not read. An earlier revision of a variant\n * it makes is served while kept and else sent to its current URL; anything else (a later\n * revision, a width another release offers) is `Unoffered`, kept briefly.\n */\n const elsewhere = (hash: string, spelling: string, ifNoneMatch: string | undefined) => {\n const current = Variant.respell(spelling, space.revision)\n if (\n Variant.revisionOf(spelling) >= space.revision ||\n Option.isNone(decodeVariant(current))\n ) {\n return Effect.succeed(refused(Answer.cases.Unoffered.make({})))\n }\n const key = `${hash}/${spelling}`\n const etag = `\"${key}\"`\n if (matches(ifNoneMatch, etag)) return Effect.succeed(notModified(etag))\n return Effect.map(variants.get(key), kept =>\n Option.match(kept, {\n onSome: ({ encoded, from }) => served(etag, from, encoded),\n onNone: () =>\n refused(\n Answer.cases.Moved.make({\n location: Variant.PATH.replace(':hash', hash).replace(':variant', current),\n }),\n ),\n }),\n )\n }\n return group.handle('variant', ({ params, request }) =>\n Option.match(Option.all([decodeHash(params.hash), decodeVariant(params.variant)]), {\n // Kept a year only when no release could spell it; anything else is answered above.\n onNone: () =>\n Option.match(decodeHash(params.hash), {\n onNone: () => Effect.succeed(refused(Answer.cases.Malformed.make({}))),\n onSome: hash =>\n isSpelling(params.variant)\n ? elsewhere(hash, params.variant, request.headers['if-none-match'])\n : Effect.succeed(refused(Answer.cases.Malformed.make({}))),\n }),\n onSome: ([hash, variant]) =>\n serve(hash, variant, request.headers['if-none-match'], clientOf(request)),\n }),\n )\n }),\n )\n}\n\n/**\n * The media server as an Effect HTTP application: its route registered with\n * the `HttpRouter`, needing `Originals`, `Transformer` and `Variants`.\n */\nexport const layer = (options: Options = {}) =>\n HttpApiBuilder.layer(MediaApi).pipe(Layer.provide(handlers({ coalesce: true, ...options })))\n\n/**\n * A Worker's fetch handler over `app`, built from each environment's bindings\n * once and kept, since a Worker hands every request the same bindings. A\n * layer that fails to build answers a 500.\n */\nexport const fetchOf = <Env extends object>(\n app: (\n env: Env,\n ) => Layer.Layer<\n never,\n unknown,\n HttpRouter.HttpRouter | Layer.Success<typeof HttpServer.layerServices>\n >,\n): ((request: Request, env: Env) => Promise<Response>) => {\n const built = new WeakMap<Env, (request: Request) => Promise<Response>>()\n return (request, env) => {\n const known = built.get(env)\n if (known !== undefined) return known(request)\n const { handler } = HttpRouter.toWebHandler(\n app(env).pipe(Layer.provide(HttpServer.layerServices)),\n { disableLogger: true },\n )\n const answer = (incoming: Request) => handler(incoming)\n built.set(env, answer)\n return answer(request)\n }\n}\n","import { Layer } from 'effect'\nimport type { Inspector } from '../describe.js'\nimport * as Variant from '../variant.js'\nimport { fetchOf, layer, type Options } from './handlers.js'\nimport type { Originals, Transformer, Variants } from './services.js'\nimport { uploadLayer, type UploadOptions, type UploadPolicy, type Uploads } from './upload.js'\n\nconst IMAGES = Variant.PATH.slice(0, Variant.PATH.indexOf(':'))\nconst UPLOADS = '/_media/'\n\n/** What `serveFetch` answers, each side's services built from the request's bindings. */\nexport interface FetchOptions<Env> {\n /** `GET /_image/…`: the variants. A Worker request cannot wait on another's, so nothing coalesces. */\n readonly images?: Omit<Options, 'coalesce'> & {\n readonly layer: (env: Env) => Layer.Layer<Originals | Transformer | Variants, unknown>\n }\n /** `POST /_media/upload` and `GET /_media/facts`: originals entering. */\n readonly uploads?: UploadOptions & {\n readonly layer: (env: Env) => Layer.Layer<Uploads | Inspector | UploadPolicy, unknown>\n }\n /** Every path outside `/_image/` and `/_media/`: the application's own routes. A 404 when omitted. */\n readonly otherwise?: (request: Request, env: Env) => Promise<Response>\n}\n\n/**\n * The media server as a Worker's fetch handler. It owns `/_image/` and\n * `/_media/`: a route of either it was not given, another method (a\n * preflight, which the upload route never answers), or another path under\n * them is a 404, and everything else goes to `otherwise`. The services are\n * built from each environment's bindings once and kept; a layer that fails\n * to build answers a 500.\n */\nexport const serveFetch = <Env extends object>(\n options: FetchOptions<Env>,\n): ((request: Request, env: Env) => Promise<Response>) => {\n const { images, uploads, otherwise } = options\n if (images === undefined && uploads === undefined) {\n throw new Error('serveFetch: give it `images`, `uploads`, or both')\n }\n const media = fetchOf<Env>(env =>\n Layer.mergeAll(\n images === undefined\n ? Layer.empty\n : layer({ ...images, coalesce: false }).pipe(Layer.provide(images.layer(env))),\n uploads === undefined\n ? Layer.empty\n : uploadLayer(uploads).pipe(Layer.provide(uploads.layer(env))),\n ),\n )\n return (request, env) => {\n const { pathname } = new URL(request.url)\n if (pathname.startsWith(IMAGES) || pathname.startsWith(UPLOADS)) return media(request, env)\n return otherwise === undefined\n ? Promise.resolve(new Response(null, { status: 404 }))\n : otherwise(request, env)\n }\n}\n","import { nonNegativeInteger, positiveInteger } from '../limits.js'\nimport { Answer, headersFor } from './headers.js'\n\n/** A variant written out as a file, at its own URL's path. */\nexport interface Materialized {\n readonly file: string\n readonly contents: Uint8Array\n}\n\n// A hosted variant's path, wherever a page names one: in a `srcset`, a `src`, a preload.\nconst VARIANT_PATH = /\\/_image\\/[0-9a-f]{64}\\/[^\\s\"',)<>]+/g\n\n// Cloudflare Pages serves at most 20,000 files a site on its free plan.\nconst DEFAULT_MAX_FILES = 20_000\n\nconst PATTERN = '/_image/*'\n\n/**\n * The `_headers` rule (Cloudflare Pages, Netlify) a host needs for variants\n * written out as files: what the server itself sends a variant, from the same\n * `headersFor`, less the `ETag` and `Server-Timing` of one answer.\n */\nexport const headersRule = (): string => {\n const headers = headersFor(Answer.cases.Variant.make({ etag: '', from: 'made' }))\n const lines = Object.entries(headers)\n .filter(([name]) => name !== 'etag' && name !== 'server-timing')\n .map(([name, value]) => ` ${name}: ${value}`)\n return [PATTERN, ...lines].join('\\n') + '\\n'\n}\n\n/**\n * Every hosted variant the built pages name, made through `fetch` (the media\n * server's own handler, `serveFetch`) and returned as files at their own\n * paths, for `foldkit-ssr`'s `emit`. `Provider.hosted` then works on a static\n * host with no server at all. With a `Variants` store on disk, a second build\n * writes without encoding.\n *\n * It fails the build, naming every one, when a variant cannot be made (a\n * page would show a broken image), when there would be more than `maxFiles`,\n * and, given the site's `_headers` text, when that file has no rule for the\n * variants, which a static host would otherwise serve uncached.\n */\nexport const materialize = async (options: {\n readonly pages: ReadonlyArray<{ readonly html: string }>\n readonly fetch: (request: Request) => Promise<Response>\n /** The most files to write. */\n readonly maxFiles?: number\n /** The site's `_headers` text, to check it has `headersRule()`'s pattern. */\n readonly headersFile?: string\n /** Variants made at once. */\n readonly concurrency?: number\n}): Promise<ReadonlyArray<Materialized>> => {\n const paths = [\n ...new Set(options.pages.flatMap(page => page.html.match(VARIANT_PATH) ?? [])),\n ].sort()\n const maxFiles = nonNegativeInteger('maxFiles', options.maxFiles ?? DEFAULT_MAX_FILES)\n const concurrency = positiveInteger(\n 'foldkit-media: materialize concurrency',\n options.concurrency ?? 4,\n )\n if (paths.length > maxFiles) {\n throw new Error(\n `foldkit-media: the pages name ${paths.length} variants, more than maxFiles (${maxFiles})`,\n )\n }\n if (\n paths.length > 0 &&\n options.headersFile !== undefined &&\n !options.headersFile.split(/\\r?\\n/).some(line => line.trim() === PATTERN)\n ) {\n throw new Error(\n `foldkit-media: _headers has no ${PATTERN} rule, so the variants would be served uncached: add Media.headersRule()`,\n )\n }\n const made: Array<Materialized> = []\n const failed: Array<string> = []\n const queue = [...paths]\n const worker = async () => {\n for (let path = queue.shift(); path !== undefined; path = queue.shift()) {\n try {\n const response = await options.fetch(new Request(`http://materialize.invalid${path}`))\n if (response.status !== 200) {\n failed.push(`${path}: ${response.status}`)\n continue\n }\n made.push({ file: path.slice(1), contents: new Uint8Array(await response.arrayBuffer()) })\n } catch (cause) {\n failed.push(`${path}: ${cause instanceof Error ? cause.message : String(cause)}`)\n }\n }\n }\n // No more workers than paths, which also keeps an absurd concurrency out of\n // an array length.\n await Promise.all(Array.from({ length: Math.min(concurrency, paths.length) }, worker))\n if (failed.length > 0) {\n throw new Error(\n `foldkit-media: ${failed.length} variants could not be made:\\n${failed.sort().join('\\n')}`,\n )\n }\n return made.sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : 0))\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAWA,MAAa,WAAW,QAAQ,KAAK,eAAe,CAAC,CAAC,IACpD,aAAa,KAAK,QAAQ,CAAC,CAAC,IAC1B,gBAAgB,IAAI,WAAWA,MAAc;CAC3C,QAAQ;EAAE,MAAM,OAAO;EAAQ,SAAS,OAAO;CAAO;CACtD,SAAS,cAAc,iBAAiB;AAC1C,CAAC,CACH,CACF;;;ACLA,MAAM,oBAAoB;AAyB1B,MAAM,mBAAmB,YACvB,QAAQ,QAAQ,uBAAuB,OAAO,UAAU,QAAQ,qBAAqB,SAAS;AAEhG,MAAM,aAAa,YAAoB;CAAE,QAAQ,SAAS,MAAM;CAAG,SAAS,WAAW,MAAM;AAAE;AAE/F,MAAM,UAAU,MAAc,MAAY,YACxC,mBAAmB,WAAW,QAAQ,OAAO;CAC3C,GAAG,UAAU,OAAO,MAAM,QAAQ,KAAK;EAAE;EAAM;CAAK,CAAC,CAAC;CACtD,aAAa,QAAQ;AACvB,CAAC;AAEH,MAAM,eAAe,SACnB,mBAAmB,MAAM,UAAU,OAAO,MAAM,YAAY,KAAK,EAAE,KAAK,CAAC,CA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AAS,KAAA,GAAW,OAAO,MAAM,MAAM,GACpE,IAAI;GACF,MAAM,WAAW,MAAM,QAAQ,MAAM,IAAI,QAAQ,6BAA6B,MAAM,CAAC;GACrF,IAAI,SAAS,WAAW,KAAK;IAC3B,OAAO,KAAK,GAAG,KAAK,IAAI,SAAS,QAAQ;IACzC;GACF;GACA,KAAK,KAAK;IAAE,MAAM,KAAK,MAAM,CAAC;IAAG,UAAU,IAAI,WAAW,MAAM,SAAS,YAAY,CAAC;GAAE,CAAC;EAC3F,SAAS,OAAO;GACd,OAAO,KAAK,GAAG,KAAK,IAAI,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG;EAClF;CAEJ;CAGA,MAAM,QAAQ,IAAI,MAAM,KAAK,EAAE,QAAQ,KAAK,IAAI,aAAa,MAAM,MAAM,EAAE,GAAG,MAAM,CAAC;CACrF,IAAI,OAAO,SAAS,GAClB,MAAM,IAAI,MACR,kBAAkB,OAAO,OAAO,gCAAgC,OAAO,KAAK,CAAC,CAAC,KAAK,IAAI,GACzF;CAEF,OAAO,KAAK,MAAM,GAAG,MAAO,EAAE,OAAO,EAAE,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,IAAI,CAAE;AAC7E"}
@@ -1,6 +1,6 @@
1
- import { n as positiveInteger } from "./limits-B6C9OOLl.mjs";
1
+ import { n as positiveInteger } from "./limits-B4hHpyfE.mjs";
2
2
  import { Context, Effect, Layer, Option, Semaphore } from "effect";
3
- //#region src/server/services.ts
3
+ // src/server/services.ts
4
4
  /** Where originals live, by their content hash. Authoritative: the server never writes it. */
5
5
  var Originals = class extends Context.Service()("foldkit-media/Originals") {};
6
6
  /**
@@ -33,7 +33,6 @@ const limitTransforms = (concurrency) => {
33
33
  return { transform: (original, variant) => Semaphore.withPermit(permits)(inner.transform(original, variant)) };
34
34
  })).pipe(Layer.provide(transformer));
35
35
  };
36
- //#endregion
37
36
  export { variantsNone as a, limitTransforms as i, Transformer as n, Variants as r, Originals as t };
38
37
 
39
- //# sourceMappingURL=services-BeakQl7F.mjs.map
38
+ //# sourceMappingURL=services-7B4hsQM7.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"services-BeakQl7F.mjs","names":[],"sources":["../src/server/services.ts"],"sourcesContent":["import { Context, Effect, Layer, Option, Semaphore } from 'effect'\nimport { positiveInteger } from '../limits.js'\nimport type { Variant } from '../variant.js'\nimport type {\n OriginalNotFound,\n OriginalTooLarge,\n QuotaExhausted,\n TransformFailed,\n} from './errors.js'\n\n/** An original's bytes, as the store hands them over, and how many there are. */\nexport interface Original {\n readonly body: ReadableStream<Uint8Array>\n readonly size: number\n}\n\n/** A variant made: its bytes and their media type. */\nexport interface Encoded {\n readonly bytes: Uint8Array<ArrayBuffer>\n readonly contentType: string\n}\n\n/** A variant found kept, and which layer had it. */\nexport interface Kept {\n readonly encoded: Encoded\n readonly from: 'edge' | 'store'\n}\n\n/** Where originals live, by their content hash. Authoritative: the server never writes it. */\nexport class Originals extends Context.Service<\n Originals,\n { readonly get: (hash: string) => Effect.Effect<Original, OriginalNotFound> }\n>()('foldkit-media/Originals') {}\n\n/**\n * Resizes and encodes an original into a variant, never larger than the\n * original (a width above it answers with the original's width). An original\n * too large to decode is `OriginalTooLarge`, a 413, as one too large to read.\n */\nexport class Transformer extends Context.Service<\n Transformer,\n {\n readonly transform: (\n original: Original,\n variant: Variant,\n ) => Effect.Effect<Encoded, TransformFailed | QuotaExhausted | OriginalTooLarge>\n }\n>()('foldkit-media/Transformer') {}\n\n/**\n * Variants already made, by the encoded request. A cache: losing it costs\n * time, and on a host that bills transformations, money; never data.\n */\nexport class Variants extends Context.Service<\n Variants,\n {\n readonly get: (key: string) => Effect.Effect<Option.Option<Kept>>\n readonly put: (key: string, encoded: Encoded) => Effect.Effect<void>\n }\n>()('foldkit-media/Variants') {}\n\n/** Keeps nothing: every request transforms. For a host with a cache of its own in front. */\nexport const variantsNone: Layer.Layer<Variants> = Layer.succeed(Variants, {\n get: () => Effect.succeed(Option.none()),\n put: () => Effect.void,\n})\n\n/**\n * A `Transformer` that runs at most `concurrency` transforms at once, the\n * rest waiting their turn: encoding is CPU work, and a burst of misses should\n * queue, not starve every other request. For a transformer that encodes in\n * this process (sharp, WebAssembly); a host's binding does the work elsewhere.\n */\nexport const limitTransforms = (concurrency: number) => {\n const permitsCount = positiveInteger('limitTransforms: concurrency', concurrency)\n return <E, R>(transformer: Layer.Layer<Transformer, E, R>): Layer.Layer<Transformer, E, R> =>\n Layer.effect(\n Transformer,\n Effect.gen(function* () {\n const inner = yield* Transformer\n const permits = yield* Semaphore.make(permitsCount)\n return {\n transform: (original: Original, variant: Variant) =>\n Semaphore.withPermit(permits)(inner.transform(original, variant)),\n }\n }),\n ).pipe(Layer.provide(transformer))\n}\n"],"mappings":";;;;AA6BA,IAAa,YAAb,cAA+B,QAAQ,QAGrC,CAAC,CAAC,yBAAyB,CAAC,CAAC,CAAC;;;;;;AAOhC,IAAa,cAAb,cAAiC,QAAQ,QAQvC,CAAC,CAAC,2BAA2B,CAAC,CAAC,CAAC;;;;;AAMlC,IAAa,WAAb,cAA8B,QAAQ,QAMpC,CAAC,CAAC,wBAAwB,CAAC,CAAC,CAAC;;AAG/B,MAAa,eAAsC,MAAM,QAAQ,UAAU;CACzE,WAAW,OAAO,QAAQ,OAAO,KAAK,CAAC;CACvC,WAAW,OAAO;AACpB,CAAC;;;;;;;AAQD,MAAa,mBAAmB,gBAAwB;CACtD,MAAM,eAAe,gBAAgB,gCAAgC,WAAW;CAChF,QAAc,gBACZ,MAAM,OACJ,aACA,OAAO,IAAI,aAAa;EACtB,MAAM,QAAQ,OAAO;EACrB,MAAM,UAAU,OAAO,UAAU,KAAK,YAAY;EAClD,OAAO,EACL,YAAY,UAAoB,YAC9B,UAAU,WAAW,OAAO,CAAC,CAAC,MAAM,UAAU,UAAU,OAAO,CAAC,EACpE;CACF,CAAC,CACH,CAAC,CAAC,KAAK,MAAM,QAAQ,WAAW,CAAC;AACrC"}
1
+ {"version":3,"file":"services-7B4hsQM7.mjs","names":[],"sources":["../src/server/services.ts"],"sourcesContent":["import { Context, Effect, Layer, Option, Semaphore } from 'effect'\nimport { positiveInteger } from '../limits.js'\nimport type { Variant } from '../variant.js'\nimport type {\n OriginalNotFound,\n OriginalTooLarge,\n QuotaExhausted,\n TransformFailed,\n} from './errors.js'\n\n/** An original's bytes, as the store hands them over, and how many there are. */\nexport interface Original {\n readonly body: ReadableStream<Uint8Array>\n readonly size: number\n}\n\n/** A variant made: its bytes and their media type. */\nexport interface Encoded {\n readonly bytes: Uint8Array<ArrayBuffer>\n readonly contentType: string\n}\n\n/** A variant found kept, and which layer had it. */\nexport interface Kept {\n readonly encoded: Encoded\n readonly from: 'edge' | 'store'\n}\n\n/** Where originals live, by their content hash. Authoritative: the server never writes it. */\nexport class Originals extends Context.Service<\n Originals,\n { readonly get: (hash: string) => Effect.Effect<Original, OriginalNotFound> }\n>()('foldkit-media/Originals') {}\n\n/**\n * Resizes and encodes an original into a variant, never larger than the\n * original (a width above it answers with the original's width). An original\n * too large to decode is `OriginalTooLarge`, a 413, as one too large to read.\n */\nexport class Transformer extends Context.Service<\n Transformer,\n {\n readonly transform: (\n original: Original,\n variant: Variant,\n ) => Effect.Effect<Encoded, TransformFailed | QuotaExhausted | OriginalTooLarge>\n }\n>()('foldkit-media/Transformer') {}\n\n/**\n * Variants already made, by the encoded request. A cache: losing it costs\n * time, and on a host that bills transformations, money; never data.\n */\nexport class Variants extends Context.Service<\n Variants,\n {\n readonly get: (key: string) => Effect.Effect<Option.Option<Kept>>\n readonly put: (key: string, encoded: Encoded) => Effect.Effect<void>\n }\n>()('foldkit-media/Variants') {}\n\n/** Keeps nothing: every request transforms. For a host with a cache of its own in front. */\nexport const variantsNone: Layer.Layer<Variants> = Layer.succeed(Variants, {\n get: () => Effect.succeed(Option.none()),\n put: () => Effect.void,\n})\n\n/**\n * A `Transformer` that runs at most `concurrency` transforms at once, the\n * rest waiting their turn: encoding is CPU work, and a burst of misses should\n * queue, not starve every other request. For a transformer that encodes in\n * this process (sharp, WebAssembly); a host's binding does the work elsewhere.\n */\nexport const limitTransforms = (concurrency: number) => {\n const permitsCount = positiveInteger('limitTransforms: concurrency', concurrency)\n return <E, R>(transformer: Layer.Layer<Transformer, E, R>): Layer.Layer<Transformer, E, R> =>\n Layer.effect(\n Transformer,\n Effect.gen(function* () {\n const inner = yield* Transformer\n const permits = yield* Semaphore.make(permitsCount)\n return {\n transform: (original: Original, variant: Variant) =>\n Semaphore.withPermit(permits)(inner.transform(original, variant)),\n }\n }),\n ).pipe(Layer.provide(transformer))\n}\n"],"mappings":";;;;AA6BA,IAAa,YAAb,cAA+B,QAAQ,QAGrC,CAAC,CAAC,yBAAyB,CAAC,CAAC,CAAC;;;;;;AAOhC,IAAa,cAAb,cAAiC,QAAQ,QAQvC,CAAC,CAAC,2BAA2B,CAAC,CAAC,CAAC;;;;;AAMlC,IAAa,WAAb,cAA8B,QAAQ,QAMpC,CAAC,CAAC,wBAAwB,CAAC,CAAC,CAAC;;AAG/B,MAAa,eAAsC,MAAM,QAAQ,UAAU;CACzE,WAAW,OAAO,QAAQ,OAAO,KAAK,CAAC;CACvC,WAAW,OAAO;AACpB,CAAC;;;;;;;AAQD,MAAa,mBAAmB,gBAAwB;CACtD,MAAM,eAAe,gBAAgB,gCAAgC,WAAW;CAChF,QAAc,gBACZ,MAAM,OACJ,aACA,OAAO,IAAI,aAAa;EACtB,MAAM,QAAQ,OAAO;EACrB,MAAM,UAAU,OAAO,UAAU,KAAK,YAAY;EAClD,OAAO,EACL,YAAY,UAAoB,YAC9B,UAAU,WAAW,OAAO,CAAC,CAAC,MAAM,UAAU,UAAU,OAAO,CAAC,EACpE;CACF,CAAC,CACH,CAAC,CAAC,KAAK,MAAM,QAAQ,WAAW,CAAC;AACrC"}
@@ -1,7 +1,6 @@
1
- import { a as OriginalNotFound, c as TransformFailed, o as OriginalTooLarge, s as QuotaExhausted } from "./describe-CivKHl4x.mjs";
2
- import { n as Variant } from "./variant-BOg1M0Wj.mjs";
1
+ import { a as OriginalNotFound, c as TransformFailed, o as OriginalTooLarge, s as QuotaExhausted } from "./describe-BOgc0xbR.mjs";
2
+ import { n as Variant } from "./variant-B-vyMmFB.mjs";
3
3
  import { Context, Effect, Layer, Option } from "effect";
4
- //#region src/server/services.d.ts
5
4
  /** An original's bytes, as the store hands them over, and how many there are. */
6
5
  interface Original {
7
6
  readonly body: ReadableStream<Uint8Array>;
@@ -49,6 +48,5 @@ declare const variantsNone: Layer.Layer<Variants>;
49
48
  * this process (sharp, WebAssembly); a host's binding does the work elsewhere.
50
49
  */
51
50
  declare const limitTransforms: (concurrency: number) => <E, R>(transformer: Layer.Layer<Transformer, E, R>) => Layer.Layer<Transformer, E, R>;
52
- //#endregion
53
51
  export { Transformer as a, variantsNone as c, Originals as i, Kept as n, Variants as o, Original as r, limitTransforms as s, Encoded as t };
54
- //# sourceMappingURL=services-8_h0ubLB.d.mts.map
52
+ //# sourceMappingURL=services-BZoK2VOY.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"services-BZoK2VOY.d.mts","names":[],"sources":["../src/server/services.ts"],"mappings":";;;;UAWiB;WACN,MAAM,eAAe;WACrB;;;UAIM;WACN,OAAO,WAAW;WAClB;;;UAIM;WACN,SAAS;WACT;;;WAMO,MAAC,iBAAiB,OAAO,OAAO,UAAU;;;cAF/C,kBAAkB;;WAaP,YAClB,UAAU,UACV,SAAS,YACN,OAAO,OAAO,SAAS,kBAAkB,iBAAiB;;;;;;;cANtD,oBAAoB;;WAiBf,MAAC,gBAAgB,OAAO,OAAO,OAAO,OAAO;WAC7C,MAAC,aAAa,SAAS,YAAY,OAAO;;;;;;cAJ/C,iBAAiB;;cASjB,cAAc,MAAM,MAAM;;;;;;;cAW1B,kBAAe,yBAElB,GAAG,GAAC,aAAe,MAAM,MAAM,aAAa,GAAG,OAAK,MAAM,MAAM,aAAa,GAAG"}
@@ -1,7 +1,6 @@
1
- import { n as Inspector } from "../describe-CivKHl4x.mjs";
2
- import { a as Transformer } from "../services-8_h0ubLB.mjs";
1
+ import { n as Inspector } from "../describe-BOgc0xbR.mjs";
2
+ import { a as Transformer } from "../services-BZoK2VOY.mjs";
3
3
  import { Layer } from "effect";
4
- //#region src/sharp/index.d.ts
5
4
  export declare const transformerSharp: (options?: {
6
5
  /** Transforms run at once; by default the machine's cores. */
7
6
  readonly concurrency?: number;
@@ -17,5 +16,4 @@ export declare const transformerSharp: (options?: {
17
16
  export declare const inspectorSharp: (options?: {
18
17
  readonly maxPixels?: number;
19
18
  }) => Layer.Layer<Inspector>;
20
- //#endregion
21
19
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/sharp/index.ts"],"mappings":";;;;qBA8Ca,mBAAgB;;WAGhB;;WAEA;MAEV,MAAM,MAAM;;;;;;;qBAuCF,iBAAc;WACL;MACnB,MAAM,MAAM"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/sharp/index.ts"],"mappings":";;;qBA8Ca,mBAAgB;;WAGhB;;WAEA;MAEV,MAAM,MAAM;;;;;;;qBAuCF,iBAAc;WACL;MACnB,MAAM,MAAM"}
@@ -1,11 +1,11 @@
1
- import { t as Inspector } from "../describe-h9F5stgR.mjs";
2
- import { t as nonNegativeInteger } from "../limits-B6C9OOLl.mjs";
3
- import { i as TransformFailed, n as OriginalTooLarge } from "../errors-qETj7Pgi.mjs";
4
- import { i as limitTransforms, n as Transformer } from "../services-BeakQl7F.mjs";
1
+ import { t as Inspector } from "../describe-C6sWA_8p.mjs";
2
+ import { t as nonNegativeInteger } from "../limits-B4hHpyfE.mjs";
3
+ import { i as TransformFailed, n as OriginalTooLarge } from "../errors-BhEgXJ4m.mjs";
4
+ import { i as limitTransforms, n as Transformer } from "../services-7B4hsQM7.mjs";
5
5
  import { Effect, Layer, Option } from "effect";
6
6
  import { availableParallelism } from "node:os";
7
7
  import sharp from "sharp";
8
- //#region src/sharp/index.ts
8
+ // src/sharp/index.ts
9
9
  /**
10
10
  * The media server's `Transformer` on a Node server, through sharp. At most
11
11
  * `concurrency` transforms run at once (`limitTransforms`), and an original
@@ -97,7 +97,6 @@ const inspectorSharp = (options = {}) => {
97
97
  };
98
98
  }).pipe(Effect.withSpan("Media.inspect")) });
99
99
  };
100
- //#endregion
101
100
  export { inspectorSharp, transformerSharp };
102
101
 
103
102
  //# sourceMappingURL=index.mjs.map