@uln/manage 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,29 @@
3
3
  `@uln/manage` on npm. Each release has a `## <version> — <YYYY-MM-DD>` section here: the Release SDK workflow
4
4
  publishes only a version that has one, and uses it as the GitHub release notes.
5
5
 
6
+ ## 0.5.0 — 2026-12-05
7
+
8
+ Photos load faster on client sites, and sites can optimize the media in their own repository.
9
+
10
+ - `PublicPhoto.placeholder` (a ~16px blurred WebP `data:` URL) and `PublicPhoto.color` (the photo's average colour,
11
+ `#rrggbb`), to show until the photo arrives. Manage makes them in the background, so older photos gain them shortly
12
+ after their first read.
13
+ - `PublicPhoto.srcset` and `PublicFilm.posterSrcset`: the requested width variants as a ready `<img srcset>` string.
14
+ - `ulnMedia()` from `@uln/manage/vite`: `?uln` imports of a site's own images (AVIF/WebP/JPEG at several widths, with a
15
+ placeholder and colour; needs `sharp`) and videos (AV1 and H.264 MP4s with a poster; needs ffmpeg), cached in the
16
+ site's committed `.uln-media/`. Types: `/// <reference types="@uln/manage/media" />`.
17
+
18
+ ## 0.4.0 — 2026-11-11
19
+
20
+ Manage can now keep a site's films on **Mux** as well as Cloudflare Stream. Sites don't change how they read content:
21
+ `playbackUrl`, `posterUrl`/`posterVariants`, `previewUrl` and `previewPlaybackUrl` are signed URLs from whichever
22
+ backend holds the film, and nothing in a record says which. `@uln/hls` plays both.
23
+
24
+ - `mediaOrigins()`: the hosts Manage's media can come from (Stream, Mux's `stream.mux.com`, `image.mux.com` and
25
+ `*.mux.com` chunk hosts, and the Images account), for a site's CSP and preconnects. Sites that pinned their CSP to the
26
+ Stream customer host must switch to it before their first film on Mux, or the browser will block it.
27
+ - The package no longer depends on `@uln/hls`. The preview schemas it re-exported types from now live in Manage.
28
+
6
29
  ## 0.3.1 — 2026-11-11
7
30
 
8
31
  First release on npm (`pnpm add @uln/manage`).
package/README.md CHANGED
@@ -31,16 +31,33 @@ const editUrl = managementUrl("simwize");
31
31
 
32
32
  // No envelopes or metadata/media joins:
33
33
  // films[0].title, films[0].playbackUrl, films[0].posterUrl, films[0].previewUrl
