@hamur/image 0.0.0-stage → 0.0.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 (156) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +24 -2
  3. package/dist/chunks/bun-index-n7xnn0a2.js +502 -0
  4. package/dist/src/adapters/angular.js +275 -0
  5. package/dist/src/adapters/html.js +70 -0
  6. package/dist/src/adapters/preact.js +82 -0
  7. package/dist/src/adapters/react.js +84 -0
  8. package/dist/src/adapters/solid.js +93 -0
  9. package/dist/src/adapters/svelte.js +15 -0
  10. package/dist/src/adapters/vue.js +147 -0
  11. package/dist/src/index.js +1442 -0
  12. package/dist/src/server/index.js +9 -0
  13. package/dist/types/src/adapters/angular-img.d.ts +40 -0
  14. package/dist/types/src/adapters/angular-picture.d.ts +36 -0
  15. package/dist/types/src/adapters/angular.d.ts +3 -0
  16. package/dist/types/src/adapters/html-img.d.ts +10 -0
  17. package/dist/types/src/adapters/html-picture.d.ts +6 -0
  18. package/dist/types/src/adapters/html.d.ts +6 -0
  19. package/dist/types/src/adapters/preact-img.d.ts +8 -0
  20. package/dist/types/src/adapters/preact-picture.d.ts +6 -0
  21. package/dist/types/src/adapters/preact.d.ts +6 -0
  22. package/dist/types/src/adapters/react-img.d.ts +8 -0
  23. package/dist/types/src/adapters/react-picture.d.ts +6 -0
  24. package/dist/types/src/adapters/react.d.ts +6 -0
  25. package/dist/types/src/adapters/solid-img.d.ts +8 -0
  26. package/dist/types/src/adapters/solid-picture.d.ts +6 -0
  27. package/dist/types/src/adapters/solid.d.ts +6 -0
  28. package/dist/types/src/adapters/svelte.d.ts +3 -0
  29. package/dist/types/src/adapters/vue-img.d.ts +119 -0
  30. package/dist/types/src/adapters/vue-picture.d.ts +121 -0
  31. package/dist/types/src/adapters/vue.d.ts +234 -0
  32. package/dist/types/src/build/endpoint.d.ts +12 -0
  33. package/dist/types/src/build/platform.d.ts +24 -0
  34. package/dist/types/src/build/runtime.d.ts +9 -0
  35. package/dist/types/src/build/types.d.ts +4 -0
  36. package/dist/types/src/build/variants.d.ts +8 -0
  37. package/dist/types/src/domains.d.ts +27 -0
  38. package/dist/types/src/index.d.ts +9 -0
  39. package/dist/types/src/module.d.ts +3 -0
  40. package/dist/types/src/options.d.ts +15 -0
  41. package/dist/types/src/providers/bunny.d.ts +9 -0
  42. package/dist/types/src/providers/cloudflare.d.ts +9 -0
  43. package/dist/types/src/providers/cloudflareImages.d.ts +9 -0
  44. package/dist/types/src/providers/cloudinary.d.ts +9 -0
  45. package/dist/types/src/providers/contentful.d.ts +9 -0
  46. package/dist/types/src/providers/fastly.d.ts +9 -0
  47. package/dist/types/src/providers/hamur-url.d.ts +3 -0
  48. package/dist/types/src/providers/hamur.d.ts +3 -0
  49. package/dist/types/src/providers/imagekit.d.ts +9 -0
  50. package/dist/types/src/providers/imgix.d.ts +9 -0
  51. package/dist/types/src/providers/imgproxy.d.ts +9 -0
  52. package/dist/types/src/providers/ipx.d.ts +9 -0
  53. package/dist/types/src/providers/netlify.d.ts +9 -0
  54. package/dist/types/src/providers/none.d.ts +8 -0
  55. package/dist/types/src/providers/sanity.d.ts +9 -0
  56. package/dist/types/src/providers/shared.d.ts +7 -0
  57. package/dist/types/src/providers/storyblok.d.ts +9 -0
  58. package/dist/types/src/providers/strapi.d.ts +9 -0
  59. package/dist/types/src/providers/supabase.d.ts +9 -0
  60. package/dist/types/src/providers/twicpics.d.ts +9 -0
  61. package/dist/types/src/providers/uploadcare.d.ts +9 -0
  62. package/dist/types/src/providers/vercel-url.d.ts +3 -0
  63. package/dist/types/src/providers/vercel.d.ts +3 -0
  64. package/dist/types/src/providers/weserv.d.ts +9 -0
  65. package/dist/types/src/runtime/image.d.ts +28 -0
  66. package/dist/types/src/runtime/img.d.ts +71 -0
  67. package/dist/types/src/runtime/index.d.ts +9 -0
  68. package/dist/types/src/runtime/picture.d.ts +24 -0
  69. package/dist/types/src/runtime/sizes.d.ts +8 -0
  70. package/dist/types/src/runtime/source.d.ts +3 -0
  71. package/dist/types/src/server/door.d.ts +1 -0
  72. package/dist/types/src/server/endpoint.d.ts +46 -0
  73. package/dist/types/src/server/handler.d.ts +1 -0
  74. package/dist/types/src/server/index.d.ts +1 -0
  75. package/dist/types/src/server/miss-handler.d.ts +1 -0
  76. package/dist/types/src/server/miss.d.ts +1 -0
  77. package/dist/types/src/server/parse.d.ts +30 -0
  78. package/dist/types/src/server/remote.d.ts +20 -0
  79. package/dist/types/src/types.d.ts +178 -0
  80. package/package.json +114 -4
  81. package/src/adapters/Img.svelte +33 -0
  82. package/src/adapters/Picture.svelte +39 -0
  83. package/src/adapters/angular-img.ts +144 -0
  84. package/src/adapters/angular-picture.ts +146 -0
  85. package/src/adapters/angular.ts +3 -0
  86. package/src/adapters/html-img.ts +42 -0
  87. package/src/adapters/html-picture.ts +30 -0
  88. package/src/adapters/html.ts +9 -0
  89. package/src/adapters/preact-img.ts +51 -0
  90. package/src/adapters/preact-picture.ts +40 -0
  91. package/src/adapters/preact.ts +9 -0
  92. package/src/adapters/react-img.ts +54 -0
  93. package/src/adapters/react-picture.ts +49 -0
  94. package/src/adapters/react.ts +9 -0
  95. package/src/adapters/solid-img.ts +47 -0
  96. package/src/adapters/solid-picture.ts +43 -0
  97. package/src/adapters/solid.ts +9 -0
  98. package/src/adapters/svelte.ts +3 -0
  99. package/src/adapters/test/ImgCustomPage.svelte +14 -0
  100. package/src/adapters/test/ImgPage.svelte +5 -0
  101. package/src/adapters/test/ImgPreloadPage.svelte +6 -0
  102. package/src/adapters/test/PicturePage.svelte +6 -0
  103. package/src/adapters/test/PicturePreloadPage.svelte +5 -0
  104. package/src/adapters/test/support.ts +116 -0
  105. package/src/adapters/vue-img.ts +72 -0
  106. package/src/adapters/vue-picture.ts +64 -0
  107. package/src/adapters/vue.ts +7 -0
  108. package/src/build/endpoint.ts +78 -0
  109. package/src/build/platform.ts +99 -0
  110. package/src/build/runtime.ts +118 -0
  111. package/src/build/types.ts +23 -0
  112. package/src/build/variants.ts +174 -0
  113. package/src/domains.ts +84 -0
  114. package/src/env.d.ts +24 -0
  115. package/src/index.ts +23 -0
  116. package/src/module.ts +29 -0
  117. package/src/options.ts +329 -0
  118. package/src/providers/bunny.ts +21 -0
  119. package/src/providers/cloudflare.ts +22 -0
  120. package/src/providers/cloudflareImages.ts +25 -0
  121. package/src/providers/cloudinary.ts +31 -0
  122. package/src/providers/contentful.ts +26 -0
  123. package/src/providers/fastly.ts +29 -0
  124. package/src/providers/hamur-url.ts +81 -0
  125. package/src/providers/hamur.ts +8 -0
  126. package/src/providers/imagekit.ts +30 -0
  127. package/src/providers/imgix.ts +26 -0
  128. package/src/providers/imgproxy.ts +24 -0
  129. package/src/providers/ipx.ts +26 -0
  130. package/src/providers/netlify.ts +23 -0
  131. package/src/providers/none.ts +9 -0
  132. package/src/providers/sanity.ts +29 -0
  133. package/src/providers/shared.ts +17 -0
  134. package/src/providers/storyblok.ts +24 -0
  135. package/src/providers/strapi.ts +24 -0
  136. package/src/providers/supabase.ts +26 -0
  137. package/src/providers/twicpics.ts +26 -0
  138. package/src/providers/uploadcare.ts +32 -0
  139. package/src/providers/vercel-url.ts +18 -0
  140. package/src/providers/vercel.ts +8 -0
  141. package/src/providers/weserv.ts +25 -0
  142. package/src/runtime/image.ts +266 -0
  143. package/src/runtime/img.ts +241 -0
  144. package/src/runtime/index.ts +18 -0
  145. package/src/runtime/picture.ts +62 -0
  146. package/src/runtime/sizes.ts +52 -0
  147. package/src/runtime/source.ts +8 -0
  148. package/src/server/door.ts +1 -0
  149. package/src/server/endpoint.ts +428 -0
  150. package/src/server/handler.ts +33 -0
  151. package/src/server/index.ts +1 -0
  152. package/src/server/miss-handler.ts +20 -0
  153. package/src/server/miss.ts +1 -0
  154. package/src/server/parse.ts +152 -0
  155. package/src/server/remote.ts +166 -0
  156. package/src/types.ts +177 -0
