@draht/durable 2026.11.27-1 → 2026.12.3-2

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 (119) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/codemode/codemode.d.ts.map +1 -1
  3. package/dist/codemode/codemode.js +39 -0
  4. package/dist/codemode/codemode.js.map +1 -1
  5. package/dist/documents.d.ts.map +1 -1
  6. package/dist/documents.js +7 -2
  7. package/dist/documents.js.map +1 -1
  8. package/dist/env/index.d.ts +11 -0
  9. package/dist/env/index.d.ts.map +1 -1
  10. package/dist/env/index.js.map +1 -1
  11. package/dist/env/node.d.ts +1 -0
  12. package/dist/env/node.d.ts.map +1 -1
  13. package/dist/env/node.js +114 -34
  14. package/dist/env/node.js.map +1 -1
  15. package/dist/harness/task-graph.d.ts.map +1 -1
  16. package/dist/harness/task-graph.js +26 -13
  17. package/dist/harness/task-graph.js.map +1 -1
  18. package/dist/harness/usage.d.ts.map +1 -1
  19. package/dist/harness/usage.js +2 -0
  20. package/dist/harness/usage.js.map +1 -1
  21. package/dist/harness/view.d.ts +5 -1
  22. package/dist/harness/view.d.ts.map +1 -1
  23. package/dist/harness/view.js +36 -24
  24. package/dist/harness/view.js.map +1 -1
  25. package/dist/ids.d.ts +10 -0
  26. package/dist/ids.d.ts.map +1 -1
  27. package/dist/ids.js +21 -0
  28. package/dist/ids.js.map +1 -1
  29. package/dist/images/encode.d.ts +33 -0
  30. package/dist/images/encode.d.ts.map +1 -0
  31. package/dist/images/encode.js +69 -0
  32. package/dist/images/encode.js.map +1 -0
  33. package/dist/images/index.d.ts +4 -4
  34. package/dist/images/index.d.ts.map +1 -1
  35. package/dist/images/index.js +41 -58
  36. package/dist/images/index.js.map +1 -1
  37. package/dist/images/node-worker.d.ts +1 -18
  38. package/dist/images/node-worker.d.ts.map +1 -1
  39. package/dist/images/node-worker.js +2 -12
  40. package/dist/images/node-worker.js.map +1 -1
  41. package/dist/images/node.d.ts.map +1 -1
  42. package/dist/images/node.js +4 -103
  43. package/dist/images/node.js.map +1 -1
  44. package/dist/images/pi-images/cloudflare.d.ts +8 -0
  45. package/dist/images/pi-images/cloudflare.d.ts.map +1 -0
  46. package/dist/images/pi-images/cloudflare.js +14 -0
  47. package/dist/images/pi-images/cloudflare.js.map +1 -0
  48. package/dist/images/pi-images/index.d.ts +37 -0
  49. package/dist/images/pi-images/index.d.ts.map +1 -0
  50. package/dist/images/pi-images/index.js +22 -0
  51. package/dist/images/pi-images/index.js.map +1 -0
  52. package/dist/images/pi-images/installed.d.ts +8 -0
  53. package/dist/images/pi-images/installed.d.ts.map +1 -0
  54. package/dist/images/pi-images/installed.js +24 -0
  55. package/dist/images/pi-images/installed.js.map +1 -0
  56. package/dist/images/pi-images/node-worker.d.ts +2 -0
  57. package/dist/images/pi-images/node-worker.d.ts.map +1 -0
  58. package/dist/images/pi-images/node-worker.js +7 -0
  59. package/dist/images/pi-images/node-worker.js.map +1 -0
  60. package/dist/images/pi-images/node.d.ts +24 -0
  61. package/dist/images/pi-images/node.d.ts.map +1 -0
  62. package/dist/images/pi-images/node.js +18 -0
  63. package/dist/images/pi-images/node.js.map +1 -0
  64. package/dist/images/pi-images/processor.d.ts +21 -0
  65. package/dist/images/pi-images/processor.d.ts.map +1 -0
  66. package/dist/images/pi-images/processor.js +117 -0
  67. package/dist/images/pi-images/processor.js.map +1 -0
  68. package/dist/images/thread.d.ts +27 -0
  69. package/dist/images/thread.d.ts.map +1 -0
  70. package/dist/images/thread.js +131 -0
  71. package/dist/images/thread.js.map +1 -0
  72. package/dist/session/session.js +32 -6
  73. package/dist/session/session.js.map +1 -1
  74. package/dist/session/transaction.d.ts.map +1 -1
  75. package/dist/session/transaction.js +3 -0
  76. package/dist/session/transaction.js.map +1 -1
  77. package/dist/storage/jsonl/storage.d.ts +6 -0
  78. package/dist/storage/jsonl/storage.d.ts.map +1 -1
  79. package/dist/storage/jsonl/storage.js +65 -0
  80. package/dist/storage/jsonl/storage.js.map +1 -1
  81. package/dist/storage/sqlite/commit.d.ts.map +1 -1
  82. package/dist/storage/sqlite/commit.js +3 -3
  83. package/dist/storage/sqlite/commit.js.map +1 -1
  84. package/dist/storage/sqlite/migrations.d.ts.map +1 -1
  85. package/dist/storage/sqlite/migrations.js +20 -0
  86. package/dist/storage/sqlite/migrations.js.map +1 -1
  87. package/dist/storage/sqlite/rows.d.ts +0 -2
  88. package/dist/storage/sqlite/rows.d.ts.map +1 -1
  89. package/dist/storage/sqlite/rows.js +3 -5
  90. package/dist/storage/sqlite/rows.js.map +1 -1
  91. package/dist/storage/sqlite/storage.d.ts +1 -1
  92. package/dist/storage/sqlite/storage.d.ts.map +1 -1
  93. package/dist/storage/sqlite/storage.js +11 -10
  94. package/dist/storage/sqlite/storage.js.map +1 -1
  95. package/dist/storage/store/documents.d.ts.map +1 -1
  96. package/dist/storage/store/documents.js +4 -6
  97. package/dist/storage/store/documents.js.map +1 -1
  98. package/dist/storage/store/migrations.d.ts +10 -0
  99. package/dist/storage/store/migrations.d.ts.map +1 -0
  100. package/dist/storage/store/migrations.js +44 -0
  101. package/dist/storage/store/migrations.js.map +1 -0
  102. package/dist/storage/store/storage.d.ts +3 -2
  103. package/dist/storage/store/storage.d.ts.map +1 -1
  104. package/dist/storage/store/storage.js +9 -6
  105. package/dist/storage/store/storage.js.map +1 -1
  106. package/dist/storage/store/tables.d.ts +21 -3
  107. package/dist/storage/store/tables.d.ts.map +1 -1
  108. package/dist/storage/store/tables.js +14 -10
  109. package/dist/storage/store/tables.js.map +1 -1
  110. package/dist/tasks.d.ts.map +1 -1
  111. package/dist/tasks.js +2 -0
  112. package/dist/tasks.js.map +1 -1
  113. package/dist/testing/storage-conformance.d.ts.map +1 -1
  114. package/dist/testing/storage-conformance.js +0 -74
  115. package/dist/testing/storage-conformance.js.map +1 -1
  116. package/dist/types.d.ts +4 -1
  117. package/dist/types.d.ts.map +1 -1
  118. package/dist/types.js.map +1 -1
  119. package/package.json +26 -6