34
- // shoot?.photos[0].url, shoot?.photos[0].variants?.["1280"], shoot?.photos[0].width, shoot?.photos[0].alt
34
+ // shoot?.photos[0].url, shoot?.photos[0].variants?.["1280"], shoot?.photos[0].srcset, shoot?.photos[0].width,
35
+ // shoot?.photos[0].alt, shoot?.photos[0].placeholder (blurred data: URL), shoot?.photos[0].color (#rrggbb)
35
36
  ```
36
37
 
38
+ Every media URL is signed and points straight at whichever backend holds the video (Cloudflare Stream or Mux) or the
39
+ still (Cloudflare Images). A site never learns which: it passes the URLs to `@uln/hls` and its image components as
40
+ supplied. For its Content-Security-Policy and preconnects it asks the package where Manage's media can come from:
41
+
42
+ ```ts
43
+ import { mediaOrigins } from "@uln/manage";
44
+
45
+ const { media, images, preconnect } = mediaOrigins();
46
+ // `media-src 'self' blob: ${media.join(" ")}`, `connect-src 'self' ${media.join(" ")}` (HLS fetches segments),
47
+ // `img-src 'self' data: ${images.join(" ")}`; <link rel="preconnect"> to each of `preconnect`.
48
+ ```
49
+
50
+ A backend Manage adds later brings its hosts with an SDK release; nothing else in the site changes.
51
+
37
52
  Lists and individual records use the same ready-to-display shapes:
38
53
 
39
54
  - `films()` — film metadata, `playbackUrl`, `posterUrl`, optional `previewUrl` (MP4), `previewPlaybackUrl` (the same preview as adaptive HLS) and `posterVariants`, and `expiresAt`.
40
55
  - `film(id)` — one complete public film, or `undefined` when missing or hidden.
41
- - `shoots()` — ordered public shoots, each with its ordered `photos` (URL, dimensions, alt text and expiry).
56
+ - `shoots()` — ordered public shoots, each with its ordered `photos` (URL, dimensions, alt text and expiry), plus a
57
+ blurred `placeholder` and average `color` to show while each loads (absent for a moment after an upload).
42
58
  - Every content method takes optional `sizes` (`photoWidths`, `posterWidths`): one signed URL per width comes back
43
- in `photo.variants` / `film.posterVariants`. Manage holds no size preferences; each site asks for its own.
59
+ in `photo.variants` / `film.posterVariants`, and as ready `srcset` strings in `photo.srcset` / `film.posterSrcset`.
60
+ Manage holds no size preferences; each site asks for its own.
44
61
  - `shoot(id)` — one complete public shoot with its photos, or `undefined` when missing or hidden.
45
62
  - `contacts()` — ordered `{ id, label, email }` contact lines.
46
63
 
@@ -95,6 +112,63 @@ The build writes `/.well-known/uln-packages.json` into the client output (the de
95
112
  site's `packageManager`. It is a static file, served like any other asset; it names package versions only. Server code
96
113
  can import the same report: `import { report } from "virtual:uln-packages"`. The contract is `src/package-report.ts`.
97
114
 
115
+ ## Optimizing the site's own images and videos
116
+
117
+ `ulnMedia()` optimizes the media committed in the site's repository (heroes, logos, background loops) at build time.
118
+ Content edited in Manage doesn't go through it: that keeps coming from its providers.
119
+
120
+ ```sh
121
+ pnpm add -D sharp # images; videos also need ffmpeg on the machine that first encodes them
122
+ ```
123
+
124
+ ```ts
125
+ // vite.config.ts
126
+ import { ulnMedia, ulnPackages } from "@uln/manage/vite";
127
+
128
+ export default defineConfig({ plugins: [ulnMedia(), ulnPackages() /* , … */] });
129
+ ```
130
+
131
+ ```ts
132
+ // vite-env.d.ts (or any .d.ts the site includes)
133
+ /// <reference types="@uln/manage/media" />
134
+ ```
135
+
136
+ Import a file with `?uln`:
137
+
138
+ ```tsx
139
+ import hero from "./hero.jpg?uln";
140
+ import loop from "./loop.mov?uln&poster=2.5"; // poster frame at 2.5s (default 0)
141
+
142
+ <picture>
143
+ {hero.sources.map((s) => <source key={s.type} type={s.type} srcSet={s.srcset} sizes="100vw" />)}
144
+ <img src={hero.src} srcSet={hero.srcset} sizes="100vw" width={hero.width} height={hero.height} alt=""
145
+ style={{ background: `${hero.color} url(${hero.placeholder}) center / cover` }} />
146
+ </picture>
147
+
148
+ <video autoPlay muted loop playsInline poster={loop.poster.src} width={loop.width} height={loop.height}>
149
+ {loop.sources.map((s) => <source key={s.src} src={s.src} type={s.type} />)}
150
+ </video>
151
+ ```
152
+
153
+ - **Images** (`jpg`, `png`, `webp`, `avif`, `tiff`, `heic`): AVIF, WebP and a JPEG fallback (PNG when the image has
154
+ transparency) at 480–2560px wide, never wider than the original; EXIF orientation applied, metadata stripped. You
155
+ get `src`, `srcset`, `sources` (best first, for `<picture>`), `width`/`height`, a ~200-byte blurred `placeholder`
156
+ (`data:` URL) and the dominant `color`.
157
+ - **Videos** (`mp4`, `mov`, `m4v`, `webm`, `mkv`): AV1 and H.264 MP4s (AAC sound, `faststart`), at most 1920px wide,
158
+ each `type` with its exact `codecs` so a browser takes the first it can decode, plus `poster` (an optimized image as
159
+ above), `width`/`height`, `duration` and `audio`.
160
+
161
+ **Commit `.uln-media/`.** Every encode is cached there, keyed by the file's bytes and the settings, and built from as
162
+ ordinary hashed assets. Workers Builds has no ffmpeg, so a video must already be encoded there: run `pnpm dev` (or a
163
+ build) once where ffmpeg is installed (`brew install ffmpeg`) and commit the folder with the video. A build that meets
164
+ an unencoded video without ffmpeg fails and says so. Images encode anywhere sharp installs, Workers Builds included,
165
+ but committing them too keeps builds fast. A changed file or setting gets a new entry; delete entries no longer
166
+ imported. For large videos consider Git LFS (`git lfs track ".uln-media/**/*.mp4"`; Workers Builds has `git-lfs`).
167
+
168
+ Options, all optional: `ulnMedia({ widths, maxWidth, quality: { avif, webp, jpeg }, video: { maxWidth, formats:
169
+ ["av1", "h264"], audio, posterTime }, cacheDir, ffmpeg, ffprobe })`. `video: { audio: false }` strips the sound (e.g.
170
+ for background loops); `formats: ["h264"]` skips the slower AV1 encode.
171
+
98
172
  ## Developing and publishing
99
173
 
100
174
  The package is built from this repository: `sdk/` holds its entry points, and its types come from Manage's
package/dist/index.js CHANGED
@@ -17,63 +17,122 @@ var t = (e, t) => ({
17
17
  });
18
18
  t("photoWidths", "Photo widths the site displays; each comes back in `variants`."), t("posterWidths", "Poster widths the site displays; each comes back in `posterVariants`.");
19
19
  // src/public-content.ts
20
- function n({ film: e, playback: t, poster: n, posterVariants: r, preview: i, previewPlayback: a }) {
21
- let o = [
20
+ function n(e, t) {
21
+ let n = t !== void 0 && t > 1 ? Math.round(t) : Infinity, r = /* @__PURE__ */ new Map(), i = Object.entries(e).sort(([e], [t]) => Number(e) - Number(t));
22
+ for (let [e, t] of i) {
23
+ let i = Math.min(Number(e), n);
24
+ Number.isFinite(i) && i > 0 && !r.has(i) && r.set(i, t);
25
+ }
26
+ return [...r].map(([e, t]) => `${t} ${e}w`).join(", ");
27
+ }
28
+ function r({ film: e, playback: t, poster: n, posterVariants: r, preview: i, previewPlayback: o }) {
29
+ let s = [
22
30
  t.expiresAt,
23
31
  n.expiresAt,
24
32
  i?.expiresAt,
25
- a?.expiresAt
26
- ].filter((e) => typeof e == "number"), s = o.length ? Math.min(...o) : null, { previewAsset: c, previewPreparation: l, frameImages: u, cachedFrames: d, processing: f, hidden: p, ...m } = e;
33
+ o?.expiresAt
34
+ ].filter((e) => typeof e == "number"), c = s.length ? Math.min(...s) : null, { previewAsset: l, previewPreparation: u, frameImages: d, cachedFrames: f, processing: p, hidden: m, videoProvider: h, videoPlaybackId: g, ..._ } = e;
27
35
  return {
28
- ...m,
36
+ ..._,
29
37
  playbackUrl: t.url,
30
38
  posterUrl: n.url,
31
- ...r ? { posterVariants: Object.fromEntries(Object.entries(r).map(([e, t]) => [e, t.url])) } : {},
39
+ ...r ? a(r) : {},
32
40
  ...i ? {
33
41
  previewUrl: i.url,
34
- previewStart: c?.sourceStart ?? e.previewStart ?? 0,
35
- ...c?.size ? { previewBytes: c.size } : {}
42
+ previewStart: l?.sourceStart ?? e.previewStart ?? 0,
43
+ ...l?.size ? { previewBytes: l.size } : {}
36
44
  } : {},
37
- ...a ? {
38
- previewPlaybackUrl: a.url,
39
- ...i ? {} : { previewStart: c?.sourceStart ?? e.previewStart ?? 0 }
45
+ ...o ? {
46
+ previewPlaybackUrl: o.url,
47
+ ...i ? {} : { previewStart: l?.sourceStart ?? e.previewStart ?? 0 }
40
48
  } : {},
41
- expiresAt: s
49
+ expiresAt: c
50
+ };
51
+ }
52
+ function i(e) {
53
+ return Object.fromEntries(Object.entries(e).map(([e, t]) => [e, t.url]));
54
+ }
55
+ function a(e) {
56
+ let t = i(e);
57
+ return {
58
+ posterVariants: t,
59
+ posterSrcset: n(t)
42
60
  };
43
61
  }
44
- function r({ shoot: e, photos: t }) {
45
- let { photos: n, hidden: r, ...i } = e;
62
+ function o({ shoot: e, photos: t }) {
63
+ let { photos: r, hidden: a, ...o } = e;
46
64
  return {
47
- ...i,
48
- photos: t.map(({ photo: e, image: t, variants: n }) => ({
49
- ...e,
50
- url: t.url,
51
- ...n ? { variants: Object.fromEntries(Object.entries(n).map(([e, t]) => [e, t.url])) } : {},
52
- expiresAt: t.expiresAt
53
- }))
65
+ ...o,
66
+ photos: t.map(({ photo: e, image: t, variants: r, preview: a }) => {
67
+ let o = r ? i(r) : void 0;
68
+ return {
69
+ ...e,
70
+ url: t.url,
71
+ ...o ? {
72
+ variants: o,
73
+ srcset: n(o, e.width)
74
+ } : {},
75
+ ...a ? {
76
+ placeholder: a.placeholder,
77
+ color: a.color
78
+ } : {},
79
+ expiresAt: t.expiresAt
80
+ };
81
+ })
82
+ };
83
+ }
84
+ // src/media-origins.ts
85
+ var s = {
86
+ streamCustomerCode: "nuayb0iz1dy4986k",
87
+ imagesAccountHash: "SSUBLwYw6Bk_Rd7fv37_lw"
88
+ }, c = {
89
+ stream: "https://stream.mux.com",
90
+ hosts: "https://*.mux.com",
91
+ image: "https://image.mux.com"
92
+ };
93
+ function l(e = s) {
94
+ if (!/^[a-z0-9]{8,64}$/.test(e.streamCustomerCode)) throw Error("Expected a Stream customer code");
95
+ if (!/^[A-Za-z0-9_-]{8,64}$/.test(e.imagesAccountHash)) throw Error("Expected an Images account hash");
96
+ let t = `https://customer-${e.streamCustomerCode}.cloudflarestream.com`;
97
+ return {
98
+ media: [
99
+ t,
100
+ c.stream,
101
+ c.hosts
102
+ ],
103
+ images: [
104
+ `https://imagedelivery.net/${e.imagesAccountHash}/`,
105
+ t,
106
+ c.image
107
+ ],
108
+ preconnect: [
109
+ t,
110
+ c.stream,
111
+ c.image
112
+ ]
54
113
  };
55
114
  }
56
115
  // sdk/index.ts