@@ -0,0 +1,43 @@
1
+ import { createComponent, createSignal, omit, onSettled, type Component } from "solid-js"
2
+ import { dynamic, type JSX } from "@solidjs/web"
3
+ import { useHead } from "@hamur/adapter-solid"
4
+ import { applyPlaceholder, createImgEvents } from "../runtime/img.ts"
5
+ import { picturePreloadLink, type PictureAttributes, type PictureOptions } from "../runtime/picture.ts"
6
+
7
+ export type PictureProps = PictureOptions & {
8
+ fetchpriority?: "high" | "low" | "auto"
9
+ } & Omit<JSX.ImgHTMLAttributes<HTMLImageElement>, keyof PictureOptions | "srcset" | "fetchpriority">
10
+
11
+ const tags = {
12
+ img: dynamic(() => "img", { static: true }),
13
+ picture: dynamic(() => "picture", { static: true }),
14
+ source: dynamic(() => "source", { static: true }),
15
+ } as Record<string, Component<Record<string, unknown>>>
16
+
17
+ const element = (tag: "img" | "picture" | "source", attributes: object): JSX.Element =>
18
+ createComponent(tags[tag]!, attributes as Record<string, unknown>)
19
+
20
+ export function createPicture(attributes: PictureAttributes): (props: PictureProps) => JSX.Element {
21
+ return function Picture(props) {
22
+ const own = props
23
+ const rest = omit(props, "onLoad", "onError")
24
+ const [isLoaded, setLoaded] = createSignal(false)
25
+ const events = createImgEvents(() => ({ load: own.onLoad as never, error: own.onError as never }), setLoaded)
26
+ let node: HTMLImageElement | undefined
27
+ onSettled(() => {
28
+ if (node) events.replay(node)
29
+ })
30
+ if (props.preload) useHead(() => ({ link: [picturePreloadLink(attributes(rest))] }))
31
+ return (() => {
32
+ const { sources, img } = attributes(rest)
33
+ const image = element("img", {
34
+ onLoad: events.load,
35
+ onError: events.error,
36
+ ref: (value: HTMLImageElement) => (node = value),
37
+ ...applyPlaceholder(img, rest, isLoaded()),
38
+ })
39
+ if (sources.length === 0) return image
40
+ return element("picture", { children: [...sources.map((source) => element("source", source)), image] })
41
+ }) as unknown as JSX.Element
42
+ }
43
+ }
@@ -0,0 +1,9 @@
1
+ import { getImage, getSizes, imgAttributes, pictureAttributes } from "../runtime/index.ts"
2
+ import { createImg } from "./solid-img.ts"
3
+ import { createPicture } from "./solid-picture.ts"
4
+
5
+ export type { ImgProps, ImgState } from "./solid-img.ts"
6
+ export type { PictureProps } from "./solid-picture.ts"
7
+ export { getImage, getSizes }
8
+ export const Img = createImg(imgAttributes)
9
+ export const Picture = createPicture(pictureAttributes)
@@ -0,0 +1,3 @@
1
+ export { getImage, getSizes } from "../runtime/index.ts"
2
+ export { default as Img } from "./Img.svelte"
3
+ export { default as Picture } from "./Picture.svelte"
@@ -0,0 +1,14 @@
1
+ <script lang="ts">
2
+ import Img from "../Img.svelte"
3
+ </script>
4
+
5
+ <Img src="/a.png" width={300} sizes="sm:100vw md:50vw" alt="">
6
+ {#snippet children({ src, isLoaded })}
7
+ <div data-src={src} data-loaded={String(isLoaded)}></div>
8
+ {/snippet}
9
+ </Img>
10
+ <Img src="/a.png" width={300} sizes="sm:100vw md:50vw" alt="">
11
+ {#snippet children({ imgAttrs })}
12
+ <img {...imgAttrs} />
13
+ {/snippet}
14
+ </Img>
@@ -0,0 +1,5 @@
1
+ <script lang="ts">
2
+ import Img from "../Img.svelte"
3
+ </script>
4
+
5
+ <Img src="/a.png" width={300} sizes="sm:100vw md:50vw" alt="" fetchpriority="high" class="hero" />
@@ -0,0 +1,6 @@
1
+ <script lang="ts">
2
+ import Img from "../Img.svelte"
3
+ </script>
4
+
5
+ <Img src="/a.png" width={300} sizes="sm:100vw md:50vw" alt="" preload />
6
+ <Img src="/a.png" width={300} sizes="sm:100vw md:50vw" alt="" preload />
@@ -0,0 +1,6 @@
1
+ <script lang="ts">
2
+ import Picture from "../Picture.svelte"
3
+ </script>
4
+
5
+ <Picture src="/a.png" width={300} sizes="sm:100vw md:50vw" alt="" format="webp" class="hero" />
6
+ <Picture src="/a.png" width={300} sizes="sm:100vw md:50vw" alt="" provider="none" />
@@ -0,0 +1,5 @@
1
+ <script lang="ts">
2
+ import Picture from "../Picture.svelte"
3
+ </script>
4
+
5
+ <Picture src="/a.png" width={300} sizes="sm:100vw md:50vw" alt="" format="webp" preload />
@@ -0,0 +1,116 @@
1
+ import { resolveOptions } from "../../options.ts"
2
+ import none from "../../providers/none.ts"
3
+ import { createHamurProvider } from "../../providers/hamur-url.ts"
4
+ import { createImage } from "../../runtime/image.ts"
5
+ import { createImgAttributes, type ImgAttributes } from "../../runtime/img.ts"
6
+ import { createPictureAttributes, type PictureAttributes } from "../../runtime/picture.ts"
7
+ import type { ImageProvider, ImageRuntimeOptions, ImageSources } from "../../types.ts"
8
+
9
+ export const SOURCES: ImageSources = { "/a.png": [1200, 800, "png", "aaaaaaaa"] }
10
+
11
+ /** The conformance snippet. */
12
+ export const SNIPPET = { src: "/a.png", width: 300, sizes: "sm:100vw md:50vw", alt: "" }
13
+
14
+ export const ATTRIBUTES =
15
+ 'src="/_hamur/image/v_aaaaaaaa,w_1200/a.png.webp" srcset="/_hamur/image/v_aaaaaaaa,w_640/a.png.webp 640w, /_hamur/image/v_aaaaaaaa,w_768/a.png.webp 768w, /_hamur/image/v_aaaaaaaa,w_1200/a.png.webp 1200w" sizes="(min-width: 768px) 50vw, (min-width: 640px) 100vw, 100vw" width="300" height="200" alt="" loading="lazy" decoding="async"'
16
+
17
+ export const SRC = "/_hamur/image/v_aaaaaaaa,w_1200/a.png.webp"
18
+
19
+ /** Preact and Vue write an empty attribute value bare; the attribute means the same. */
20
+ export const BARE_ATTRIBUTES = ATTRIBUTES.replace('alt=""', "alt")
21
+
22
+ export function testEnvironment(warn: (message: string) => void = () => {}, sources: ImageSources = SOURCES) {
23
+ const resolved = resolveOptions({}, { rootDir: "/app", publicDirs: ["/app/public"], exists: () => true })
24
+ const options: ImageRuntimeOptions = {
25
+ baseURL: "/",
26
+ provider: resolved.provider,
27
+ providers: {},
28
+ presets: resolved.presets,
29
+ screens: resolved.screens,
30
+ densities: resolved.densities,
31
+ widths: resolved.widths,
32
+ format: resolved.format,
33
+ domains: resolved.domains,
34
+ alias: resolved.alias,
35
+ }
36
+ const providers: Record<string, ImageProvider> = { hamur: createHamurProvider(sources), none }
37
+ return { options, sources, providers, warn }
38
+ }
39
+
40
+ export function testImgAttributes(warn: (message: string) => void = () => {}): ImgAttributes {
41
+ return createImgAttributes(createImage(testEnvironment()), warn)
42
+ }
43
+
44
+ export const SIZES = "(min-width: 768px) 50vw, (min-width: 640px) 100vw, 100vw"
45
+
46
+ export const SOURCE =
47
+ '<source type="image/webp" srcset="/_hamur/image/v_aaaaaaaa,w_640/a.png.webp 640w, /_hamur/image/v_aaaaaaaa,w_768/a.png.webp 768w, /_hamur/image/v_aaaaaaaa,w_1200/a.png.webp 1200w" sizes="(min-width: 768px) 50vw, (min-width: 640px) 100vw, 100vw">'
48
+
49
+ /** The `<img>` of a PNG source in its own format. */
50
+ export const LEGACY_IMG = `<img ${ATTRIBUTES.replaceAll(".webp", ".png")}>`
51
+
52
+ export const PICTURE = `<picture>${SOURCE}${LEGACY_IMG}</picture>`
53
+
54
+ export const PICTURE_SNIPPET = { ...SNIPPET, format: "webp" as const }
55
+
56
+ /** Libraries differ in the closing `/>`, a bare empty `alt`, hydration keys, Svelte's event replay and the whitespace between tags; the markup means the same. */
57
+ export function canonical(html: string): string {
58
+ return html
59
+ .replace(/<!--.*?-->/g, "")
60
+ .replace(/ _hk=(?:"[^"]*"|[^\s>]*)/g, "")
61
+ .replace(/ onload="this\.__e=event" onerror="this\.__e=event"/g, "")
62
+ .replace(/\s*\/>/g, ">")
63
+ .replace(/<(\w+) >/g, "<$1>")
64
+ .replace(/ alt(?=[ >])/g, ' alt=""')
65
+ .replace(/>\s+</g, "><")
66
+ .replace(/ srcSet=/gi, " srcset=")
67
+ }
68
+
69
+ export function testPictureAttributes(
70
+ providers: Record<string, ImageProvider> = {},
71
+ warn: (message: string) => void = () => {},
72
+ ): PictureAttributes {
73
+ const environment = testEnvironment(warn)
74
+ return createPictureAttributes(
75
+ createImgAttributes(createImage({ ...environment, providers: { ...environment.providers, ...providers } }), warn),
76
+ {
77
+ options: environment.options,
78
+ providers: { ...environment.providers, ...providers },
79
+ },
80
+ )
81
+ }
82
+
83
+ export const SRCSET = / srcset="([^"]*)"/.exec(ATTRIBUTES)![1]!
84
+
85
+ /** The `<img>` of `ATTRIBUTES` with `preload`: eager, and fetchpriority high. */
86
+ export const PRELOAD_ATTRIBUTES = `${ATTRIBUTES.replace('loading="lazy"', 'loading="eager"')} fetchpriority="high"`
87
+
88
+ export const PRELOAD_BARE_ATTRIBUTES = PRELOAD_ATTRIBUTES.replace('alt=""', "alt")
89
+
90
+ /** The attributes of the one `<link>` in the rendered head `tags`; throws when there is not exactly one. */
91
+ export function preloadLink(tags: string[]): Record<string, string> {
92
+ const links = tags.filter((tag) => tag.startsWith("<link"))
93
+ if (links.length !== 1) throw new Error(`expected one <link>, got ${links.length}: ${links.join("")}`)
94
+ return Object.fromEntries([...links[0]!.matchAll(/ ([\w-]+)="([^"]*)"/g)].map(([, name, value]) => [name!, value!]))
95
+ }
96
+
97
+ export const PRELOAD_LINK = {
98
+ rel: "preload",
99
+ as: "image",
100
+ href: SRC,
101
+ imagesrcset: SRCSET,
102
+ imagesizes: SIZES,
103
+ fetchpriority: "high",
104
+ }
105
+
106
+ export const SOURCE_SRCSET = / srcset="([^"]*)"/.exec(SOURCE)![1]!
107
+
108
+ export const PICTURE_PRELOAD_LINK = {
109
+ rel: "preload",
110
+ as: "image",
111
+ href: SOURCE_SRCSET.split(" ")[0]!,
112
+ imagesrcset: SOURCE_SRCSET,
113
+ imagesizes: SIZES,
114
+ fetchpriority: "high",
115
+ type: "image/webp",
116
+ }
@@ -0,0 +1,72 @@
1
+ import { defineComponent, h, onMounted, ref, type PropType, type VNodeChild } from "vue"
2
+ import type { ImageMeta } from "hamur"
3
+ import type { ImageFit, ImageFormat, ImageModifiers, HamurImagePreset, HamurImageProvider } from "../types.ts"
4
+ import { useHead } from "@hamur/adapter-vue"
5
+ import {
6
+ applyPlaceholder,
7
+ createImgEvents,
8
+ imagePreloadLink,
9
+ type ImgAttributes,
10
+ type ImgState,
11
+ } from "../runtime/img.ts"
12
+
13
+ const call = (handler: unknown, event: Event): void => {
14
+ for (const listener of Array.isArray(handler) ? handler : [handler])
15
+ if (typeof listener === "function") listener(event)
16
+ }
17
+
18
+ export function createImg(attributes: ImgAttributes) {
19
+ return defineComponent({
20
+ name: "Img",
21
+ inheritAttrs: false,
22
+ props: {
23
+ src: { type: [String, Object] as PropType<string | ImageMeta>, required: true },
24
+ alt: { type: String },
25
+ width: { type: [Number, String] as PropType<number | `${number}`> },
26
+ height: { type: [Number, String] as PropType<number | `${number}`> },
27
+ sizes: { type: String },
28
+ densities: { type: Array as PropType<number[]> },
29
+ format: { type: String as PropType<ImageFormat> },
30
+ quality: { type: Number },
31
+ fit: { type: String as PropType<ImageFit> },
32
+ modifiers: { type: Object as PropType<ImageModifiers> },
33
+ provider: { type: String as PropType<HamurImageProvider> },
34
+ preset: { type: String as PropType<HamurImagePreset> },
35
+ loading: { type: String as PropType<"lazy" | "eager"> },
36
+ fetchpriority: { type: String as PropType<"high" | "low" | "auto"> },
37
+ placeholder: { type: String },
38
+ placeholderClass: { type: String },
39
+ preload: { type: Boolean },
40
+ custom: { type: Function as PropType<(state: ImgState) => VNodeChild> },
41
+ },
42
+ setup(props, { attrs, slots }) {
43
+ const isLoaded = ref(false)
44
+ const events = createImgEvents(
45
+ () => ({ load: (event) => call(attrs.onLoad, event), error: (event) => call(attrs.onError, event) }),
46
+ (value) => (isLoaded.value = value),
47
+ )
48
+ const resolve = () => {
49
+ const { custom, ...own } = props
50
+ const { onLoad, onError, ...rest } = attrs
51
+ return attributes({ ...own, ...rest })
52
+ }
53
+ if (props.preload) useHead(() => ({ link: [imagePreloadLink(resolve())] }))
54
+ let image: HTMLImageElement | null = null
55
+ onMounted(() => {
56
+ if (image) events.replay(image)
57
+ })
58
+ return () => {
59
+ const computed = resolve()
60
+ const imgAttrs = {
61
+ ...applyPlaceholder(computed, props, isLoaded.value),
62
+ onLoad: events.load,
63
+ onError: events.error,
64
+ ref: (node: unknown) => (image = node as HTMLImageElement | null),
65
+ }
66
+ const render = props.custom ?? slots.default
67
+ if (render) return render({ imgAttrs, src: String(computed.src), isLoaded: isLoaded.value })
68
+ return h("img", imgAttrs)
69
+ }
70
+ },
71
+ })
72
+ }
@@ -0,0 +1,64 @@
1
+ import { defineComponent, h, onMounted, ref, type PropType } from "vue"
2
+ import type { ImageMeta } from "hamur"
3
+ import type { ImageFit, ImageFormat, ImageModifiers, HamurImagePreset, HamurImageProvider } from "../types.ts"
4
+ import { useHead } from "@hamur/adapter-vue"
5
+ import { applyPlaceholder, createImgEvents } from "../runtime/img.ts"
6
+ import { picturePreloadLink, type PictureAttributes } from "../runtime/picture.ts"
7
+
8
+ export function createPicture(attributes: PictureAttributes) {
9
+ return defineComponent({
10
+ name: "Picture",
11
+ inheritAttrs: false,
12
+ props: {
13
+ src: { type: [String, Object] as PropType<string | ImageMeta>, required: true },
14
+ alt: { type: String },
15
+ width: { type: [Number, String] as PropType<number | `${number}`> },
16
+ height: { type: [Number, String] as PropType<number | `${number}`> },
17
+ sizes: { type: String },
18
+ densities: { type: Array as PropType<number[]> },
19
+ format: { type: [String, Array] as PropType<ImageFormat | ImageFormat[]> },
20
+ legacyFormat: { type: String as PropType<ImageFormat> },
21
+ quality: { type: Number },
22
+ fit: { type: String as PropType<ImageFit> },
23
+ modifiers: { type: Object as PropType<ImageModifiers> },
24
+ provider: { type: String as PropType<HamurImageProvider> },
25
+ preset: { type: String as PropType<HamurImagePreset> },
26
+ loading: { type: String as PropType<"lazy" | "eager"> },
27
+ fetchpriority: { type: String as PropType<"high" | "low" | "auto"> },
28
+ preload: { type: Boolean },
29
+ placeholder: { type: String },
30
+ placeholderClass: { type: String },
31
+ },
32
+ setup(props, { attrs }) {
33
+ const isLoaded = ref(false)
34
+ const call = (handler: unknown, event: Event): void => {
35
+ for (const listener of Array.isArray(handler) ? handler : [handler])
36
+ if (typeof listener === "function") listener(event)
37
+ }
38
+ const events = createImgEvents(
39
+ () => ({ load: (event) => call(attrs.onLoad, event), error: (event) => call(attrs.onError, event) }),
40
+ (value) => (isLoaded.value = value),
41
+ )
42
+ const resolve = () => {
43
+ const { onLoad, onError, ...rest } = attrs
44
+ return attributes({ ...props, ...rest })
45
+ }
46
+ if (props.preload) useHead(() => ({ link: [picturePreloadLink(resolve())] }))
47
+ let node: HTMLImageElement | null = null
48
+ onMounted(() => {
49
+ if (node) events.replay(node)
50
+ })
51
+ return () => {
52
+ const { sources, img } = resolve()
53
+ const image = h("img", {
54
+ ...applyPlaceholder(img, props, isLoaded.value),
55
+ onLoad: events.load,
56
+ onError: events.error,
57
+ ref: (value: unknown) => (node = value as HTMLImageElement | null),
58
+ })
59
+ if (sources.length === 0) return image
60
+ return h("picture", [...sources.map((source) => h("source", source)), image])
61
+ }
62
+ },
63
+ })
64
+ }
@@ -0,0 +1,7 @@
1
+ import { getImage, getSizes, imgAttributes, pictureAttributes } from "../runtime/index.ts"
2
+ import { createImg } from "./vue-img.ts"
3
+ import { createPicture } from "./vue-picture.ts"
4
+
5
+ export { getImage, getSizes }
6
+ export const Img = createImg(imgAttributes)
7
+ export const Picture = createPicture(pictureAttributes)
@@ -0,0 +1,78 @@
1
+ import {
2
+ addServer,
3
+ addServerAssets,
4
+ addTemplate,
5
+ createResolver,
6
+ diagnostic,
7
+ presetFeatures,
8
+ useLogger,
9
+ type HamurContext,
10
+ } from "hamur/kit"
11
+ import type { ImageBuildOptions, ImageEndpointOptions, ImageProviderName } from "../types.ts"
12
+
13
+ /** True where the `hamur` provider transforms at run time: `hamur dev` on any preset, and a preset whose `features.imageTransforms` is not `unsupported`. */
14
+ export function transformsAtRunTime(hamur: HamurContext): boolean {
15
+ return hamur.options.dev || presetFeatures(hamur.options.preset).imageTransforms !== "unsupported"
16
+ }
17
+
18
+ /** What `image.provider` names on this build. `auto` is `hamur` under `hamur dev`, else the preset's `features.imageService`, else `hamur`. */
19
+ export function resolveProvider(provider: string, hamur: HamurContext): ImageProviderName {
20
+ if (provider !== "auto") return provider as ImageProviderName
21
+ return (
22
+ hamur.options.dev ? "hamur" : (presetFeatures(hamur.options.preset).imageService ?? "hamur")
23
+ ) as ImageProviderName
24
+ }
25
+
26
+ /** Blob sources need run-time transforms: the build has no blob to read. */
27
+ export function blobsUntransformed(options: ImageBuildOptions, hamur: HamurContext): boolean {
28
+ return options.sources.blob !== undefined && providersUsed(options).has("hamur") && !transformsAtRunTime(hamur)
29
+ }
30
+
31
+ /** The built-in providers a build may call: the default, the presets' and every configured entry. */
32
+ export function providersUsed(options: ImageBuildOptions): Set<string> {
33
+ const named = [
34
+ options.provider,
35
+ ...Object.values(options.presets).flatMap((preset) => (preset.provider === undefined ? [] : [preset.provider])),
36
+ ...Object.keys(options.providers),
37
+ ]
38
+ return new Set(named.map((name) => options.providers[name]?.builtIn ?? name))
39
+ }
40
+
41
+ /** The door with `/_hamur/image/**` where transforms run at run time; the 404 route on a build-variants preset with a server, none on `static`. */
42
+ export function setupEndpoint(options: ImageBuildOptions, hamur: HamurContext): void {
43
+ if (blobsUntransformed(options, hamur)) {
44
+ useLogger("image").warn(
45
+ diagnostic(
46
+ "HAMUR_W6005",
47
+ `image.sources.blob needs run-time transforms; the ${hamur.options.preset} preset transforms at build, so blob sources are served untransformed`,
48
+ ),
49
+ )
50
+ }
51
+ if (!providersUsed(options).has("hamur")) return
52
+ if (!transformsAtRunTime(hamur)) {
53
+ if (hamur.options.preset !== "static") addServer(createResolver(import.meta.url).resolve("../server/miss.ts"))
54
+ return
55
+ }
56
+ const { dev } = hamur.options
57
+ const publicDirs = [hamur.options.publicDir, ...hamur.options.layers.map((layer) => layer.publicDir)]
58
+ const own = options.dirs.length !== publicDirs.length || options.dirs.some((dir, i) => dir !== publicDirs[i])
59
+ if (own && !dev) addServerAssets({ name: "image", dir: options.dirs[0]! })
60
+ const endpoint: ImageEndpointOptions = {
61
+ dev,
62
+ dirs: dev ? options.dirs : [],
63
+ assets: own && !dev,
64
+ maxPixels: options.maxPixels,
65
+ maxBytes: options.maxBytes,
66
+ ...(options.sources.blob === undefined ? {} : { blobPrefix: options.sources.blob.prefix }),
67
+ }
68
+ // a template has no importer, so the app's @hamur/blob is resolved from its root
69
+ const blob =
70
+ endpoint.blobPrefix === undefined
71
+ ? "export const useBlob = undefined;"
72
+ : `export { useBlob } from ${JSON.stringify(Bun.resolveSync("@hamur/blob/server", hamur.options.rootDir))};`
73
+ addTemplate({
74
+ filename: "image/endpoint",
75
+ getContents: () => `export default ${JSON.stringify(endpoint)};\n${blob}\n`,
76
+ })
77
+ addServer(createResolver(import.meta.url).resolve("../server/door.ts"))
78
+ }
@@ -0,0 +1,99 @@
1
+ import { presetFeatures, type HamurContext } from "hamur/kit"
2
+ import { hostSource, parseDomain, pathSource } from "../domains.ts"
3
+ import type { ImageBuildOptions, ImageFormat } from "../types.ts"
4
+ import { providersUsed } from "./endpoint.ts"
5
+
6
+ const MIME: Partial<Record<ImageFormat, string>> = { avif: "image/avif", webp: "image/webp" }
7
+ const MINIMUM_CACHE_TTL = 14400
8
+ const DEFAULT_QUALITY = 75
9
+
10
+ export interface RemotePattern {
11
+ protocol: "http" | "https"
12
+ hostname: string
13
+ port: string
14
+ pathname: string
15
+ }
16
+
17
+ type Sources = Pick<ImageBuildOptions, "domains" | "alias">
18
+
19
+ /** `image.domains` and the `alias` targets as URL patterns. A target contributes its protocol, host, port and path (below which everything matches); `resolveOptions` has refused a query, a fragment and credentials. */
20
+ export function remotePatterns({ domains, alias }: Sources): RemotePattern[] {
21
+ const patterns = domains.map((entry) => {
22
+ const { protocol, host, port, path } = parseDomain(entry)
23
+ return {
24
+ protocol: protocol.slice(0, -1) as RemotePattern["protocol"],
25
+ hostname: host,
26
+ port,
27
+ pathname: path ?? "/**",
28
+ }
29
+ })
30
+ for (const target of Object.values(alias)) {
31
+ const url = new URL(target)
32
+ patterns.push({
33
+ protocol: url.protocol.slice(0, -1) as RemotePattern["protocol"],
34
+ hostname: url.hostname,
35
+ port: url.port,
36
+ pathname: `${url.pathname.replace(/\/+$/, "")}/**`,
37
+ })
38
+ }
39
+ return patterns
40
+ }
41
+
42
+ /** One anchored expression per `image.domains` entry and alias target: the whole URL, an optional query string allowed. */
43
+ export function remoteImages(sources: Sources): string[] {
44
+ return remotePatterns(sources).map(
45
+ ({ protocol, hostname, port, pathname }) =>
46
+ `^${protocol}://${hostSource(hostname)}${port === "" ? "" : `:${port}`}${pathSource(pathname)}(?:\\?.*)?$`,
47
+ )
48
+ }
49
+
50
+ /** The qualities a `getImage` URL on Vercel can carry: the default, each preset's and the 75 sent when none is set. */
51
+ export function qualities(options: Pick<ImageBuildOptions, "quality" | "presets">): number[] {
52
+ const found = [
53
+ DEFAULT_QUALITY,
54
+ options.quality,
55
+ ...Object.values(options.presets).map((preset) => preset.modifiers.quality),
56
+ ]
57
+ return [...new Set(found.filter((quality): quality is number => typeof quality === "number"))].sort((a, b) => a - b)
58
+ }
59
+
60
+ /** The `images` of `.vercel/output/config.json`. */
61
+ export function vercelImages(options: ImageBuildOptions): Record<string, unknown> {
62
+ return {
63
+ sizes: options.widths,
64
+ domains: [],
65
+ remotePatterns: remotePatterns(options),
66
+ formats: options.format.flatMap((format) => MIME[format] ?? []),
67
+ qualities: qualities(options),
68
+ minimumCacheTTL: MINIMUM_CACHE_TTL,
69
+ }
70
+ }
71
+
72
+ /** The `images` of `.netlify/v1/config.json`. */
73
+ export function netlifyImages(options: ImageBuildOptions): Record<string, unknown> {
74
+ return { remote_images: remoteImages(options) }
75
+ }
76
+
77
+ const plain = (value: unknown): value is Record<string, unknown> =>
78
+ typeof value === "object" && value !== null && !Array.isArray(value)
79
+
80
+ /** The app's `images` with Hamur's over it: a plain object merges, an array is the union of both (the app's entries first), any other value is Hamur's. */
81
+ export function mergeImages(own: unknown, ours: Record<string, unknown>): Record<string, unknown> {
82
+ const result: Record<string, unknown> = plain(own) ? { ...own } : {}
83
+ for (const [key, value] of Object.entries(ours)) {
84
+ const current = result[key]
85
+ if (plain(value) && plain(current)) result[key] = mergeImages(current, value)
86
+ else if (Array.isArray(value) && Array.isArray(current))
87
+ result[key] = [...new Map([...current, ...value].map((entry) => [JSON.stringify(entry), entry])).values()]
88
+ else result[key] = value
89
+ }
90
+ return result
91
+ }
92
+
93
+ /** Puts the platform service's `images` into `vercel.config.images` or `netlify.config.images`, which the preset writes. */
94
+ export function setupPlatform(options: ImageBuildOptions, hamur: HamurContext): void {
95
+ const service = presetFeatures(hamur.options.preset).imageService
96
+ if (service === undefined || !providersUsed(options).has(service)) return
97
+ const config = hamur.options[service].config
98
+ config.images = mergeImages(config.images, service === "vercel" ? vercelImages(options) : netlifyImages(options))
99
+ }
@@ -0,0 +1,118 @@
1
+ import { createHash } from "node:crypto"
2
+ import { readdir } from "node:fs/promises"
3
+ import { join, relative, sep } from "node:path"
4
+ import { addTemplate, createResolver, diagnostic, readImageMeta, useLogger, type HamurContext } from "hamur/kit"
5
+ import type { ImageRuntimeOptions, ImageSources, ImageBuildOptions } from "../types.ts"
6
+ import { blobsUntransformed } from "./endpoint.ts"
7
+
8
+ const IMAGE_FILE = /\.(png|jpe?g|gif|webp|avif|svg)$/i
9
+
10
+ export const normalizedBase = (baseURL: string): string => `${baseURL.replace(/\/+$/, "")}/`
11
+
12
+ /** The names `#hamur/image/providers` imports: the default provider, the keys of `providers`, the presets' providers and `none`. */
13
+ export function providerNames(options: ImageBuildOptions): string[] {
14
+ const names = new Set<string>(["none", options.provider, ...Object.keys(options.providers)])
15
+ for (const preset of Object.values(options.presets)) if (preset.provider !== undefined) names.add(preset.provider)
16
+ return [...names]
17
+ }
18
+
19
+ /** One entry per image file below the source dirs; the first dir that holds a path wins. A file whose header cannot be read, or whose path holds `:` (the separator of a storage key), is left out with one `warn`. */
20
+ export async function readSources(dirs: string[], warn: (message: string) => void = () => {}): Promise<ImageSources> {
21
+ const sources: ImageSources = {}
22
+ for (const dir of dirs) {
23
+ const entries = await readdir(dir, { recursive: true, withFileTypes: true }).catch(() => [])
24
+ for (const entry of entries
25
+ .filter((item) => item.isFile() && IMAGE_FILE.test(item.name))
26
+ .sort((a, b) => join(a.parentPath, a.name).localeCompare(join(b.parentPath, b.name)))) {
27
+ const file = join(entry.parentPath, entry.name)
28
+ const key = `/${relative(dir, file).split(sep).join("/")}`
29
+ if (Object.hasOwn(sources, key)) continue
30
+ if (key.includes(":")) {
31
+ warn(
32
+ `[image] ${diagnostic("HAMUR_W6007", `${key} is not an image source: a path with ":" cannot be a storage key`)}`,
33
+ )
34
+ continue
35
+ }
36
+ const bytes = new Uint8Array(await Bun.file(file).arrayBuffer())
37
+ let meta: ReturnType<typeof readImageMeta>
38
+ try {
39
+ meta = readImageMeta(bytes, entry.name.slice(entry.name.lastIndexOf(".") + 1), key)
40
+ } catch (error) {
41
+ warn(
42
+ `[image] ${diagnostic("HAMUR_W6007", `${key} is not an image source: ${error instanceof Error ? error.message.replace(`${key}: `, "") : String(error)}`)}`,
43
+ )
44
+ continue
45
+ }
46
+ const v = createHash("sha256").update(bytes).digest("hex").slice(0, 8)
47
+ sources[key] = meta.animated
48
+ ? [meta.width, meta.height, meta.format, v, true]
49
+ : [meta.width, meta.height, meta.format, v]
50
+ }
51
+ }
52
+ return sources
53
+ }
54
+
55
+ /** `#hamur/image/options`, `#hamur/image/providers` and `#hamur/image/sources`. */
56
+ export function setupRuntime(options: ImageBuildOptions, hamur: HamurContext): void {
57
+ const baseURL = normalizedBase(hamur.options.app.baseURL)
58
+ const r = createResolver(import.meta.url)
59
+ const runtime: ImageRuntimeOptions = {
60
+ baseURL,
61
+ provider: options.provider,
62
+ providers: Object.fromEntries(
63
+ Object.entries(options.providers).map(([name, { file, options: own }]) => [
64
+ name,
65
+ { ...(file === undefined ? {} : { file }), options: own },
66
+ ]),
67
+ ),
68
+ presets: options.presets,
69
+ screens: options.screens,
70
+ densities: options.densities,
71
+ widths: options.widths,
72
+ format: options.format,
73
+ ...(options.quality === undefined ? {} : { quality: options.quality }),
74
+ domains: options.domains,
75
+ alias: options.alias,
76
+ }
77
+ if (options.sources.blob !== undefined && blobsUntransformed(options, hamur)) {
78
+ const named = Object.entries(options.providers).flatMap(([name, entry]) =>
79
+ entry.builtIn === "hamur" ? [name] : [],
80
+ )
81
+ runtime.blobUntransformed = {
82
+ prefix: options.sources.blob.prefix,
83
+ providers: Object.hasOwn(options.providers, "hamur") ? named : ["hamur", ...named],
84
+ }
85
+ }
86
+ addTemplate({ filename: "image/options", getContents: () => `export default ${JSON.stringify(runtime)};\n` })
87
+ addTemplate({
88
+ filename: "image/providers",
89
+ getContents: () => {
90
+ const names = providerNames(options)
91
+ const files = names.map((name) => {
92
+ const entry = options.providers[name]
93
+ if (entry?.file !== undefined) return r.resolve(hamur.options.rootDir, entry.file)
94
+ return r.resolve(`../providers/${entry?.builtIn ?? name}.ts`)
95
+ })
96
+ const imports = files.map((file, i) => `import p${i} from ${JSON.stringify(file)};`)
97
+ return `${imports.join("\n")}\nexport default {\n${names.map((name, i) => ` ${JSON.stringify(name)}: p${i},`).join("\n")}\n};\n`
98
+ },
99
+ })
100
+ const warned = new Set<string>()
101
+ const warn = (message: string) => {
102
+ if (warned.has(message)) return
103
+ warned.add(message)
104
+ useLogger("image").warn(message)
105
+ }
106
+ addTemplate({
107
+ filename: "image/sources",
108
+ getContents: async () => `export default ${JSON.stringify(await readSources(options.dirs, warn))};\n`,
109
+ })
110
+ if (options.format.includes("avif") && options.provider === "hamur") {
111
+ useLogger("image").warn(
112
+ diagnostic(
113
+ "HAMUR_W6006",
114
+ 'the hamur provider makes no AVIF; image.format "avif" is used by the other providers only',
115
+ ),
116
+ )
117
+ }
118
+ }