@@ -0,0 +1,69 @@
1
+ // The policy every image processor shares, so their behaviour cannot drift: when an image goes back as it is, the
2
+ // size it is fitted to, and the encode loop (PNG, then JPEG at falling qualities, JPEG first for a JPEG source; then
3
+ // 3/4 smaller each round, down to 1x1, until the base64 fits). The processors bring the mechanics: decoding, turning
4
+ // upright, resizing, encoding.
5
+ import { detectSupportedImageMimeType } from "../tools/image.js";
6
+ import { base64Length, INLINE_IMAGE_TYPES, toBase64, } from "../tools/image-processor.js";
7
+ /** JPEG qualities tried in order. */
8
+ const JPEG_QUALITIES = [80, 70, 55, 40];
9
+ /**
10
+ * Whether an image may go back as it is, its size aside: a type providers take inline that its bytes are (an image
11
+ * declared as another type goes back re-encoded, never under the wrong type), already upright (EXIF `orientation` 1),
12
+ * and its base64 within the byte limit.
13
+ */
14
+ export function mayReturnAsIs(bytes, mimeType, orientation, limits) {
15
+ return (INLINE_IMAGE_TYPES.has(mimeType) &&
16
+ detectSupportedImageMimeType(bytes) === mimeType &&
17
+ orientation === 1 &&
18
+ base64Length(bytes.byteLength) <= limits.maxBytes);
19
+ }
20
+ /** Whether `size` is within the limits' width and height. */
21
+ export function withinLimits(size, limits) {
22
+ return size.width <= limits.maxWidth && size.height <= limits.maxHeight;
23
+ }
24
+ /** The largest size within the limits' width and height with `size`'s aspect, never larger, at least 1x1. */
25
+ export function fittedSize(size, limits) {
26
+ const scale = Math.min(1, limits.maxWidth / size.width, limits.maxHeight / size.height);
27
+ return { width: Math.max(1, Math.round(size.width * scale)), height: Math.max(1, Math.round(size.height * scale)) };
28
+ }
29
+ /**
30
+ * `encoder`'s image, upright at `from` before resizing, as the first encoding whose base64 fits `maxBytes`: at
31
+ * `first`, the encoder's starting size, then 3/4 smaller each round, down to 1x1; `undefined` when not even that fits.
32
+ * `resized` is set when the size changed, `convertedFrom` when the format differs from `mimeType`, the source's
33
+ * declared type.
34
+ */
35
+ export function encodeToFit(encoder, from, first, mimeType, maxBytes) {
36
+ const jpegFirst = mimeType === "image/jpeg";
37
+ for (let size = first;; size = smaller(size)) {
38
+ if (size !== first)
39
+ encoder.shrink(size);
40
+ const encoded = encodeWithin(encoder, maxBytes, jpegFirst);
41
+ if (encoded !== undefined) {
42
+ const resized = size.width === from.width && size.height === from.height ? {} : { resized: { from, to: size } };
43
+ const converted = encoded.mimeType === mimeType ? {} : { convertedFrom: mimeType };
44
+ return { ...encoded, ...converted, ...resized };
45
+ }
46
+ if (size.width === 1 && size.height === 1)
47
+ return undefined;
48
+ }
49
+ }
50
+ /** `size` scaled to 3/4, at least 1x1. */
51
+ function smaller(size) {
52
+ return { width: Math.max(1, Math.floor(size.width * 0.75)), height: Math.max(1, Math.floor(size.height * 0.75)) };
53
+ }
54
+ /**
55
+ * The image at its current size in the first encoding whose base64 fits `maxBytes`: PNG, then JPEG at falling
56
+ * qualities, or the JPEG qualities first when `jpegFirst`; `undefined` if none fits.
57
+ */
58
+ function encodeWithin(encoder, maxBytes, jpegFirst) {
59
+ const png = { mimeType: "image/png", encode: () => encoder.png() };
60
+ const jpegs = JPEG_QUALITIES.map((quality) => ({ mimeType: "image/jpeg", encode: () => encoder.jpeg(quality) }));
61
+ for (const candidate of jpegFirst ? [...jpegs, png] : [png, ...jpegs]) {
62
+ const bytes = candidate.encode();
63
+ if (bytes !== undefined && base64Length(bytes.byteLength) <= maxBytes) {
64
+ return { data: toBase64(bytes), mimeType: candidate.mimeType };
65
+ }
66
+ }
67
+ return undefined;
68
+ }
69
+ //# sourceMappingURL=encode.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encode.js","sourceRoot":"","sources":["../../src/images/encode.ts"],"names":[],"mappings":"AAAA,kHAAkH;AAClH,qHAAqH;AACrH,qHAAqH;AACrH,+BAA+B;AAE/B,OAAO,EAAE,4BAA4B,EAAE,MAAM,mBAAmB,CAAC;AACjE,OAAO,EACN,YAAY,EAEZ,kBAAkB,EAElB,QAAQ,GACR,MAAM,6BAA6B,CAAC;AAerC,qCAAqC;AACrC,MAAM,cAAc,GAAG,CAAC,EA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,SAAkB;IAElB,MAAM,GAAG,GAAG,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC;IACnE,MAAM,KAAK,GAAG,cAAc,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC;IACjH,KAAK,MAAM,SAAS,IAAI,SAAS,CAAC,CAAC,CAAC,CAAC,GAAG,KAAK,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,EAAE,CAAC;QACvE,MAAM,KAAK,GAAG,SAAS,CAAC,MAAM,EAAE,CAAC;QACjC,IAAI,KAAK,KAAK,SAAS,IAAI,YAAY,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,QAAQ,EAAE,CAAC;YACvE,OAAO,EAAE,IAAI,EAAE,QAAQ,CAAC,KAAK,CAAC,EAAE,QAAQ,EAAE,SAAS,CAAC,QAAQ,EAAE,CAAC;QAChE,CAAC;IACF,CAAC;IACD,OAAO,SAAS,CAAC;AAClB,CAAC","sourcesContent":["// The policy every image processor shares, so their behaviour cannot drift: when an image goes back as it is, the\n// size it is fitted to, and the encode loop (PNG, then JPEG at falling qualities, JPEG first for a JPEG source; then\n// 3/4 smaller each round, down to 1x1, until the base64 fits). The processors bring the mechanics: decoding, turning\n// upright, resizing, encoding.\n\nimport { detectSupportedImageMimeType } from \"../tools/image.ts\";\nimport {\n\tbase64Length,\n\ttype ImageLimits,\n\tINLINE_IMAGE_TYPES,\n\ttype PreparedImage,\n\ttoBase64,\n} from \"../tools/image-processor.ts\";\n\n/** A width and height in pixels. */\nexport type ImageSize = { readonly width: number; readonly height: number };\n\n/** A processor's upright image, starting at the fitted size, encoded at the sizes `encodeToFit` asks for. */\nexport type ImageEncoder = {\n\t/** Scales the image down to `size`, smaller than its current one, for the next encodings. */\n\tshrink(size: ImageSize): void;\n\t/** The image as PNG, read before the next call; `undefined` when it cannot be encoded. */\n\tpng(): Uint8Array | undefined;\n\t/** The image as JPEG at `quality`, as `png()` returns it. */\n\tjpeg(quality: number): Uint8Array | undefined;\n};\n\n/** JPEG qualities tried in order. */\nconst JPEG_QUALITIES = [80, 70, 55, 40];\n\n/**\n * Whether an image may go back as it is, its size aside: a type providers take inline that its bytes are (an image\n * declared as another type goes back re-encoded, never under the wrong type), already upright (EXIF `orientation` 1),\n * and its base64 within the byte limit.\n */\nexport function mayReturnAsIs(bytes: Uint8Array, mimeType: string, orientation: number, limits: ImageLimits): boolean {\n\treturn (\n\t\tINLINE_IMAGE_TYPES.has(mimeType) &&\n\t\tdetectSupportedImageMimeType(bytes) === mimeType &&\n\t\torientation === 1 &&\n\t\tbase64Length(bytes.byteLength) <= limits.maxBytes\n\t);\n}\n\n/** Whether `size` is within the limits' width and height. */\nexport function withinLimits(size: ImageSize, limits: ImageLimits): boolean {\n\treturn size.width <= limits.maxWidth && size.height <= limits.maxHeight;\n}\n\n/** The largest size within the limits' width and height with `size`'s aspect, never larger, at least 1x1. */\nexport function fittedSize(size: ImageSize, limits: ImageLimits): ImageSize {\n\tconst scale = Math.min(1, limits.maxWidth / size.width, limits.maxHeight / size.height);\n\treturn { width: Math.max(1, Math.round(size.width * scale)), height: Math.max(1, Math.round(size.height * scale)) };\n}\n\n/**\n * `encoder`'s image, upright at `from` before resizing, as the first encoding whose base64 fits `maxBytes`: at\n * `first`, the encoder's starting size, then 3/4 smaller each round, down to 1x1; `undefined` when not even that fits.\n * `resized` is set when the size changed, `convertedFrom` when the format differs from `mimeType`, the source's\n * declared type.\n */\nexport function encodeToFit(\n\tencoder: ImageEncoder,\n\tfrom: ImageSize,\n\tfirst: ImageSize,\n\tmimeType: string,\n\tmaxBytes: number,\n): PreparedImage | undefined {\n\tconst jpegFirst = mimeType === \"image/jpeg\";\n\tfor (let size = first; ; size = smaller(size)) {\n\t\tif (size !== first) encoder.shrink(size);\n\t\tconst encoded = encodeWithin(encoder, maxBytes, jpegFirst);\n\t\tif (encoded !== undefined) {\n\t\t\tconst resized =\n\t\t\t\tsize.width === from.width && size.height === from.height ? {} : { resized: { from, to: size } };\n\t\t\tconst converted = encoded.mimeType === mimeType ? {} : { convertedFrom: mimeType };\n\t\t\treturn { ...encoded, ...converted, ...resized };\n\t\t}\n\t\tif (size.width === 1 && size.height === 1) return undefined;\n\t}\n}\n\n/** `size` scaled to 3/4, at least 1x1. */\nfunction smaller(size: ImageSize): ImageSize {\n\treturn { width: Math.max(1, Math.floor(size.width * 0.75)), height: Math.max(1, Math.floor(size.height * 0.75)) };\n}\n\n/**\n * The image at its current size in the first encoding whose base64 fits `maxBytes`: PNG, then JPEG at falling\n * qualities, or the JPEG qualities first when `jpegFirst`; `undefined` if none fits.\n */\nfunction encodeWithin(\n\tencoder: ImageEncoder,\n\tmaxBytes: number,\n\tjpegFirst: boolean,\n): { readonly data: string; readonly mimeType: string } | undefined {\n\tconst png = { mimeType: \"image/png\", encode: () => encoder.png() };\n\tconst jpegs = JPEG_QUALITIES.map((quality) => ({ mimeType: \"image/jpeg\", encode: () => encoder.jpeg(quality) }));\n\tfor (const candidate of jpegFirst ? [...jpegs, png] : [png, ...jpegs]) {\n\t\tconst bytes = candidate.encode();\n\t\tif (bytes !== undefined && base64Length(bytes.byteLength) <= maxBytes) {\n\t\t\treturn { data: toBase64(bytes), mimeType: candidate.mimeType };\n\t\t}\n\t}\n\treturn undefined;\n}\n"]}
@@ -6,10 +6,10 @@ import type { ImageProcessor } from "../tools/image-processor.ts";
6
6
  * the installed package, `@draht/durable/images/cloudflare` imports it as a Workers module. Elsewhere, such