57
- function i(e) {
116
+ function u(e) {
58
117
  return {
59
118
  async films(t) {
60
- return (await e.filmsContent(t)).films.map(n);
119
+ return (await e.filmsContent(t)).films.map(r);
61
120
  },
62
- async film(t, r) {
63
- let i = await e.filmContent(t, r);
64
- return i ? n(i) : void 0;
121
+ async film(t, n) {
122
+ let i = await e.filmContent(t, n);
123
+ return i ? r(i) : void 0;
65
124
  },
66
125
  async shoots(t) {
67
- return (await e.stillsContent(t)).shoots.map(r);
126
+ return (await e.stillsContent(t)).shoots.map(o);
68
127
  },
69
128
  async shoot(t, n) {
70
- let i = await e.shootContent(t, n);
71
- return i ? r(i) : void 0;
129
+ let r = await e.shootContent(t, n);
130
+ return r ? o(r) : void 0;
72
131
  },
73
132
  contacts: () => e.contactsContent()
74
133
  };
75
134
  }
76
- function a(t) {
135
+ function d(t) {
77
136
  let n = `${new URL(t.origin ?? "https://manage.uln.industries").origin}/api/content/v1`, r = t.fetch ?? ((e, t) => fetch(e, t));
78
137
  async function i(e, i, a = !1) {
79
138
  let o = await r(`${n}${e}`, { headers: {
@@ -97,10 +156,10 @@ function a(t) {
97
156
  contacts: () => i("/contacts", "contacts")
98
157
  };
99
158
  }
100
- function o(e, t = "https://manage.uln.industries") {
159
+ function f(e, t = "https://manage.uln.industries") {
101
160
  if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(e)) throw Error("Invalid site id");
102
161
  let n = new URL(t);
103
162
  if (n.protocol !== "https:" && (n.protocol !== "http:" || n.hostname !== "localhost")) throw Error("Manage requires HTTPS (or localhost)");
104
163
  return n.pathname = `/sites/${e}`, n.search = "", n.hash = "", n.toString();
105
164
  }
106
- export { a as createHttpManagementClient, i as createManagementClient, o as managementUrl };
165
+ export { s as MANAGE_MEDIA_ACCOUNT, d as createHttpManagementClient, u as createManagementClient, f as managementUrl, l as mediaOrigins };
@@ -2,6 +2,7 @@ import { type MediaSizes } from "../src/media-sizes.ts";
2
2
  import { type PublicFilm, type PublicShoot } from "../src/public-content.ts";
3
3
  import type { PublicCatalogRpc } from "../src/rpc-types.ts";
4
4
  import type { SiteContact } from "../src/schema.ts";
5
+ export { MANAGE_MEDIA_ACCOUNT, type MediaOrigins, mediaOrigins } from "../src/media-origins.ts";
5
6
  export type { MediaSizes } from "../src/media-sizes.ts";
6
7
  export type { PublicFilm, PublicPhoto, PublicShoot } from "../src/public-content.ts";
7
8
  export type { PublicCatalogProps, PublicCatalogRpc } from "../src/rpc-types.ts";
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Types for `?uln` media imports (`ulnMedia()` from `@uln/manage/vite`). Reference it once in the site, e.g. in
3
+ * `vite-env.d.ts`: `/// <reference types="@uln/manage/media" />`.
4
+ */
5
+ declare module "*.jpg?uln" {
6
+ const image: import("./media-types.ts").UlnImage;
7
+ export default image;
8
+ }
9
+ declare module "*.jpeg?uln" {
10
+ const image: import("./media-types.ts").UlnImage;
11
+ export default image;
12
+ }
13
+ declare module "*.png?uln" {
14
+ const image: import("./media-types.ts").UlnImage;
15
+ export default image;
16
+ }
17
+ declare module "*.webp?uln" {
18
+ const image: import("./media-types.ts").UlnImage;
19
+ export default image;
20
+ }
21
+ declare module "*.avif?uln" {
22
+ const image: import("./media-types.ts").UlnImage;
23
+ export default image;
24
+ }
25
+ declare module "*.tif?uln" {
26
+ const image: import("./media-types.ts").UlnImage;
27
+ export default image;
28
+ }
29
+ declare module "*.tiff?uln" {
30
+ const image: import("./media-types.ts").UlnImage;
31
+ export default image;
32
+ }
33
+ declare module "*.heic?uln" {
34
+ const image: import("./media-types.ts").UlnImage;
35
+ export default image;
36
+ }
37
+ declare module "*.heif?uln" {
38
+ const image: import("./media-types.ts").UlnImage;
39
+ export default image;
40
+ }
41
+ declare module "*.mp4?uln" {
42
+ const video: import("./media-types.ts").UlnVideo;
43
+ export default video;
44
+ }
45
+ declare module "*.mov?uln" {
46
+ const video: import("./media-types.ts").UlnVideo;
47
+ export default video;
48
+ }
49
+ declare module "*.m4v?uln" {
50
+ const video: import("./media-types.ts").UlnVideo;
51
+ export default video;
52
+ }
53
+ declare module "*.webm?uln" {
54
+ const video: import("./media-types.ts").UlnVideo;
55
+ export default video;
56
+ }
57
+ declare module "*.mkv?uln" {
58
+ const video: import("./media-types.ts").UlnVideo;
59
+ export default video;
60
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * What a `?uln` media import gives a site's code (`ulnMedia()` in `@uln/manage/vite`). Plain data, no runtime:
3
+ * every URL is a hashed asset in the site's own build.
4
+ */
5
+ /** One encoding of an image or video, newest format first in `sources`: browsers take the first they support. */
6
+ export interface UlnImageSource {
7
+ /** MIME type for `<source type>`, e.g. `image/avif`. */
8
+ type: string;
9
+ /** Width-descriptor `srcset`: `/assets/hero-640.avif 640w, …`. */
10
+ srcset: string;
11
+ }
12
+ export interface UlnImage {
13
+ /** The largest fallback-format file (JPEG, or PNG for images with transparency): `<img src>`. */
14
+ src: string;
15
+ /** Every width in the fallback format: `<img srcset>`. */
16
+ srcset: string;
17
+ /** Modern formats for `<picture><source>`, best first (AVIF, then WebP). */
18
+ sources: UlnImageSource[];
19
+ /** The intrinsic size of the largest file: set both on `<img>` so the page doesn't shift when it loads. */
20
+ width: number;
21
+ height: number;
22
+ /** A tiny blurred preview as a `data:` URL (a few hundred bytes): a background until the image arrives. */
23
+ placeholder: string;
24
+ /** The image's dominant colour as `#rrggbb`, for an even cheaper placeholder. */
25
+ color: string;
26
+ }
27
+ export interface UlnVideoSource {
28
+ src: string;
29
+ /** MIME type with codecs, e.g. `video/mp4; codecs="av01.0.08M.08"`, so browsers skip what they can't decode. */
30
+ type: string;
31
+ }
32
+ export interface UlnVideo {
33
+ /** For `<video><source>`, best first: AV1, then H.264 that every browser plays. */
34
+ sources: UlnVideoSource[];
35
+ /** A frame of the video as an optimized image: `<video poster={poster.src}>`, or a `<picture>` before playback. */
36
+ poster: UlnImage;
37
+ width: number;
38
+ height: number;
39
+ /** Seconds. */
40
+ duration: number;
41
+ /** Whether the encodes have sound. A silent video can autoplay muted without a mute control. */
42
+ audio: boolean;
43
+ }
@@ -0,0 +1,45 @@
1
+ import type { Plugin } from "vite";
2
+ export type { UlnImage, UlnImageSource, UlnVideo, UlnVideoSource } from "./media-types.ts";
3
+ export declare const MEDIA_QUERY = "uln";
4
+ export declare const IMAGE_EXTENSIONS: string[];
5
+ export declare const VIDEO_EXTENSIONS: string[];
6
+ export type VideoFormat = "av1" | "h264";
7
+ export interface UlnMediaOptions {
8
+ /** Where encodes are kept, relative to Vite's `root`. Commit it. Default `.uln-media`. */
9
+ cacheDir?: string;
10
+ /** Image widths to offer, in pixels; widths above the image's own (or `maxWidth`) are dropped. */
11
+ widths?: number[];
12
+ /** The widest image file produced. Default 2560. */
13
+ maxWidth?: number;
14
+ /** Encoder quality, 1–100. Defaults: AVIF 50, WebP 75, JPEG 80. */
15
+ quality?: {
16
+ avif?: number;
17
+ webp?: number;
18
+ jpeg?: number;
19
+ };
20
+ video?: {
21
+ /** The widest video produced. Default 1920. */
22
+ maxWidth?: number;
23
+ /** Encodes to produce, best first. Default `["av1", "h264"]`; keep `h264` last as the one every browser plays. */
24
+ formats?: VideoFormat[];
25
+ /** Keep the soundtrack (AAC). Default true; false strips it, e.g. for background loops. */
26
+ audio?: boolean;
27
+ /** Seconds into the video for the poster frame. Default 0; per file with `?uln&poster=2.5`. */
28
+ posterTime?: number;
29
+ };
30
+ /** The ffmpeg and ffprobe commands. Default `ffmpeg` and `ffprobe` on the PATH. */
31
+ ffmpeg?: string;
32
+ ffprobe?: string;
33
+ }
34
+ /** `hero.jpg?uln&poster=2` → the file and its params, or null when the import isn't ours. */
35
+ export declare function parseMediaId(id: string): {
36
+ file: string;
37
+ kind: "image" | "video";
38
+ params: URLSearchParams;
39
+ } | null;
40
+ /** The `codecs` parameter for an encode, from what ffprobe reads back out of it. */
41
+ export declare function codecsOf(video: {
42
+ codec_name?: string | undefined;
43
+ level?: number | undefined;
44
+ }, audio: boolean): string;
45
+ export declare function ulnMedia(options?: UlnMediaOptions): Plugin;
@@ -10,3 +10,4 @@ export declare function packageReport(root: string, now?: Date): PackageReport;
10
10
  /** The report as a module of the site's own code: `import { report } from "virtual:uln-packages"`. */
11
11
  export declare const VIRTUAL_MODULE = "virtual:uln-packages";
12
12
  export declare function ulnPackages(options?: UlnPackagesOptions): Plugin;
13
+ export { type UlnImage, type UlnImageSource, type UlnMediaOptions, type UlnVideo, type UlnVideoSource, ulnMedia, } from "./media.ts";
@@ -418,6 +418,10 @@ export declare function contentApiSpec(server: string): {
418
418
  readonly format: "uri";
419
419
  };
420
420
  };
421
+ readonly posterSrcset: {
422
+ readonly type: "string";
423
+ readonly description: "`posterVariants` as an `<img srcset>` (`url 640w, url 1280w`), narrowest first.";
424
+ };
421
425
  readonly previewUrl: {
422
426
  readonly type: "string";
423
427
  readonly format: "uri";
@@ -519,6 +523,19 @@ export declare function contentApiSpec(server: string): {
519
523
  readonly format: "uri";
520
524
  };
521
525
  };
526
+ readonly srcset: {
527
+ readonly type: "string";
528
+ readonly description: string;
529
+ };
530
+ readonly placeholder: {
531
+ readonly type: "string";
532
+ readonly description: string;
533
+ };
534
+ readonly color: {
535
+ readonly type: "string";
536
+ readonly pattern: "^#[0-9a-f]{6}$";
537
+ readonly description: "The photo's average colour as `#rrggbb`, for a solid placeholder. Absent with `placeholder`.";
538
+ };
522
539
  readonly expiresAt: {
523
540
  readonly type: readonly ["integer", "null"];
524
541
  readonly description: "Unix milliseconds when the earliest signed URL in this record expires; null when nothing expires. Refresh before then.";
@@ -14,11 +14,20 @@ export interface FilmContent {
14
14
  /** The preview as an adaptive stream (HLS), when it was made with one. */
15
15
  previewPlayback?: MediaUrl;
16
16
  }
17
+ /** A photo's blurred preview and colour (`photo_previews`, made by `src/photo-previews.server.ts`). */
18
+ export interface PhotoPreview {
19
+ /** A tiny blurred WebP as a `data:` URL. */
20
+ placeholder: string;
21
+ /** The photo's average colour, `#rrggbb`. */
22
+ color: string;
23
+ }
17
24
  export interface PhotoContent {
18
25
  photo: Photo;
19
26
  image: MediaUrl;
20
27
  /** The photo scaled down to each width the site asked for (`MediaSizes.photoWidths`), keyed by width. */
21
28
  variants?: Record<string, MediaUrl>;
29
+ /** Its blurred preview and colour, once made (`src/photo-previews.server.ts`). */
30
+ preview?: PhotoPreview;
22
31
  }
23
32
  export interface ShootContent {
24
33
  shoot: Shoot;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Where the media Manage hands out is served from, for a site's Content-Security-Policy and preconnects: every video
3
+ * backend Manage may store a film in (Cloudflare Stream, Mux) and the Images account for stills. A site allows these
4
+ * and never needs to know which backend holds which film; the URLs it gets are already signed.
5
+ *
6
+ * Client-safe and part of the SDK (`mediaOrigins()` from `@uln/manage`): only grows. A new backend adds its hosts here,
7
+ * and sites pick them up with the next SDK release.
8
+ */
9
+ /** Manage's media account: Stream's customer code and the Images account hash (both public). */
10
+ export declare const MANAGE_MEDIA_ACCOUNT: {
11
+ readonly streamCustomerCode: "nuayb0iz1dy4986k";
12
+ readonly imagesAccountHash: "SSUBLwYw6Bk_Rd7fv37_lw";
13
+ };
14
+ export interface MediaOrigins {
15
+ /** Video, HLS playlists and segments: `media-src` (and `connect-src`, since HLS players fetch segments). */
16
+ media: string[];
17
+ /** Posters and photos: `img-src`. */
18
+ images: string[];
19
+ /** The hosts worth a `preconnect`: where a page's first video and poster come from. */
20
+ preconnect: string[];
21
+ }
22
+ export declare function mediaOrigins(account?: {
23
+ streamCustomerCode: string;
24
+ imagesAccountHash: string;
25
+ }): MediaOrigins;
@@ -0,0 +1,52 @@
1
+ /**
2
+ * A film's preview clip, whatever video backend holds it: how long it may run, which part of the film it shows, and
3
+ * the run that prepares it. Client-safe (part of the record shapes in `./schema.ts`). Moved here from
4
+ * `@uln/hls/cloudflare`, which no longer exists: storing and cutting clips is Manage's job, playing them is `@uln/hls`'s.
5
+ */
6
+ import { z } from "zod";
7
+ export declare const PREVIEW_MAX_DURATION_SECONDS = 15;
8
+ /** The clip length when a film sets a start but no end. */
9
+ export declare const DEFAULT_PREVIEW_DURATION_SECONDS = 6;
10
+ /** Queued or processing preparations older than this are treated as stuck. */
11
+ export declare const STALE_PREVIEW_PREPARATION_MS: number;
12
+ /** A stored progressive MP4 preview: the backend's id for it, what it is, and which part of the film it shows. */
13
+ export declare const previewAssetSchema: z.ZodObject<{
14
+ key: z.ZodString;
15
+ version: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
16
+ contentType: z.ZodLiteral<"video/mp4">;
17
+ size: z.ZodNumber;
18
+ duration: z.ZodNumber;
19
+ sourceStart: z.ZodNumber;
20
+ source: z.ZodOptional<z.ZodEnum<{
21
+ automatic: "automatic";
22
+ manual: "manual";
23
+ }>>;
24
+ }, z.core.$strip>;
25
+ export type PreviewAsset = z.infer<typeof previewAssetSchema>;
26
+ /** A queued or running automatic preview, owned by one workflow run. */
27
+ export declare const previewPreparationSchema: z.ZodObject<{
28
+ workflowId: z.ZodString;
29
+ status: z.ZodEnum<{
30
+ failed: "failed";
31
+ processing: "processing";
32
+ queued: "queued";
33
+ }>;
34
+ sourceStart: z.ZodNumber;
35
+ requestedDuration: z.ZodNumber;
36
+ updatedAt: z.ZodString;
37
+ error: z.ZodOptional<z.ZodString>;
38
+ }, z.core.$strip>;
39
+ export type PreviewPreparation = z.infer<typeof previewPreparationSchema>;
40
+ export interface PreviewRange {
41
+ sourceStart: number;
42
+ requestedDuration: number;
43
+ }
44
+ /** The clip to cut for a film's preview start and end: never negative, at most 15 s, 6 s without an end. */
45
+ export declare function previewRange(previewStart?: number, previewEnd?: number): PreviewRange;
46
+ /** Convert a time on the clip's own timeline back to the film's. */
47
+ export declare function previewTimeInFilm(asset: Pick<PreviewAsset, "sourceStart">, clipTime: number): number;
48
+ /**
49
+ * A film needs an automatic preview queued when it has none and no live
50
+ * preparation: none yet, a failed one, or one stuck past the stale window.
51
+ */
52
+ export declare function needsPreviewBackfill(asset: PreviewAsset | undefined, preparation: PreviewPreparation | undefined, nowMs: number): boolean;
@@ -1,5 +1,6 @@
1
1
  /**
2
2
  * What a website receives: ready-to-display records with direct provider URLs, and no storage or workflow details.
3
+ * Nothing here says which backend (Cloudflare Stream, Mux) holds a video: the URLs are signed and played the same way.
3
4
  * The one projection from Manage's content to these shapes, shared by the SDK's service-binding client
4
5
  * (`sdk/index.ts`) and the HTTP content API (`worker/content-api.ts`). Client-safe: no Workers runtime, no database.
5
6
  * Part of the public contract: only grows.
@@ -7,11 +8,13 @@
7
8
  import type { FilmContent, ShootContent } from "./content-types.ts";
8
9
  import type { Film, Photo, Shoot } from "./schema.ts";
9
10
  /** Ready to display: metadata and direct provider URLs, with no storage/workflow details. */
10
- export type PublicFilm = Omit<Film, "previewAsset" | "previewPreparation" | "frameImages" | "cachedFrames" | "processing" | "hidden"> & {
11
+ export type PublicFilm = Omit<Film, "previewAsset" | "previewPreparation" | "frameImages" | "cachedFrames" | "processing" | "hidden" | "videoProvider" | "videoPlaybackId"> & {
11
12
  playbackUrl: string;
12
13
  posterUrl: string;
13
14
  /** The poster at each width the site asked for (`MediaSizes.posterWidths`), keyed by width, e.g. `["640"]`. */
14
15
  posterVariants?: Record<string, string>;
16
+ /** `posterVariants` as an `<img srcset>`, narrowest first. */
17
+ posterSrcset?: string;
15
18
  /** The preview clip as one progressive MP4 (540p, silent). */
16
19
  previewUrl?: string;
17
20
  /**
@@ -29,10 +32,21 @@ export type PublicPhoto = Photo & {
29
32
  url: string;
30
33
  /** The photo scaled down to each width the site asked for (`MediaSizes.photoWidths`), keyed by width. */
31
34
  variants?: Record<string, string>;
35
+ /** `variants` as an `<img srcset>` (`url 480w, url 960w`), widest no wider than the photo itself. */
36
+ srcset?: string;
37
+ /** A tiny blurred preview (`data:image/webp;base64,…`, a few hundred bytes) to show until the photo loads. */
38
+ placeholder?: string;
39
+ /** The photo's average colour (`#rrggbb`), an even lighter placeholder. */
40
+ color?: string;
32
41
  expiresAt: number | null;
33
42
  };
34
43
  export type PublicShoot = Omit<Shoot, "photos" | "hidden"> & {
35
44
  photos: PublicPhoto[];
36
45
  };
46
+ /**
47
+ * Width variants as a `srcset`, narrowest first. Images scales down only, so a width past the original's (`maxWidth`,
48
+ * when known) is served at the original's size: it is listed once, at its real width.
49
+ */
50
+ export declare function widthSrcset(variants: Record<string, string>, maxWidth?: number): string;
37
51
  export declare function publicFilm({ film, playback, poster, posterVariants, preview, previewPlayback, }: FilmContent): PublicFilm;
38
52
  export declare function publicShoot({ shoot, photos }: ShootContent): PublicShoot;
@@ -2,9 +2,9 @@
2
2
  * The catalog's record shapes, shared by the Manage Worker and every client site. Client-safe: no Workers
3
3
  * runtime, no database. Sites import these types to read what the RPC returns.
4
4
  */
5
- import { type PreviewPreparation } from "@uln/hls/cloudflare";
6
5
  import { z } from "zod";
7
6
  import { type CategoryIndexGroup, type FilmCategory } from "./lib/category-order.ts";
7
+ import { type PreviewPreparation } from "./preview-asset.ts";
8
8
  export declare const creditSchema: z.ZodObject<{
9
9
  role: z.ZodString;
10
10
  name: z.ZodString;
@@ -12,8 +12,27 @@ export declare const creditSchema: z.ZodObject<{
12
12
  }, z.core.$strip>;
13
13
  export type Credit = z.infer<typeof creditSchema>;
14
14
  /**
15
- * A film's preview: the progressive MP4 `@uln/hls` describes (`key`), and, for previews made since adaptive previews,
16
- * the video backend's id of the same clip at full quality, played as an adaptive stream (`playbackKey`).
15
+ * The video backends Manage can keep a site's videos in. Which one holds a video is recorded with it (D1's
16
+ * `video_provider` / `preview_provider`) and shown in Manage; sites never see it, only the signed URLs it serves.
17
+ */
18
+ export declare const VIDEO_PROVIDERS: readonly ["cloudflare", "mux"];
19
+ export declare const videoProviderSchema: z.ZodEnum<{
20
+ cloudflare: "cloudflare";
21
+ mux: "mux";
22
+ }>;
23
+ export type VideoProviderName = z.infer<typeof videoProviderSchema>;
24
+ /** Where a film's video comes from: a backend Manage uploaded it to, or an imported external HLS URL. */
25
+ export declare const filmVideoSourceSchema: z.ZodEnum<{
26
+ cloudflare: "cloudflare";
27
+ external: "external";
28
+ mux: "mux";
29
+ }>;
30
+ export type FilmVideoSource = z.infer<typeof filmVideoSourceSchema>;
31
+ /**
32
+ * A film's preview: the progressive MP4 (`key`, the backend's id for it), and, for previews made since adaptive
33
+ * previews, the backend's id of the same clip played as an adaptive stream (`playbackKey`). `provider` is the backend
34
+ * that holds both (Cloudflare Stream when absent, as for every preview made before Mux); a Mux preview also carries
35
+ * the signed `playbackId` its URLs are made from.
17
36
  */
18
37
  export declare const filmPreviewAssetSchema: z.ZodObject<{
19
38
  key: z.ZodString;
@@ -27,6 +46,11 @@ export declare const filmPreviewAssetSchema: z.ZodObject<{
27
46
  manual: "manual";
28
47
  }>>;
29
48
  playbackKey: z.ZodOptional<z.ZodString>;
49
+ provider: z.ZodOptional<z.ZodEnum<{
50
+ cloudflare: "cloudflare";
51
+ mux: "mux";
52
+ }>>;
53
+ playbackId: z.ZodOptional<z.ZodString>;
30
54
  }, z.core.$strip>;
31
55
  export type FilmPreviewAsset = z.infer<typeof filmPreviewAssetSchema>;
32
56
  export declare const filmPreviewPreparationSchema: z.ZodObject<{
@@ -51,6 +75,12 @@ export declare const filmSchema: z.ZodObject<{
51
75
  client: z.ZodOptional<z.ZodString>;
52
76
  clientUrl: z.ZodOptional<z.ZodString>;
53
77
  description: z.ZodOptional<z.ZodString>;
78
+ videoProvider: z.ZodOptional<z.ZodEnum<{
79
+ cloudflare: "cloudflare";
80
+ external: "external";
81
+ mux: "mux";
82
+ }>>;
83
+ videoPlaybackId: z.ZodOptional<z.ZodString>;
54
84
  playbackUrl: z.ZodOptional<z.ZodURL>;
55
85
  posterUrl: z.ZodOptional<z.ZodString>;
56
86
  credits: z.ZodOptional<z.ZodArray<z.ZodObject<{
@@ -77,6 +107,11 @@ export declare const filmSchema: z.ZodObject<{
77
107
  manual: "manual";
78
108
  }>>;
79
109
  playbackKey: z.ZodOptional<z.ZodString>;
110
+ provider: z.ZodOptional<z.ZodEnum<{
111
+ cloudflare: "cloudflare";
112
+ mux: "mux";
113
+ }>>;
114
+ playbackId: z.ZodOptional<z.ZodString>;
80
115
  }, z.core.$strip>>;
81
116
  previewPreparation: z.ZodOptional<z.ZodObject<{
82
117
  workflowId: z.ZodString;
package/dist/vite.js CHANGED
@@ -1,85 +1,481 @@
1
- import { readFileSync as e } from "node:fs";
2
- import { dirname as t, join as n, resolve as r } from "node:path";
1
+ import { existsSync as e, mkdirSync as t, readFileSync as n, renameSync as r, rmSync as i, writeFileSync as a } from "node:fs";
2
+ import { basename as o, dirname as s, extname as c, join as l, resolve as u } from "node:path";
3
+ import { execFile as d } from "node:child_process";
4
+ import { createHash as f } from "node:crypto";
5
+ import { promisify as p } from "node:util";
6
+ import { z as m } from "zod";
3
7
  // src/package-report.ts
4
- var i = "/.well-known/uln-packages.json", a = [
8
+ var h = "/.well-known/uln-packages.json", g = [
5
9
  "dependencies",
6
10
  "devDependencies",
7
11
  "peerDependencies",
8
12
  "optionalDependencies"
9
- ], o = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
10
- function s(e) {
11
- return typeof e == "string" && e.length <= 64 && o.test(e);
13
+ ], _ = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
14
+ function v(e) {
15
+ return typeof e == "string" && e.length <= 64 && _.test(e);
16
+ }
17
+ // sdk/media.ts
18
+ var y = p(d), b = 1, x = [
19
+ ".jpg",
20
+ ".jpeg",
21
+ ".png",
22
+ ".webp",
23
+ ".avif",
24
+ ".tif",
25
+ ".tiff",
26
+ ".heic",
27
+ ".heif"
28
+ ], S = [
29
+ ".mp4",
30
+ ".mov",
31
+ ".m4v",
32
+ ".webm",
33
+ ".mkv"
34
+ ];
35
+ function C(e) {
36
+ return {
37
+ widths: e.widths ?? [
38
+ 480,
39
+ 768,
40
+ 1080,
41
+ 1440,
42
+ 1920,
43
+ 2560
44
+ ],
45
+ maxWidth: e.maxWidth ?? 2560,
46
+ quality: {
47
+ avif: 50,
48
+ webp: 75,
49
+ jpeg: 80,
50
+ ...e.quality
51
+ },
52
+ video: {
53
+ maxWidth: 1920,
54
+ formats: ["av1", "h264"],
55
+ audio: !0,
56
+ posterTime: 0,
57
+ ...e.video
58
+ },
59
+ ffmpeg: e.ffmpeg ?? "ffmpeg",
60
+ ffprobe: e.ffprobe ?? "ffprobe"
61
+ };
62
+ }
63
+ var w = m.enum([
64
+ "avif",
65
+ "webp",
66
+ "jpeg",
67
+ "png"
68
+ ]), T = m.object({
69
+ width: m.number(),
70
+ height: m.number(),
71
+ widths: m.array(m.number()).min(1),
72
+ formats: m.array(w).min(1),
73
+ placeholder: m.string(),
74
+ color: m.string()
75
+ }), E = m.object({
76
+ width: m.number(),
77
+ height: m.number(),
78
+ duration: m.number(),
79
+ audio: m.boolean(),
80
+ encodes: m.array(m.object({
81
+ file: m.string(),
82
+ type: m.string()
83
+ })).min(1),
84
+ poster: T
85
+ }), D = {
86
+ avif: "image/avif",
87
+ webp: "image/webp",
88
+ jpeg: "image/jpeg",
89
+ png: "image/png"
90
+ }, O = {
91
+ avif: "avif",
92
+ webp: "webp",
93
+ jpeg: "jpg",
94
+ png: "png"
95
+ };
96
+ function k(e) {
97
+ let t = e.indexOf("?");
98
+ if (t < 0) return null;
99
+ let n = new URLSearchParams(e.slice(t + 1));
100
+ if (!n.has("uln")) return null;
101
+ let r = e.slice(0, t), i = c(r).toLowerCase();
102
+ return x.includes(i) ? {
103
+ file: r,
104
+ kind: "image",
105
+ params: n
106
+ } : S.includes(i) ? {
107
+ file: r,
108
+ kind: "video",
109
+ params: n
110
+ } : null;
111
+ }
112
+ function A(e) {
113
+ return o(e, c(e)).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || "media";
114
+ }
115
+ function j(e, t) {
116
+ return f("sha256").update(`${b}\n${JSON.stringify(t)}\n`).update(e).digest("hex").slice(0, 16);
117
+ }
118
+ var M;
119
+ function N() {
120
+ return M ??= import("sharp").then((e) => e.default, () => {
121
+ throw Error("ulnMedia: images need sharp. Add it to the site: pnpm add -D sharp");
122
+ }), M;
123
+ }
124
+ function P(e) {
125
+ return Math.max(0, Math.min(255, Math.round(e))).toString(16).padStart(2, "0");
126
+ }
127
+ async function F(e, t, n, r) {
128
+ let i = await N(), { data: o, info: s } = await i(e, { failOn: "none" }).rotate().toBuffer({ resolveWithObject: !0 }), c = await i(o).stats(), u = Math.min(s.width, r.maxWidth), d = [.../* @__PURE__ */ new Set([...r.widths.filter((e) => e < u), u])].sort((e, t) => e - t), f = [
129
+ "avif",
130
+ "webp",
131
+ c.isOpaque ? "jpeg" : "png"
132
+ ], { quality: p } = r;
133
+ await Promise.all(d.flatMap((e) => f.map(async (r) => {
134
+ let s = i(o).resize({
135
+ width: e,
136
+ withoutEnlargement: !0
137
+ }), c = r === "avif" ? s.avif({
138
+ quality: p.avif,
139
+ effort: 6
140
+ }) : r === "webp" ? s.webp({
141
+ quality: p.webp,
142
+ effort: 6
143
+ }) : r === "jpeg" ? s.jpeg({
144
+ quality: p.jpeg,
145
+ mozjpeg: !0
146
+ }) : s.png({ compressionLevel: 9 });
147
+ a(l(t, `${n}-${e}.${O[r]}`), await c.toBuffer());
148
+ })));
149
+ let m = await i(o).resize({ width: 16 }).webp({ quality: 40 }).toBuffer(), { r: h, g, b: _ } = c.dominant;
150
+ return {
151
+ width: u,
152
+ height: Math.round(s.height * u / s.width),
153
+ widths: d,
154
+ formats: f,
155
+ placeholder: `data:image/webp;base64,${m.toString("base64")}`,
156
+ color: `#${P(h)}${P(g)}${P(_)}`
157
+ };
158
+ }
159
+ var I = m.object({
160
+ streams: m.array(m.object({
161
+ codec_type: m.string(),
162
+ codec_name: m.string().optional(),
163
+ profile: m.string().optional(),
164
+ level: m.number().optional(),
165
+ width: m.number().optional(),
166
+ height: m.number().optional()
167
+ })),
168
+ format: m.object({ duration: m.string().optional() })
169
+ });
170
+ async function L(e, t) {
171
+ let { stdout: n } = await y(e.ffprobe, [
172
+ "-v",
173
+ "error",
174
+ "-print_format",
175
+ "json",
176
+ "-show_streams",
177
+ "-show_format",
178
+ t
179
+ ]), r = I.parse(JSON.parse(n)), i = r.streams.find((e) => e.codec_type === "video");
180
+ if (!i?.width || !i.height) throw Error(`ulnMedia: no video stream in ${t}`);
181
+ return {
182
+ video: i,
183
+ width: i.width,
184
+ height: i.height,
185
+ duration: Number(r.format.duration ?? 0),
186
+ audio: r.streams.some((e) => e.codec_type === "audio")
187
+ };
188
+ }
189
+ function R(e, t) {
190
+ let n = e.level ?? 0, r = e.codec_name === "av1" ? `av01.0.${String(n).padStart(2, "0")}M.08` : `avc1.6400${n.toString(16).padStart(2, "0")}`;
191
+ return t ? `${r}, mp4a.40.2` : r;
192
+ }
193
+ function z(e) {
194
+ return e === "av1" ? [
195
+ "-c:v",
196
+ "libsvtav1",
197
+ "-preset",
198
+ "6",
199
+ "-crf",
200
+ "35"
201
+ ] : [
202
+ "-c:v",
203
+ "libx264",
204
+ "-preset",
205
+ "slow",
206
+ "-crf",
207
+ "23",
208
+ "-profile:v",
209
+ "high"
210
+ ];
211
+ }
212
+ async function B(e) {
213
+ try {
214
+ return await y(e.ffmpeg, ["-version"]), await y(e.ffprobe, ["-version"]), !0;
215
+ } catch {
216
+ return !1;
217
+ }
218
+ }
219
+ async function V(e, t, r, a, o) {
220
+ let { video: s } = o, c = `scale='min(${s.maxWidth},iw)':-2`, u = s.audio ? [
221
+ "-c:a",
222
+ "aac",
223
+ "-b:a",
224
+ "128k"
225
+ ] : ["-an"], d = [], f = {
226
+ width: 0,
227
+ height: 0,
228
+ duration: 0,
229
+ audio: !1
230
+ };
231
+ for (let n of s.formats) {
232
+ let i = `${r}-${n}.mp4`, a = l(t, i);
233
+ await y(o.ffmpeg, [
234
+ "-hide_banner",
235
+ "-loglevel",
236
+ "error",
237
+ "-y",
238
+ "-i",
239
+ e,
240
+ "-map_metadata",
241
+ "-1",
242
+ "-vf",
243
+ c,
244
+ ...z(n),
245
+ "-pix_fmt",
246
+ "yuv420p",
247
+ ...u,
248
+ "-movflags",
249
+ "+faststart",
250
+ a
251
+ ], { maxBuffer: 16777216 });
252
+ let s = await L(o, a);
253
+ f = s, d.push({
254
+ file: i,
255
+ type: `video/mp4; codecs="${R(s.video, s.audio)}"`
256
+ });
257
+ }
258
+ let p = l(t, "poster-source.png");
259
+ await y(o.ffmpeg, [
260
+ "-hide_banner",
261
+ "-loglevel",
262
+ "error",
263
+ "-y",
264
+ "-ss",
265
+ String(a),
266
+ "-i",
267
+ e,
268
+ "-frames:v",
269
+ "1",
270
+ "-vf",
271
+ c,
272
+ p
273
+ ]);
274
+ let m = await F(n(p), t, `${r}-poster`, o);
275
+ return i(p), {
276
+ width: f.width,
277
+ height: f.height,
278
+ duration: f.duration,
279
+ audio: f.audio,
280
+ encodes: d,
281
+ poster: m
282
+ };
283
+ }
284
+ var H = class {
285
+ imports = [];
286
+ url(e) {
287
+ let t = `u${this.imports.length}`;
288
+ return this.imports.push(`import ${t} from ${JSON.stringify(`${e}?no-inline`)};`), t;
289
+ }
290
+ image(e, t, n) {
291
+ let r = (r) => e.widths.map((e) => `${this.url(l(t, `${n}-${e}.${O[r]}`))} + " ${e}w"`).join(" + \", \" + "), i = e.formats[e.formats.length - 1] ?? "jpeg", a = e.widths[e.widths.length - 1] ?? e.width, o = e.formats.slice(0, -1).map((e) => `{ type: ${JSON.stringify(D[e])}, srcset: ${r(e)} }`);
292
+ return `{
293
+ src: ${this.url(l(t, `${n}-${a}.${O[i]}`))},
294
+ srcset: ${r(i)},
295
+ sources: [${o.join(", ")}],
296
+ width: ${e.width},
297
+ height: ${e.height},
298
+ placeholder: ${JSON.stringify(e.placeholder)},
299
+ color: ${JSON.stringify(e.color)},
300
+ }`;
301
+ }
302
+ video(e, t, n) {
303
+ return `{
304
+ sources: [${e.encodes.map((e) => `{ src: ${this.url(l(t, e.file))}, type: ${JSON.stringify(e.type)} }`).join(", ")}],
305
+ poster: ${this.image(e.poster, t, `${n}-poster`)},
306
+ width: ${e.width},
307
+ height: ${e.height},
308
+ duration: ${e.duration},
309
+ audio: ${e.audio},
310
+ }`;
311
+ }
312
+ module(e) {
313
+ return `${this.imports.join("\n")}\nexport default ${e};\n`;
314
+ }
315
+ };
316
+ function U(e, t) {
317
+ try {
318
+ return t.parse(JSON.parse(n(l(e, "meta.json"), "utf8")));
319
+ } catch {
320
+ return null;
321
+ }
322
+ }
323
+ function W(s = {}) {
324
+ let c = C(s), d = u(s.cacheDir ?? ".uln-media"), f = () => void 0, p = /* @__PURE__ */ new Map();
325
+ async function m(e, s, c, u) {
326
+ let m = A(e), h = l(d, `${m}-${j(n(e), s)}`), g = U(h, c);
327
+ if (g) return {
328
+ meta: g,
329
+ dir: h,
330
+ stem: m
331
+ };
332
+ let _ = p.get(h);
333
+ if (_) {
334
+ await _;
335
+ let e = U(h, c);
336
+ if (e) return {
337
+ meta: e,
338
+ dir: h,
339
+ stem: m
340
+ };
341
+ }
342
+ let v = (async () => {
343
+ let n = `${h}.tmp-${process.pid}`;
344
+ i(n, {
345
+ recursive: !0,
346
+ force: !0
347
+ }), t(n, { recursive: !0 });
348
+ try {
349
+ let t = Date.now(), s = await u(n, m);
350
+ return a(l(n, "meta.json"), `${JSON.stringify(s, null, 2)}\n`), i(h, {
351
+ recursive: !0,
352
+ force: !0
353
+ }), r(n, h), f(`ulnMedia: encoded ${o(e)} in ${((Date.now() - t) / 1e3).toFixed(1)}s`), s;
354
+ } catch (e) {
355
+ throw i(n, {
356
+ recursive: !0,
357
+ force: !0
358
+ }), e;
359
+ }
360
+ })();
361
+ p.set(h, v);
362
+ try {
363
+ return {
364
+ meta: c.parse(await v),
365
+ dir: h,
366
+ stem: m
367
+ };
368
+ } finally {
369
+ p.delete(h);
370
+ }
371
+ }
372
+ return {
373
+ name: "uln-media",
374
+ enforce: "pre",
375
+ configResolved(e) {
376
+ d = u(e.root, s.cacheDir ?? ".uln-media"), f = (t) => e.logger.info(t);
377
+ },
378
+ async load(t) {
379
+ let r = k(t);
380
+ if (!r) return;
381
+ let { file: i, kind: a, params: s } = r;
382
+ if (!e(i)) return;
383
+ this.addWatchFile(i);
384
+ let l = new H();
385
+ if (a === "image") {
386
+ let { meta: e, dir: t, stem: r } = await m(i, { image: [
387
+ c.widths,
388
+ c.maxWidth,
389
+ c.quality
390
+ ] }, T, (e, t) => F(n(i), e, t, c));
391
+ return l.module(l.image(e, t, r));
392
+ }
393
+ let u = Number(s.get("poster")), p = s.has("poster") && Number.isFinite(u) ? u : c.video.posterTime, { meta: h, dir: g, stem: _ } = await m(i, {
394
+ image: [
395
+ c.widths,
396
+ c.maxWidth,
397
+ c.quality
398
+ ],
399
+ video: c.video,
400
+ posterTime: p
401
+ }, E, async (e, t) => {
402
+ if (!await B(c)) throw Error(`ulnMedia: ${o(i)} isn't encoded in ${o(d)}/ yet, and ffmpeg isn't installed here (Workers Builds has none). Run the dev server or a build once where ffmpeg is installed, then commit ${o(d)}/.`);
403
+ return f(`ulnMedia: encoding ${o(i)} into ${o(d)}/ (once; commit it)`), V(i, e, t, p, c);
404
+ });
405
+ return l.module(l.video(h, g, _));
406
+ }
407
+ };
12
408
  }
13
409
  // sdk/vite.ts
14
- function c(t) {
410
+ function G(e) {
15
411
  try {
16
- let n = JSON.parse(e(t, "utf8"));
17
- return typeof n == "object" && n ? n : null;
412
+ let t = JSON.parse(n(e, "utf8"));
413
+ return typeof t == "object" && t ? t : null;
18
414
  } catch {
19
415
  return null;
20
416
  }
21
417
  }
22
- function l(e, r) {
23
- let i = r;
418
+ function K(e, t) {
419
+ let n = t;
24
420
  for (;;) {
25
- let r = c(n(i, "node_modules", e, "package.json")), a = r ? Reflect.get(r, "version") : void 0;
26
- if (s(a)) return a;
27
- let o = t(i);
28
- if (o === i) return null;
29
- i = o;
421
+ let t = G(l(n, "node_modules", e, "package.json")), r = t ? Reflect.get(t, "version") : void 0;
422
+ if (v(r)) return r;
423
+ let i = s(n);
424
+ if (i === n) return null;
425
+ n = i;
30
426
  }
31
427
  }
32
- function u(e, t = /* @__PURE__ */ new Date()) {
33
- let r = c(n(e, "package.json"));
34
- if (!r) throw Error(`ulnPackages: no package.json in ${e}`);
35
- let i = {};
36
- for (let t of a) {
37
- let n = Reflect.get(r, t);
38
- if (typeof n == "object" && n) for (let [r, a] of Object.entries(n)) {
39
- if (!r.startsWith("@uln/") || typeof a != "string" || r in i) continue;
40
- let n = l(r, e);
41
- n && (i[r] = {
42
- version: n,
428
+ function q(e, t = /* @__PURE__ */ new Date()) {
429
+ let n = G(l(e, "package.json"));
430
+ if (!n) throw Error(`ulnPackages: no package.json in ${e}`);
431
+ let r = {};
432
+ for (let t of g) {
433
+ let i = Reflect.get(n, t);
434
+ if (typeof i == "object" && i) for (let [n, a] of Object.entries(i)) {
435
+ if (!n.startsWith("@uln/") || typeof a != "string" || n in r) continue;
436
+ let i = K(n, e);
437
+ i && (r[n] = {
438
+ version: i,
43
439
  range: a,
44
440
  type: t
45
441
  });
46
442
  }
47
443
  }
48
- let o = Reflect.get(r, "packageManager");
444
+ let i = Reflect.get(n, "packageManager");
49
445
  return {
50
446
  schema: 1,
51
447
  builtAt: t.toISOString(),
52
- ...typeof o == "string" ? { packageManager: o } : {},
53
- packages: Object.fromEntries(Object.entries(i).sort(([e], [t]) => e.localeCompare(t)))
448
+ ...typeof i == "string" ? { packageManager: i } : {},
449
+ packages: Object.fromEntries(Object.entries(r).sort(([e], [t]) => e.localeCompare(t)))
54
450
  };
55
451
  }
56
- var d = "virtual:uln-packages", f = `\0${d}`;
57
- function p(e = {}) {
452
+ var J = "virtual:uln-packages", Y = `\0${J}`;
453
+ function X(e = {}) {
58
454
  let t = process.cwd();
59
455
  return {
60
456
  name: "uln-packages",
61
457
  resolveId(e) {
62
- return e === "virtual:uln-packages" ? f : void 0;
458
+ return e === "virtual:uln-packages" ? Y : void 0;
63
459
  },
64
460
  load(e) {
65
- return e === f ? `export const report = ${JSON.stringify(u(t))};` : void 0;
461
+ return e === Y ? `export const report = ${JSON.stringify(q(t))};` : void 0;
66
462
  },
67
463
  configResolved(n) {
68
- t = r(n.root, e.root ?? ".");
464
+ t = u(n.root, e.root ?? ".");
69
465
  },
70
466
  configureServer(e) {
71
- e.middlewares.use(i, (e, n) => {
72
- n.setHeader("Content-Type", "application/json"), n.end(JSON.stringify(u(t), null, 2));
467
+ e.middlewares.use(h, (e, n) => {
468
+ n.setHeader("Content-Type", "application/json"), n.end(JSON.stringify(q(t), null, 2));
73
469
  });
74
470
  },
75
471
  generateBundle() {
76
472
  let e = Reflect.get(this, "environment");
77
473
  (e ? Reflect.get(Reflect.get(e, "config") ?? {}, "consumer") : void 0) !== "server" && this.emitFile({
78
474
  type: "asset",
79
- fileName: i.slice(1),
80
- source: `${JSON.stringify(u(t), null, 2)}\n`
475
+ fileName: h.slice(1),
476
+ source: `${JSON.stringify(q(t), null, 2)}\n`
81
477
  });
82
478
  }
83
479
  };
84
480
  }
85
- export { i as PACKAGE_REPORT_PATH, d as VIRTUAL_MODULE, u as packageReport, p as ulnPackages };
481
+ export { h as PACKAGE_REPORT_PATH, J as VIRTUAL_MODULE, q as packageReport, W as ulnMedia, X as ulnPackages };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@uln/manage",
3
- "version": "0.3.1",
4
- "description": "Typed public catalog client and Manage links for ULN sites.",
3
+ "version": "0.5.0",
4
+ "description": "Typed public catalog client, Manage links, and Vite plugins for ULN sites.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "license": "UNLICENSED",
@@ -26,6 +26,9 @@
26
26
  "./vite": {
27
27
  "types": "./dist/types/sdk/vite.d.ts",
28
28
  "import": "./dist/vite.js"
29
+ },
30
+ "./media": {
31
+ "types": "./dist/types/sdk/media-env.d.ts"
29
32
  }
30
33
  },
31
34
  "publishConfig": {
@@ -35,15 +38,18 @@
35
38
  "prepack": "pnpm --dir .. build:sdk"
36
39
  },
37
40
  "dependencies": {
38
- "@uln/hls": "^0.3.5",
39
41
  "zod": "^4.6.7"
40
42
  },
41
43
  "peerDependencies": {
42
- "vite": ">=6"
44
+ "vite": ">=6",
45
+ "sharp": ">=0.34"
43
46
  },
44
47
  "peerDependenciesMeta": {
45
48
  "vite": {
46
49
  "optional": true
50
+ },
51
+ "sharp": {
52
+ "optional": true
47
53
  }
48
54
  }
49
55
  }