@hamur/image 0.0.0-stage → 0.0.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 (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 +43 -0
  14. package/dist/types/src/adapters/angular-picture.d.ts +39 -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 +141 -4
  81. package/src/adapters/Img.svelte +33 -0
  82. package/src/adapters/Picture.svelte +39 -0
  83. package/src/adapters/angular-img.ts +143 -0
  84. package/src/adapters/angular-picture.ts +172 -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,47 @@
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 {
5
+ applyPlaceholder,
6
+ createImgEvents,
7
+ imagePreloadLink,
8
+ type ImgAttributes,
9
+ type ImgOptions,
10
+ type ImgState as State,
11
+ } from "../runtime/img.ts"
12
+
13
+ export type ImgState = State
14
+
15
+ export type ImgProps = ImgOptions & {
16
+ fetchpriority?: "high" | "low" | "auto"
17
+ children?: ((state: ImgState) => JSX.Element) | JSX.Element
18
+ } & Omit<JSX.ImgHTMLAttributes<HTMLImageElement>, keyof ImgOptions | "srcset" | "fetchpriority" | "children">
19
+
20
+ const Image = dynamic(() => "img", { static: true }) as Component<Record<string, unknown>>
21
+
22
+ export function createImg(attributes: ImgAttributes): (props: ImgProps) => JSX.Element {
23
+ return function Img(props) {
24
+ const own = props
25
+ const rest = omit(props, "children", "onLoad", "onError")
26
+ const [isLoaded, setLoaded] = createSignal(false)
27
+ const events = createImgEvents(() => ({ load: own.onLoad as never, error: own.onError as never }), setLoaded)
28
+ let image: HTMLImageElement | undefined
29
+ onSettled(() => {
30
+ if (image) events.replay(image)
31
+ })
32
+ if (props.preload) useHead(() => ({ link: [imagePreloadLink(attributes(rest))] }))
33
+ return (() => {
34
+ const attrs = attributes(rest)
35
+ const imgAttrs = {
36
+ onLoad: events.load,
37
+ onError: events.error,
38
+ ref: (node: HTMLImageElement) => (image = node),
39
+ ...applyPlaceholder(attrs, rest, isLoaded()),
40
+ }
41
+ const child = own.children
42
+ if (typeof child === "function")
43
+ return (child as (state: ImgState) => JSX.Element)({ imgAttrs, src: String(attrs.src), isLoaded: isLoaded() })
44
+ return createComponent(Image, imgAttrs)
45
+ }) as unknown as JSX.Element
46
+ }
47
+ }
@@ -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
+ }