7
7
  * as a browser, fetch the file and pass its bytes. Photon loads once per process; later calls reuse the first `wasm`.
8
8
  *
9
- * An image already upright, in a format providers take inline, and within the limits is returned as it is, once it
10
- * decodes. Otherwise it is turned upright by its EXIF orientation, scaled to the
11
- * maximum width and height, and encoded as PNG or JPEG at falling qualities (JPEG first for JPEG sources), then at
12
- * smaller dimensions, 3/4 at a time, until the base64 fits. Formats providers do not take inline (BMP) become PNG.
9
+ * An image already upright, in a format providers take inline that its bytes are, and within the limits is returned as
10
+ * it is, once it decodes. Otherwise it is turned upright by its EXIF orientation, scaled to the maximum width and
11
+ * height, and encoded as PNG or JPEG at falling qualities (JPEG first for JPEG sources), then at smaller dimensions,
12
+ * 3/4 at a time, until the base64 fits. Formats providers do not take inline (BMP) become PNG.
13
13
  *
14
14
  * The work runs on the calling thread: about a second and a half for a 12-megapixel photo. Decoding takes the image's
15
15
  * RGBA size in WebAssembly memory, which does not shrink again; leave the processor out on memory-constrained hosts.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/images/index.ts"],"names":[],"mappings":"AACA,OAAO,EAON,KAAK,aAAa,EAClB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,KAAK,EAAe,cAAc,EAAiB,MAAM,6BAA6B,CAAC;AAO9F;;;;;;;;;;;;;GAaG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,aAAa,GAAG,cAAc,CAGtE"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/images/index.ts"],"names":[],"mappings":"AACA,OAAO,EAON,KAAK,aAAa,EAClB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,KAAK,EAAe,cAAc,EAAiB,MAAM,6BAA6B,CAAC;AAK9F;;;;;;;;;;;;;GAaG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,aAAa,GAAG,cAAc,CAGtE"}
@@ -1,19 +1,18 @@
1
1
  // The package declares only `module`, which bundlers use but Node does not: import the file itself.
2
2
  import { fliph, flipv, initSync, PhotonImage, resize, SamplingFilter, } from "@silvia-odwyer/photon/photon_rs.js";
3
- import { base64Length, INLINE_IMAGE_TYPES, toBase64 } from "../tools/image-processor.js";
3
+ import { toBase64 } from "../tools/image-processor.js";
4
+ import { encodeToFit, fittedSize, mayReturnAsIs, withinLimits } from "./encode.js";
4
5
  import { exifOrientation } from "./exif.js";
5
- /** JPEG qualities tried in order. */
6
- const JPEG_QUALITIES = [80, 70, 55, 40];
7
6
  /**
8
7
  * An `ImageProcessor` on Photon (Rust compiled to WebAssembly), for `createCodingTools({ images })`. `wasm` is
9
8
  * Photon's `photon_rs_bg.wasm` as bytes or as a compiled module: `@draht/durable/images/node` reads it from
10
9
  * the installed package, `@draht/durable/images/cloudflare` imports it as a Workers module. Elsewhere, such
11
10
  * as a browser, fetch the file and pass its bytes. Photon loads once per process; later calls reuse the first `wasm`.
12
11
  *
13
- * An image already upright, in a format providers take inline, and within the limits is returned as it is, once it
14
- * decodes. Otherwise it is turned upright by its EXIF orientation, scaled to the
15
- * maximum width and height, and encoded as PNG or JPEG at falling qualities (JPEG first for JPEG sources), then at
16
- * smaller dimensions, 3/4 at a time, until the base64 fits. Formats providers do not take inline (BMP) become PNG.
12
+ * An image already upright, in a format providers take inline that its bytes are, and within the limits is returned as
13
+ * it is, once it decodes. Otherwise it is turned upright by its EXIF orientation, scaled to the maximum width and
14
+ * height, and encoded as PNG or JPEG at falling qualities (JPEG first for JPEG sources), then at smaller dimensions,
15
+ * 3/4 at a time, until the base64 fits. Formats providers do not take inline (BMP) become PNG.
17
16
  *
18
17
  * The work runs on the calling thread: about a second and a half for a 12-megapixel photo. Decoding takes the image's
19
18
  * RGBA size in WebAssembly memory, which does not shrink again; leave the processor out on memory-constrained hosts.
@@ -24,16 +23,13 @@ export function createPhotonImages(wasm) {
24
23
  }
25
24
  function prepare(bytes, mimeType, limits) {
26
25
  const orientation = exifOrientation(bytes);
27
- const inline = INLINE_IMAGE_TYPES.has(mimeType);
28
26
  let image;
27
+ let encoder;
29
28
  try {
30
29
  // Decoded even when it is returned as it is: a damaged file is an error, not an image the provider rejects.
31
30
  image = PhotonImage.new_from_byteslice(bytes);
32
- if (inline &&
33
- orientation === 1 &&
34
- image.get_width() <= limits.maxWidth &&
35
- image.get_height() <= limits.maxHeight &&
36
- base64Length(bytes.byteLength) <= limits.maxBytes) {
31
+ const stored = { width: image.get_width(), height: image.get_height() };
32
+ if (mayReturnAsIs(bytes, mimeType, orientation, limits) && withinLimits(stored, limits)) {
37
33
  return { data: toBase64(bytes), mimeType };
38
34
  }
39
35
  if (orientation >= 5) {
@@ -49,60 +45,20 @@ function prepare(bytes, mimeType, limits) {
49
45
  if (orientation !== 2)
50
46
  flipv(image);
51
47
  }
52
- const width = image.get_width();
53
- const height = image.get_height();
54
- const scale = Math.min(1, limits.maxWidth / width, limits.maxHeight / height);
55
- let target = { width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)) };
56
- for (;;) {
57
- const encoded = encodeWithin(image, target, limits.maxBytes, mimeType === "image/jpeg");
58
- if (encoded !== undefined) {
59
- const resized = target.width === width && target.height === height
60
- ? {}
61
- : { resized: { from: { width, height }, to: target } };
62
- const converted = encoded.mimeType === mimeType ? {} : { convertedFrom: mimeType };
63
- return { ...encoded, ...converted, ...resized };
64
- }
65
- if (target.width === 1 && target.height === 1)
66
- return undefined;
67
- target = {
68
- width: Math.max(1, Math.floor(target.width * 0.75)),
69
- height: Math.max(1, Math.floor(target.height * 0.75)),
70
- };
71
- }
48
+ const from = { width: image.get_width(), height: image.get_height() };
49
+ const first = fittedSize(from, limits);
50
+ encoder = new PhotonEncoder(image, first);
51
+ return encodeToFit(encoder, from, first, mimeType, limits.maxBytes);
72
52
  }
73
53
  catch {
74
54
  // Photon throws for bytes it cannot decode.
75
55
  return undefined;
76
56
  }
77
57
  finally {
58
+ encoder?.free();
78
59
  image?.free();
79
60
  }
80
61
  }
81
- /**
82
- * `image` at `size` in the first encoding whose base64 fits `maxBytes`: PNG, then JPEG at falling qualities, or the
83
- * JPEG qualities first when `jpegFirst`; `undefined` if none fits.
84
- */
85
- function encodeWithin(image, size, maxBytes, jpegFirst) {
86
- const same = size.width === image.get_width() && size.height === image.get_height();
87
- const scaled = same ? image : resize(image, size.width, size.height, SamplingFilter.Lanczos3);
88
- try {
89
- const png = { mimeType: "image/png", encode: () => scaled.get_bytes() };
90
- const jpegs = JPEG_QUALITIES.map((quality) => ({
91
- mimeType: "image/jpeg",
92
- encode: () => scaled.get_bytes_jpeg(quality),
93
- }));
94
- for (const candidate of jpegFirst ? [...jpegs, png] : [png, ...jpegs]) {
95
- const bytes = candidate.encode();
96
- if (base64Length(bytes.byteLength) <= maxBytes)
97
- return { data: toBase64(bytes), mimeType: candidate.mimeType };
98
- }
99
- return undefined;
100
- }
101
- finally {
102
- if (!same)
103
- scaled.free();
104
- }
105
- }
106
62
  /**
107
63
  * The RGBA pixels of `image` turned upright for EXIF `orientation` 5 to 8, the orientations that swap width and
108
64
  * height. Photon's own `rotate` drops pixels at right angles, so the pixels are moved here.
@@ -122,4 +78,31 @@ function transposed(image, orientation) {
122
78
  }
123
79
  return { pixels, width: height, height: width };
124
80
  }
81
+ /** The upright image, resized from the original with Lanczos3 to the fitted size, then to each smaller one asked. */
82
+ class PhotonEncoder {
83
+ #image;
84
+ /** The resized copy, when the size differs from the original's. */
85
+ #scaled;
86
+ constructor(image, size) {
87
+ this.#image = image;
88
+ this.shrink(size);
89
+ }
90
+ shrink(size) {
91
+ this.free();
92
+ const same = size.width === this.#image.get_width() && size.height === this.#image.get_height();
93
+ if (!same)
94
+ this.#scaled = resize(this.#image, size.width, size.height, SamplingFilter.Lanczos3);
95
+ }
96
+ png() {
97
+ return (this.#scaled ?? this.#image).get_bytes();
98
+ }
99
+ jpeg(quality) {
100
+ return (this.#scaled ?? this.#image).get_bytes_jpeg(quality);
101
+ }
102
+ /** Frees the resized copy. */
103
+ free() {
104
+ this.#scaled?.free();
105
+ this.#scaled = undefined;
106
+ }
107
+ }
125
108
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/images/index.ts"],"names":[],"mappings":"AAAA,oGA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,MAAM,MAAM,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAC7C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACjC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE,EAAE,CAAC;YAChC,mEAAmE;YACnE,MAAM,IAAI,GAAG,WAAW,KAAK,CAAC,IAAI,WAAW,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,GAAG,CAAC,CAAC;YACzE,MAAM,IAAI,GAAG,WAAW,KAAK,CAAC,IAAI,WAAW,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,GAAG,CAAC,CAAC;YACxE,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,KAAK,GAAG,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,GAAG,KAAK,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,IAAI,GAAG,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;QACvG,CAAC;IACF,CAAC;IACD,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;AACjD,CAAC","sourcesContent":["// The package declares only `module`, which bundlers use but Node does not: import the file itself.\nimport {\n\tfliph,\n\tflipv,\n\tinitSync,\n\tPhotonImage,\n\tresize,\n\tSamplingFilter,\n\ttype SyncInitInput,\n} from \"@silvia-odwyer/photon/photon_rs.js\";\nimport type { ImageLimits, ImageProcessor, PreparedImage } from \"../tools/image-processor.ts\";\nimport { base64Length, INLINE_IMAGE_TYPES, toBase64 } from \"../tools/image-processor.ts\";\nimport { exifOrientation } from \"./exif.ts\";\n\n/** JPEG qualities tried in order. */\nconst JPEG_QUALITIES = [80, 70, 55, 40];\n\n/**\n * An `ImageProcessor` on Photon (Rust compiled to WebAssembly), for `createCodingTools({ images })`. `wasm` is\n * Photon's `photon_rs_bg.wasm` as bytes or as a compiled module: `@draht/durable/images/node` reads it from\n * the installed package, `@draht/durable/images/cloudflare` imports it as a Workers module. Elsewhere, such\n * as a browser, fetch the file and pass its bytes. Photon loads once per process; later calls reuse the first `wasm`.\n *\n * An image already upright, in a format providers take inline, and within the limits is returned as it is, once it\n * decodes. Otherwise it is turned upright by its EXIF orientation, scaled to the\n * maximum width and height, and encoded as PNG or JPEG at falling qualities (JPEG first for JPEG sources), then at\n * smaller dimensions, 3/4 at a time, until the base64 fits. Formats providers do not take inline (BMP) become PNG.\n *\n * The work runs on the calling thread: about a second and a half for a 12-megapixel photo. Decoding takes the image's\n * RGBA size in WebAssembly memory, which does not shrink again; leave the processor out on memory-constrained hosts.\n */\nexport function createPhotonImages(wasm: SyncInitInput): ImageProcessor {\n\tinitSync({ module: wasm });\n\treturn { prepare: async (bytes, mimeType, limits) => prepare(bytes, mimeType, limits) };\n}\n\nfunction prepare(bytes: Uint8Array, mimeType: string, limits: ImageLimits): PreparedImage | undefined {\n\tconst orientation = exifOrientation(bytes);\n\tconst inline = INLINE_IMAGE_TYPES.has(mimeType);\n\tlet image: PhotonImage | undefined;\n\ttry {\n\t\t// Decoded even when it is returned as it is: a damaged file is an error, not an image the provider rejects.\n\t\timage = PhotonImage.new_from_byteslice(bytes);\n\t\tif (\n\t\t\tinline &&\n\t\t\torientation === 1 &&\n\t\t\timage.get_width() <= limits.maxWidth &&\n\t\t\timage.get_height() <= limits.maxHeight &&\n\t\t\tbase64Length(bytes.byteLength) <= limits.maxBytes\n\t\t) {\n\t\t\treturn { data: toBase64(bytes), mimeType };\n\t\t}\n\t\tif (orientation >= 5) {\n\t\t\tconst upright = transposed(image, orientation);\n\t\t\t// Freed first, so the upright copy reuses its WebAssembly memory.\n\t\t\timage.free();\n\t\t\timage = undefined;\n\t\t\timage = new PhotonImage(upright.pixels, upright.width, upright.height);\n\t\t} else if (orientation !== 1) {\n\t\t\tif (orientation !== 4) fliph(image);\n\t\t\tif (orientation !== 2) flipv(image);\n\t\t}\n\t\tconst width = image.get_width();\n\t\tconst height = image.get_height();\n\t\tconst scale = Math.min(1, limits.maxWidth / width, limits.maxHeight / height);\n\t\tlet target = { width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)) };\n\t\tfor (;;) {\n\t\t\tconst encoded = encodeWithin(image, target, limits.maxBytes, mimeType === \"image/jpeg\");\n\t\t\tif (encoded !== undefined) {\n\t\t\t\tconst resized =\n\t\t\t\t\ttarget.width === width && target.height === height\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { resized: { from: { width, height }, to: target } };\n\t\t\t\tconst converted = encoded.mimeType === mimeType ? {} : { convertedFrom: mimeType };\n\t\t\t\treturn { ...encoded, ...converted, ...resized };\n\t\t\t}\n\t\t\tif (target.width === 1 && target.height === 1) return undefined;\n\t\t\ttarget = {\n\t\t\t\twidth: Math.max(1, Math.floor(target.width * 0.75)),\n\t\t\t\theight: Math.max(1, Math.floor(target.height * 0.75)),\n\t\t\t};\n\t\t}\n\t} catch {\n\t\t// Photon throws for bytes it cannot decode.\n\t\treturn undefined;\n\t} finally {\n\t\timage?.free();\n\t}\n}\n\n/**\n * `image` at `size` in the first encoding whose base64 fits `maxBytes`: PNG, then JPEG at falling qualities, or the\n * JPEG qualities first when `jpegFirst`; `undefined` if none fits.\n */\nfunction encodeWithin(\n\timage: PhotonImage,\n\tsize: { readonly width: number; readonly height: number },\n\tmaxBytes: number,\n\tjpegFirst: boolean,\n): { readonly data: string; readonly mimeType: string } | undefined {\n\tconst same = size.width === image.get_width() && size.height === image.get_height();\n\tconst scaled = same ? image : resize(image, size.width, size.height, SamplingFilter.Lanczos3);\n\ttry {\n\t\tconst png = { mimeType: \"image/png\", encode: () => scaled.get_bytes() };\n\t\tconst jpegs = JPEG_QUALITIES.map((quality) => ({\n\t\t\tmimeType: \"image/jpeg\",\n\t\t\tencode: () => scaled.get_bytes_jpeg(quality),\n\t\t}));\n\t\tfor (const candidate of jpegFirst ? [...jpegs, png] : [png, ...jpegs]) {\n\t\t\tconst bytes = candidate.encode();\n\t\t\tif (base64Length(bytes.byteLength) <= maxBytes) return { data: toBase64(bytes), mimeType: candidate.mimeType };\n\t\t}\n\t\treturn undefined;\n\t} finally {\n\t\tif (!same) scaled.free();\n\t}\n}\n\n/**\n * The RGBA pixels of `image` turned upright for EXIF `orientation` 5 to 8, the orientations that swap width and\n * height. Photon's own `rotate` drops pixels at right angles, so the pixels are moved here.\n */\nfunction transposed(\n\timage: PhotonImage,\n\torientation: number,\n): { readonly pixels: Uint8Array; readonly width: number; readonly height: number } {\n\tconst width = image.get_width();\n\tconst height = image.get_height();\n\tconst source = image.get_raw_pixels();\n\tconst pixels = new Uint8Array(source.length);\n\tfor (let y = 0; y < height; y++) {\n\t\tfor (let x = 0; x < width; x++) {\n\t\t\t// Where (x, y) lands in the upright image, which is `height` wide.\n\t\t\tconst outX = orientation === 5 || orientation === 8 ? y : height - 1 - y;\n\t\t\tconst outY = orientation === 5 || orientation === 6 ? x : width - 1 - x;\n\t\t\tpixels.set(source.subarray((y * width + x) * 4, (y * width + x) * 4 + 4), (outY * height + outX) * 4);\n\t\t}\n\t}\n\treturn { pixels, width: height, height: width };\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/images/index.ts"],"names":[],"mappings":"AAAA,oGAAoG;AACpG,OAAO,EACN,KAAK,EACL,KAAK,EACL,QAAQ,EACR,WAAW,EACX,MAAM,EACN,cAAc,GAEd,MAAM,oCAAoC,CAAC;AAE5C,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,UAAU,EAAqC,aAAa,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AACtH,OAAO,EAA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EAAE,cAAc,CAAC,QAAQ,CAAC,CAAC;IACjG,CAAC;IAED,GAAG;QACF,OAAO,CAAC,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,CAAC;IAClD,CAAC;IAED,IAAI,CAAC,OAAe;QACnB,OAAO,CAAC,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,MAAM,CAAC,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC;IAC9D,CAAC;IAED,8BAA8B;IAC9B,IAAI;QACH,IAAI,CAAC,OAAO,EAAE,IAAI,EAAE,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,SAAS,CAAC;IAC1B,CAAC;CACD","sourcesContent":["// The package declares only `module`, which bundlers use but Node does not: import the file itself.\nimport {\n\tfliph,\n\tflipv,\n\tinitSync,\n\tPhotonImage,\n\tresize,\n\tSamplingFilter,\n\ttype SyncInitInput,\n} from \"@silvia-odwyer/photon/photon_rs.js\";\nimport type { ImageLimits, ImageProcessor, PreparedImage } from \"../tools/image-processor.ts\";\nimport { toBase64 } from \"../tools/image-processor.ts\";\nimport { encodeToFit, fittedSize, type ImageEncoder, type ImageSize, mayReturnAsIs, withinLimits } from \"./encode.ts\";\nimport { exifOrientation } from \"./exif.ts\";\n\n/**\n * An `ImageProcessor` on Photon (Rust compiled to WebAssembly), for `createCodingTools({ images })`. `wasm` is\n * Photon's `photon_rs_bg.wasm` as bytes or as a compiled module: `@draht/durable/images/node` reads it from\n * the installed package, `@draht/durable/images/cloudflare` imports it as a Workers module. Elsewhere, such\n * as a browser, fetch the file and pass its bytes. Photon loads once per process; later calls reuse the first `wasm`.\n *\n * An image already upright, in a format providers take inline that its bytes are, and within the limits is returned as\n * it is, once it decodes. Otherwise it is turned upright by its EXIF orientation, scaled to the maximum width and\n * height, and encoded as PNG or JPEG at falling qualities (JPEG first for JPEG sources), then at smaller dimensions,\n * 3/4 at a time, until the base64 fits. Formats providers do not take inline (BMP) become PNG.\n *\n * The work runs on the calling thread: about a second and a half for a 12-megapixel photo. Decoding takes the image's\n * RGBA size in WebAssembly memory, which does not shrink again; leave the processor out on memory-constrained hosts.\n */\nexport function createPhotonImages(wasm: SyncInitInput): ImageProcessor {\n\tinitSync({ module: wasm });\n\treturn { prepare: async (bytes, mimeType, limits) => prepare(bytes, mimeType, limits) };\n}\n\nfunction prepare(bytes: Uint8Array, mimeType: string, limits: ImageLimits): PreparedImage | undefined {\n\tconst orientation = exifOrientation(bytes);\n\tlet image: PhotonImage | undefined;\n\tlet encoder: PhotonEncoder | undefined;\n\ttry {\n\t\t// Decoded even when it is returned as it is: a damaged file is an error, not an image the provider rejects.\n\t\timage = PhotonImage.new_from_byteslice(bytes);\n\t\tconst stored = { width: image.get_width(), height: image.get_height() };\n\t\tif (mayReturnAsIs(bytes, mimeType, orientation, limits) && withinLimits(stored, limits)) {\n\t\t\treturn { data: toBase64(bytes), mimeType };\n\t\t}\n\t\tif (orientation >= 5) {\n\t\t\tconst upright = transposed(image, orientation);\n\t\t\t// Freed first, so the upright copy reuses its WebAssembly memory.\n\t\t\timage.free();\n\t\t\timage = undefined;\n\t\t\timage = new PhotonImage(upright.pixels, upright.width, upright.height);\n\t\t} else if (orientation !== 1) {\n\t\t\tif (orientation !== 4) fliph(image);\n\t\t\tif (orientation !== 2) flipv(image);\n\t\t}\n\t\tconst from = { width: image.get_width(), height: image.get_height() };\n\t\tconst first = fittedSize(from, limits);\n\t\tencoder = new PhotonEncoder(image, first);\n\t\treturn encodeToFit(encoder, from, first, mimeType, limits.maxBytes);\n\t} catch {\n\t\t// Photon throws for bytes it cannot decode.\n\t\treturn undefined;\n\t} finally {\n\t\tencoder?.free();\n\t\timage?.free();\n\t}\n}\n\n/**\n * The RGBA pixels of `image` turned upright for EXIF `orientation` 5 to 8, the orientations that swap width and\n * height. Photon's own `rotate` drops pixels at right angles, so the pixels are moved here.\n */\nfunction transposed(\n\timage: PhotonImage,\n\torientation: number,\n): { readonly pixels: Uint8Array; readonly width: number; readonly height: number } {\n\tconst width = image.get_width();\n\tconst height = image.get_height();\n\tconst source = image.get_raw_pixels();\n\tconst pixels = new Uint8Array(source.length);\n\tfor (let y = 0; y < height; y++) {\n\t\tfor (let x = 0; x < width; x++) {\n\t\t\t// Where (x, y) lands in the upright image, which is `height` wide.\n\t\t\tconst outX = orientation === 5 || orientation === 8 ? y : height - 1 - y;\n\t\t\tconst outY = orientation === 5 || orientation === 6 ? x : width - 1 - x;\n\t\t\tpixels.set(source.subarray((y * width + x) * 4, (y * width + x) * 4 + 4), (outY * height + outX) * 4);\n\t\t}\n\t}\n\treturn { pixels, width: height, height: width };\n}\n\n/** The upright image, resized from the original with Lanczos3 to the fitted size, then to each smaller one asked. */\nclass PhotonEncoder implements ImageEncoder {\n\treadonly #image: PhotonImage;\n\t/** The resized copy, when the size differs from the original's. */\n\t#scaled: PhotonImage | undefined;\n\n\tconstructor(image: PhotonImage, size: ImageSize) {\n\t\tthis.#image = image;\n\t\tthis.shrink(size);\n\t}\n\n\tshrink(size: ImageSize): void {\n\t\tthis.free();\n\t\tconst same = size.width === this.#image.get_width() && size.height === this.#image.get_height();\n\t\tif (!same) this.#scaled = resize(this.#image, size.width, size.height, SamplingFilter.Lanczos3);\n\t}\n\n\tpng(): Uint8Array {\n\t\treturn (this.#scaled ?? this.#image).get_bytes();\n\t}\n\n\tjpeg(quality: number): Uint8Array {\n\t\treturn (this.#scaled ?? this.#image).get_bytes_jpeg(quality);\n\t}\n\n\t/** Frees the resized copy. */\n\tfree(): void {\n\t\tthis.#scaled?.free();\n\t\tthis.#scaled = undefined;\n\t}\n}\n"]}
@@ -1,19 +1,2 @@
1
- import type { ImageLimits, PreparedImage } from "../tools/image-processor.ts";
2
- /** One request: the image to prepare, and its ID for the reply. */
3
- export type PrepareRequest = {
4
- readonly id: number;
5
- readonly bytes: Uint8Array;
6
- readonly mimeType: string;
7
- readonly limits: ImageLimits;
8
- };
9
- /** The reply to a request: its result, or why it failed. */
10
- export type PrepareReply = {
11
- readonly kind: "prepared";
12
- readonly id: number;
13
- readonly result: PreparedImage | undefined;
14
- } | {
15
- readonly kind: "failed";
16
- readonly id: number;
17
- readonly error: string;
18
- };
1
+ export {};
19
2
  //# sourceMappingURL=node-worker.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"node-worker.d.ts","sourceRoot":"","sources":["../../src/images/node-worker.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAG9E,mEAAmE;AACnE,MAAM,MAAM,cAAc,GAAG;IAC5B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAC;IAC3B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC;CAC7B,CAAC;AAEF,4DAA4D;AAC5D,MAAM,MAAM,YAAY,GACrB;IAAE,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC;IAAC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,aAAa,GAAG,SAAS,CAAA;CAAE,GAC9F;IAAE,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC;IAAC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC"}
1
+ {"version":3,"file":"node-worker.d.ts","sourceRoot":"","sources":["../../src/images/node-worker.ts"],"names":[],"mappings":""}
@@ -1,17 +1,7 @@
1
1
  // The worker thread of `createNodePhotonImages()`: Photon prepares images here, off the caller's event loop.
2
2
  import { readFileSync } from "node:fs";
3
3
  import { createRequire } from "node:module";
4
- import { parentPort } from "node:worker_threads";
5
4
  import { createPhotonImages } from "./index.js";
6
- const port = parentPort;
7
- if (port === null)
8
- throw new Error("The Photon image worker needs a parent thread");
9
- const images = createPhotonImages(readFileSync(createRequire(import.meta.url).resolve("@silvia-odwyer/photon/photon_rs_bg.wasm")));
10
- port.on("message", (request) => {
11
- void images.prepare(request.bytes, request.mimeType, request.limits).then((result) => port.postMessage({ kind: "prepared", id: request.id, result }), (error) => port.postMessage({
12
- kind: "failed",
13
- id: request.id,
14
- error: error instanceof Error ? error.message : String(error),
15
- }));
16
- });
5
+ import { serveImages } from "./thread.js";
6
+ serveImages(createPhotonImages(readFileSync(createRequire(import.meta.url).resolve("@silvia-odwyer/photon/photon_rs_bg.wasm"))));
17
7
  //# sourceMappingURL=node-worker.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"node-worker.js","sourceRoot":"","sources":["../../src/images/node-worker.ts"],"names":[],"mappings":"AAAA,6GAA6G;AAC7G,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAEjD,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAehD,MAAM,IAAI,GAAG,UAAU,CAAC;AACxB,IAAI,IAAI,KAAK,IAAI;IAAE,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;AACpF,MAAM,MAAM,GAAG,kBAAkB,CAChC,YAAY,CAAC,aAAa,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,yCAAyC,CAAC,CAAC,CAC/F,CAAC;AACF,IAAI,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,OAAuB,EAAE,EAAE;IAC9C,KAAK,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,QAAQ,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,IAAI,CACxE,CAAC,MAAM,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,IAAI,EAAE,UAAU,EAAE,EAAE,EAAE,OAAO,CAAC,EAAE,EAAE,MAAM,EAAyB,CAAC,EACjG,CAAC,KAAc,EAAE,EAAE,CAClB,IAAI,CAAC,WAAW,CAAC;QAChB,IAAI,EAAE,QAAQ;QACd,EAAE,EAAE,OAAO,CAAC,EAAE;QACd,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;KACtC,CAAC,CAC1B,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["// The worker thread of `createNodePhotonImages()`: Photon prepares images here, off the caller's event loop.\nimport { readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { parentPort } from \"node:worker_threads\";\nimport type { ImageLimits, PreparedImage } from \"../tools/image-processor.ts\";\nimport { createPhotonImages } from \"./index.ts\";\n\n/** One request: the image to prepare, and its ID for the reply. */\nexport type PrepareRequest = {\n\treadonly id: number;\n\treadonly bytes: Uint8Array;\n\treadonly mimeType: string;\n\treadonly limits: ImageLimits;\n};\n\n/** The reply to a request: its result, or why it failed. */\nexport type PrepareReply =\n\t| { readonly kind: \"prepared\"; readonly id: number; readonly result: PreparedImage | undefined }\n\t| { readonly kind: \"failed\"; readonly id: number; readonly error: string };\n\nconst port = parentPort;\nif (port === null) throw new Error(\"The Photon image worker needs a parent thread\");\nconst images = createPhotonImages(\n\treadFileSync(createRequire(import.meta.url).resolve(\"@silvia-odwyer/photon/photon_rs_bg.wasm\")),\n);\nport.on(\"message\", (request: PrepareRequest) => {\n\tvoid images.prepare(request.bytes, request.mimeType, request.limits).then(\n\t\t(result) => port.postMessage({ kind: \"prepared\", id: request.id, result } satisfies PrepareReply),\n\t\t(error: unknown) =>\n\t\t\tport.postMessage({\n\t\t\t\tkind: \"failed\",\n\t\t\t\tid: request.id,\n\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t} satisfies PrepareReply),\n\t);\n});\n"]}
1
+ {"version":3,"file":"node-worker.js","sourceRoot":"","sources":["../../src/images/node-worker.ts"],"names":[],"mappings":"AAAA,6GAA6G;AAC7G,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,WAAW,CACV,kBAAkB,CAAC,YAAY,CAAC,aAAa,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,yCAAyC,CAAC,CAAC,CAAC,CACnH,CAAC","sourcesContent":["// The worker thread of `createNodePhotonImages()`: Photon prepares images here, off the caller's event loop.\nimport { readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { createPhotonImages } from \"./index.ts\";\nimport { serveImages } from \"./thread.ts\";\n\nserveImages(\n\tcreatePhotonImages(readFileSync(createRequire(import.meta.url).resolve(\"@silvia-odwyer/photon/photon_rs_bg.wasm\"))),\n);\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../../src/images/node.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAe,cAAc,EAAiB,MAAM,6BAA6B,CAAC;AAI9F,MAAM,MAAM,uBAAuB,GAAG;IACrC;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;IAC1B;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CACzB,CAAC;AAEF;;;;;GAKG;AACH,wBAAsB,sBAAsB,CAAC,OAAO,GAAE,uBAA4B,GAAG,OAAO,CAAC,cAAc,CAAC,CAqB3G"}
1
+ {"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../../src/images/node.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAIlE,MAAM,MAAM,uBAAuB,GAAG;IACrC;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;IAC1B;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CACzB,CAAC;AAEF;;;;;GAKG;AACH,wBAAsB,sBAAsB,CAAC,OAAO,GAAE,uBAA4B,GAAG,OAAO,CAAC,cAAc,CAAC,CAK3G"}
@@ -1,7 +1,7 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import { createRequire } from "node:module";
3
- import { Worker } from "node:worker_threads";
4
3
  import { createPhotonImages } from "./index.js";
4
+ import { threadedImages } from "./thread.js";
5
5
  /**
6
6
  * `createPhotonImages()` for Node and Bun, with Photon's WebAssembly read from the installed `@silvia-odwyer/photon`,
7
7
  * by default in a worker thread that keeps the process alive only while it prepares an image. A worker that cannot
@@ -11,111 +11,12 @@ import { createPhotonImages } from "./index.js";
11
11
  export async function createNodePhotonImages(options = {}) {
12
12
  if (options.worker === false)
13
13
  return inProcess();
14
- const idleMs = options.idleMs ?? 30_000;
15
- let thread;
16
- let fallback;
17
- return {
18
- async prepare(bytes, mimeType, limits) {
19
- if (fallback !== undefined)
20
- return (await fallback).prepare(bytes, mimeType, limits);
21
- try {
22
- thread ??= new PhotonThread(idleMs, () => {
23
- thread = undefined;
24
- });
25
- return await thread.prepare(bytes, mimeType, limits);
26
- }
27
- catch (error) {
28
- if (!(error instanceof WorkerUnavailable))
29
- throw error;
30
- // No worker on this platform or build: prepare here from now on.
31
- fallback = inProcess();
32
- return (await fallback).prepare(bytes, mimeType, limits);
33
- }
34
- },
35
- };
14
+ // Run from source under a TypeScript runtime, as in tests; built, the worker sits next to this file as JS.
15
+ const file = new URL(import.meta.url.endsWith(".ts") ? "./node-worker.ts" : "./node-worker.js", import.meta.url);
16
+ return threadedImages(file, options.idleMs ?? 30_000, inProcess);
36
17
  }
37
18
  async function inProcess() {
38
19
  const path = createRequire(import.meta.url).resolve("@silvia-odwyer/photon/photon_rs_bg.wasm");
39
20
  return createPhotonImages(await readFile(path));
40
21
  }
41
- /** The worker could not start, as opposed to failing on one image. */
42
- class WorkerUnavailable extends Error {
43
- }
44
- /** One worker thread and the requests it has not answered; it exits after `idleMs` without requests. */
45
- class PhotonThread {
46
- #worker;
47
- #pending = new Map();
48
- #idleMs;
49
- #onExit;
50
- #nextId = 0;
51
- #idle;
52
- /** Whether the worker answered once: a failure before that means it is unavailable. */
53
- #started = false;
54
- constructor(idleMs, onExit) {
55
- this.#idleMs = idleMs;
56
- this.#onExit = onExit;
57
- // Run from source under a TypeScript runtime, as in tests; built, the worker sits next to this file as JS.
58
- const file = import.meta.url.endsWith(".ts") ? "./node-worker.ts" : "./node-worker.js";
59
- try {
60
- this.#worker = new Worker(new URL(file, import.meta.url));
61
- }
62
- catch (error) {
63
- throw new WorkerUnavailable("The Photon image worker cannot start", { cause: error });
64
- }
65
- this.#worker.unref();
66
- this.#worker.on("message", (reply) => {
67
- this.#started = true;
68
- const request = this.#pending.get(reply.id);
69
- if (request === undefined)
70
- return;
71
- this.#pending.delete(reply.id);
72
- if (reply.kind === "failed")
73
- request.reject(new Error(reply.error));
74
- else
75
- request.resolve(reply.result);
76
- this.#settled();
77
- });
78
- const fail = (error) => {
79
- const failure = this.#started
80
- ? error
81
- : new WorkerUnavailable("The Photon image worker cannot start", { cause: error });
82
- for (const request of this.#pending.values())
83
- request.reject(failure);
84
- this.#pending.clear();
85
- this.#exit();
86
- };
87
- this.#worker.on("error", fail);
88
- this.#worker.on("exit", (code) => fail(new Error(`The Photon image worker exited with code ${code}`)));
89
- }
90
- prepare(bytes, mimeType, limits) {
91
- const id = this.#nextId++;
92
- const request = Promise.withResolvers();
93
- this.#pending.set(id, request);
94
- if (this.#idle !== undefined)
95
- clearTimeout(this.#idle);
96
- this.#idle = undefined;
97
- // A pending image keeps the process alive, as one prepared on the calling thread would.
98
- this.#worker.ref();
99
- // A copy, transferred: the caller keeps its bytes.
100
- const copy = bytes.slice();
101
- this.#worker.postMessage({ id, bytes: copy, mimeType, limits }, [copy.buffer]);
102
- return request.promise;
103
- }
104
- #settled() {
105
- if (this.#pending.size > 0)
106
- return;
107
- this.#worker.unref();
108
- this.#idle = setTimeout(() => {
109
- this.#exit();
110
- void this.#worker.terminate();
111
- }, this.#idleMs);
112
- this.#idle.unref();
113
- }
114
- #exit() {
115
- if (this.#idle !== undefined)
116
- clearTimeout(this.#idle);
117
- this.#idle = undefined;
118
- this.#onExit();
119
- }
120
- }
121
22
  //# sourceMappingURL=node.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"node.js","sourceRoot":"","sources":["../../src/images/node.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAE7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAgBhD;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAAC,OAAO,GAA4B,EAAE;IACjF,IAAI,OAAO,CAAC,MAAM,KAAK,KAAK;QAAE,OAAO,SAAS,EAAE,CAAC;IACjD,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,MAAM,CAAC;IACxC,IAAI,MAAgC,CAAC;IACrC,IAAI,QAA6C,CAAC;IAClD,OAAO;QACN,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM;YACpC,IAAI,QAAQ,KAAK,SAAS;gBAAE,OAAO,CAAC,MAAM,QAAQ,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;YACrF,IAAI,CAAC;gBACJ,MAAM,KAAK,IAAI,YAAY,CAAC,MAAM,EAAE,GAAG,EAAE;oBACxC,MAAM,GAAG,SAAS,CAAC;gBACpB,CAAC,CAAC,CAAC;gBACH,OAAO,MAAM,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE,QAAQ,EAAE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,CAAC,OAAO,CAAC,CAAC;QACjB,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;IACpB,CAAC;IAED,KAAK;QACJ,IAAI,IAAI,CAAC,KAAK,KAAK,SAAS;YAAE,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACvD,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC;QACvB,IAAI,CAAC,OAAO,EAAE,CAAC;IAChB,CAAC;CACD","sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { Worker } from \"node:worker_threads\";\nimport type { ImageLimits, ImageProcessor, PreparedImage } from \"../tools/image-processor.ts\";\nimport { createPhotonImages } from \"./index.ts\";\nimport type { PrepareReply, PrepareRequest } from \"./node-worker.ts\";\n\nexport type NodePhotonImagesOptions = {\n\t/**\n\t * Prepare images in a worker thread, so a large photo does not block the event loop for the second or two Photon\n\t * takes. Default `true`; `false` prepares them on the calling thread.\n\t */\n\treadonly worker?: boolean;\n\t/**\n\t * How long the worker stays after its last image before it exits, freeing Photon's WebAssembly memory, which never\n\t * shrinks while it lives. The next image starts a new one. Default 30 s.\n\t */\n\treadonly idleMs?: number;\n};\n\n/**\n * `createPhotonImages()` for Node and Bun, with Photon's WebAssembly read from the installed `@silvia-odwyer/photon`,\n * by default in a worker thread that keeps the process alive only while it prepares an image. A worker that cannot\n * start falls back to the calling thread. A single-file binary cannot resolve the package: read its own copy of\n * `photon_rs_bg.wasm` and call `createPhotonImages()`.\n */\nexport async function createNodePhotonImages(options: NodePhotonImagesOptions = {}): Promise<ImageProcessor> {\n\tif (options.worker === false) return inProcess();\n\tconst idleMs = options.idleMs ?? 30_000;\n\tlet thread: PhotonThread | undefined;\n\tlet fallback: Promise<ImageProcessor> | undefined;\n\treturn {\n\t\tasync prepare(bytes, mimeType, limits) {\n\t\t\tif (fallback !== undefined) return (await fallback).prepare(bytes, mimeType, limits);\n\t\t\ttry {\n\t\t\t\tthread ??= new PhotonThread(idleMs, () => {\n\t\t\t\t\tthread = undefined;\n\t\t\t\t});\n\t\t\t\treturn await thread.prepare(bytes, mimeType, limits);\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof WorkerUnavailable)) throw error;\n\t\t\t\t// No worker on this platform or build: prepare here from now on.\n\t\t\t\tfallback = inProcess();\n\t\t\t\treturn (await fallback).prepare(bytes, mimeType, limits);\n\t\t\t}\n\t\t},\n\t};\n}\n\nasync function inProcess(): Promise<ImageProcessor> {\n\tconst path = createRequire(import.meta.url).resolve(\"@silvia-odwyer/photon/photon_rs_bg.wasm\");\n\treturn createPhotonImages(await readFile(path));\n}\n\n/** The worker could not start, as opposed to failing on one image. */\nclass WorkerUnavailable extends Error {}\n\n/** One worker thread and the requests it has not answered; it exits after `idleMs` without requests. */\nclass PhotonThread {\n\treadonly #worker: Worker;\n\treadonly #pending = new Map<number, PromiseWithResolvers<PreparedImage | undefined>>();\n\treadonly #idleMs: number;\n\treadonly #onExit: () => void;\n\t#nextId = 0;\n\t#idle: ReturnType<typeof setTimeout> | undefined;\n\t/** Whether the worker answered once: a failure before that means it is unavailable. */\n\t#started = false;\n\n\tconstructor(idleMs: number, onExit: () => void) {\n\t\tthis.#idleMs = idleMs;\n\t\tthis.#onExit = onExit;\n\t\t// Run from source under a TypeScript runtime, as in tests; built, the worker sits next to this file as JS.\n\t\tconst file = import.meta.url.endsWith(\".ts\") ? \"./node-worker.ts\" : \"./node-worker.js\";\n\t\ttry {\n\t\t\tthis.#worker = new Worker(new URL(file, import.meta.url));\n\t\t} catch (error) {\n\t\t\tthrow new WorkerUnavailable(\"The Photon image worker cannot start\", { cause: error });\n\t\t}\n\t\tthis.#worker.unref();\n\t\tthis.#worker.on(\"message\", (reply: PrepareReply) => {\n\t\t\tthis.#started = true;\n\t\t\tconst request = this.#pending.get(reply.id);\n\t\t\tif (request === undefined) return;\n\t\t\tthis.#pending.delete(reply.id);\n\t\t\tif (reply.kind === \"failed\") request.reject(new Error(reply.error));\n\t\t\telse request.resolve(reply.result);\n\t\t\tthis.#settled();\n\t\t});\n\t\tconst fail = (error: unknown): void => {\n\t\t\tconst failure = this.#started\n\t\t\t\t? error\n\t\t\t\t: new WorkerUnavailable(\"The Photon image worker cannot start\", { cause: error });\n\t\t\tfor (const request of this.#pending.values()) request.reject(failure);\n\t\t\tthis.#pending.clear();\n\t\t\tthis.#exit();\n\t\t};\n\t\tthis.#worker.on(\"error\", fail);\n\t\tthis.#worker.on(\"exit\", (code) => fail(new Error(`The Photon image worker exited with code ${code}`)));\n\t}\n\n\tprepare(bytes: Uint8Array, mimeType: string, limits: ImageLimits): Promise<PreparedImage | undefined> {\n\t\tconst id = this.#nextId++;\n\t\tconst request = Promise.withResolvers<PreparedImage | undefined>();\n\t\tthis.#pending.set(id, request);\n\t\tif (this.#idle !== undefined) clearTimeout(this.#idle);\n\t\tthis.#idle = undefined;\n\t\t// A pending image keeps the process alive, as one prepared on the calling thread would.\n\t\tthis.#worker.ref();\n\t\t// A copy, transferred: the caller keeps its bytes.\n\t\tconst copy = bytes.slice();\n\t\tthis.#worker.postMessage({ id, bytes: copy, mimeType, limits } satisfies PrepareRequest, [copy.buffer]);\n\t\treturn request.promise;\n\t}\n\n\t#settled(): void {\n\t\tif (this.#pending.size > 0) return;\n\t\tthis.#worker.unref();\n\t\tthis.#idle = setTimeout(() => {\n\t\t\tthis.#exit();\n\t\t\tvoid this.#worker.terminate();\n\t\t}, this.#idleMs);\n\t\tthis.#idle.unref();\n\t}\n\n\t#exit(): void {\n\t\tif (this.#idle !== undefined) clearTimeout(this.#idle);\n\t\tthis.#idle = undefined;\n\t\tthis.#onExit();\n\t}\n}\n"]}
1
+ {"version":3,"file":"node.js","sourceRoot":"","sources":["../../src/images/node.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE5C,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAe7C;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAAC,OAAO,GAA4B,EAAE;IACjF,IAAI,OAAO,CAAC,MAAM,KAAK,KAAK;QAAE,OAAO,SAAS,EAAE,CAAC;IACjD,2GAA2G;IAC3G,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,kBAAkB,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;IACjH,OAAO,cAAc,CAAC,IAAI,EAAE,OAAO,CAAC,MAAM,IAAI,MAAM,EAAE,SAAS,CAAC,CAAC;AAClE,CAAC;AAED,KAAK,UAAU,SAAS;IACvB,MAAM,IAAI,GAAG,aAAa,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,yCAAyC,CAAC,CAAC;IAC/F,OAAO,kBAAkB,CAAC,MAAM,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;AACjD,CAAC","sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport type { ImageProcessor } from \"../tools/image-processor.ts\";\nimport { createPhotonImages } from \"./index.ts\";\nimport { threadedImages } from \"./thread.ts\";\n\nexport type NodePhotonImagesOptions = {\n\t/**\n\t * Prepare images in a worker thread, so a large photo does not block the event loop for the second or two Photon\n\t * takes. Default `true`; `false` prepares them on the calling thread.\n\t */\n\treadonly worker?: boolean;\n\t/**\n\t * How long the worker stays after its last image before it exits, freeing Photon's WebAssembly memory, which never\n\t * shrinks while it lives. The next image starts a new one. Default 30 s.\n\t */\n\treadonly idleMs?: number;\n};\n\n/**\n * `createPhotonImages()` for Node and Bun, with Photon's WebAssembly read from the installed `@silvia-odwyer/photon`,\n * by default in a worker thread that keeps the process alive only while it prepares an image. A worker that cannot\n * start falls back to the calling thread. A single-file binary cannot resolve the package: read its own copy of\n * `photon_rs_bg.wasm` and call `createPhotonImages()`.\n */\nexport async function createNodePhotonImages(options: NodePhotonImagesOptions = {}): Promise<ImageProcessor> {\n\tif (options.worker === false) return inProcess();\n\t// Run from source under a TypeScript runtime, as in tests; built, the worker sits next to this file as JS.\n\tconst file = new URL(import.meta.url.endsWith(\".ts\") ? \"./node-worker.ts\" : \"./node-worker.js\", import.meta.url);\n\treturn threadedImages(file, options.idleMs ?? 30_000, inProcess);\n}\n\nasync function inProcess(): Promise<ImageProcessor> {\n\tconst path = createRequire(import.meta.url).resolve(\"@silvia-odwyer/photon/photon_rs_bg.wasm\");\n\treturn createPhotonImages(await readFile(path));\n}\n"]}
@@ -0,0 +1,8 @@
1
+ import type { ImageProcessor } from "../../tools/image-processor.ts";
2
+ /**
3
+ * `createPiImages()` for Cloudflare Workers and Durable Objects, built with Wrangler. The instance goes at the next
4
+ * macrotask after the last image (`idleMs: 0`): Durable arms no timer that only frees memory in Workers, where a
5
+ * pending one keeps a Durable Object from hibernating; a 0 ms timer fires at once.
6
+ */
7
+ export declare function createCloudflarePiImages(): ImageProcessor;
8
+ //# sourceMappingURL=cloudflare.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloudflare.d.ts","sourceRoot":"","sources":["../../../src/images/pi-images/cloudflare.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAGrE;;;;GAIG;AACH,wBAAgB,wBAAwB,IAAI,cAAc,CAEzD"}
@@ -0,0 +1,14 @@
1
+ // `@draht/durable/images/pi-images/cloudflare`. Wrangler's default `CompiledWasm` rule turns this import
2
+ // into a `WebAssembly.Module`; Workers cannot compile WebAssembly from bytes at runtime. Other bundlers do not support
3
+ // it: use `createPiImages()` there.
4
+ import piImagesWasm from "@earendil-works/pi-images/pi-images.wasm";
5
+ import { createPiImages } from "./index.js";
6
+ /**
7
+ * `createPiImages()` for Cloudflare Workers and Durable Objects, built with Wrangler. The instance goes at the next
8
+ * macrotask after the last image (`idleMs: 0`): Durable arms no timer that only frees memory in Workers, where a
9
+ * pending one keeps a Durable Object from hibernating; a 0 ms timer fires at once.
10
+ */
11
+ export function createCloudflarePiImages() {
12
+ return createPiImages(piImagesWasm, { idleMs: 0 });
13
+ }
14
+ //# sourceMappingURL=cloudflare.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloudflare.js","sourceRoot":"","sources":["../../../src/images/pi-images/cloudflare.ts"],"names":[],"mappings":"AAAA,yGAAyG;AACzG,uHAAuH;AACvH,oCAAoC;AACpC,OAAO,YAAY,MAAM,0CAA0C,CAAC;AAEpE,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAE5C;;;;GAIG;AACH,MAAM,UAAU,wBAAwB;IACvC,OAAO,cAAc,CAAC,YAAY,EAAE,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC;AACpD,CAAC","sourcesContent":["// `@draht/durable/images/pi-images/cloudflare`. Wrangler's default `CompiledWasm` rule turns this import\n// into a `WebAssembly.Module`; Workers cannot compile WebAssembly from bytes at runtime. Other bundlers do not support\n// it: use `createPiImages()` there.\nimport piImagesWasm from \"@earendil-works/pi-images/pi-images.wasm\";\nimport type { ImageProcessor } from \"../../tools/image-processor.ts\";\nimport { createPiImages } from \"./index.ts\";\n\n/**\n * `createPiImages()` for Cloudflare Workers and Durable Objects, built with Wrangler. The instance goes at the next\n * macrotask after the last image (`idleMs: 0`): Durable arms no timer that only frees memory in Workers, where a\n * pending one keeps a Durable Object from hibernating; a 0 ms timer fires at once.\n */\nexport function createCloudflarePiImages(): ImageProcessor {\n\treturn createPiImages(piImagesWasm, { idleMs: 0 });\n}\n"]}
@@ -0,0 +1,37 @@
1
+ import type { ImageProcessor } from "../../tools/image-processor.ts";
2
+ /** How `createPiImages` keeps its instance. */
3
+ export type PiImagesOptions = {
4
+ /**
5
+ * How long the instance (and its memory) stays after its last image, so a burst of images shares one; the next
6
+ * image after that opens a fresh one, and the dropped one's memory goes at the engine's next garbage collection.
7
+ * 0 drops it at the next macrotask: images prepared one after another without waiting on I/O still share it.
8
+ * Default 1 s, an unreferenced timer, which never keeps a Node process alive.
9
+ */
10
+ readonly idleMs?: number;
11
+ /**
12
+ * Called once each time the processor drops an instance (after its idle time; after an image failed on it, in a task
13
+ * of its own once the failure unwound), once nothing of the processor's holds it any more: for a host that wants the
14
+ * memory back at once rather than at the engine's next collection, which an idle process may not run for a long
15
+ * time. Node's `gc()` (with `--expose-gc`) returns it then.
16
+ */
17
+ readonly onDropped?: () => void;
18
+ };
19
+ /**
20
+ * An `ImageProcessor` on pi-images, for `createCodingTools({ images })` and `/images/fit`. `module` is
21
+ * `@earendil-works/pi-images/pi-images.wasm` compiled, or a promise of it: `/images/pi-images/node` reads and compiles
22
+ * it, `/images/pi-images/cloudflare` imports it as a Workers module; a browser passes
23
+ * `WebAssembly.compileStreaming(fetch(url))`.
24
+ *
25
+ * It prepares as Photon's processor does (`encode.ts` holds the policy both follow): an image already upright, in a
26
+ * format providers take inline that its bytes are, and within the limits is returned as it is once it decodes;
27
+ * otherwise it is decoded into the maximum width and height turned upright by its EXIF orientation, and encoded as PNG
28
+ * or JPEG at falling qualities (JPEG first for JPEG sources), then 3/4 smaller at a time, until the base64 fits. The
29
+ * format is read from the bytes; one providers do not take inline (BMP) becomes PNG. Scaling averages the area each
30
+ * pixel covers.
31
+ *
32
+ * The work runs on the calling thread: about 0.2 s for a 12-megapixel JPEG, 0.3 s for a 6-megapixel PNG. A trap (the
33
+ * library's 512 MiB memory ceiling, a panic) answers `undefined`, any other error rejects, and either loses only that
34
+ * instance.
35
+ */
36
+ export declare function createPiImages(module: WebAssembly.Module | Promise<WebAssembly.Module>, options?: PiImagesOptions): ImageProcessor;
37
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/images/pi-images/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAGrE,+CAA+C;AAC/C,MAAM,MAAM,eAAe,GAAG;IAC7B;;;;;OAKG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB;;;;;OAKG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,IAAI,CAAC;CAChC,CAAC;AAEF;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,cAAc,CAC7B,MAAM,EAAE,WAAW,CAAC,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,MAAM,CAAC,EACxD,OAAO,GAAE,eAAoB,GAC3B,cAAc,CAEhB"}