dsh-coding-subscription-oauth 0.6.4 → 0.6.5

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 (144) hide show
  1. package/CHANGELOG.md +280 -255
  2. package/CONTRIBUTING.md +138 -129
  3. package/INSTALL.md +256 -255
  4. package/LICENSE +19 -19
  5. package/NOTICE +11 -11
  6. package/README.de.md +303 -303
  7. package/README.es.md +304 -304
  8. package/README.fr.md +304 -304
  9. package/README.ja.md +304 -304
  10. package/README.ko.md +304 -304
  11. package/README.md +320 -320
  12. package/README.pt-BR.md +304 -304
  13. package/README.ru.md +304 -304
  14. package/README.zh-CN.md +318 -318
  15. package/compatibility/dsh-bom.json +30 -30
  16. package/cordis.patch.yml +13 -13
  17. package/docs/00-project-rules.md +212 -212
  18. package/docs/02-architecture.md +141 -137
  19. package/docs/02-architecture.zh-CN.md +141 -137
  20. package/lib/bin.js.map +1 -1
  21. package/lib/client.js +1 -1
  22. package/lib/client.js.map +1 -1
  23. package/lib/gateway-protocol.d.ts +3 -46
  24. package/lib/gateway-protocol.d.ts.map +1 -1
  25. package/lib/gateway-routes.d.ts.map +1 -1
  26. package/lib/grok-errors.d.ts +2 -12
  27. package/lib/grok-errors.d.ts.map +1 -1
  28. package/lib/grok-imagine/client.d.ts +73 -0
  29. package/lib/grok-imagine/client.d.ts.map +1 -0
  30. package/lib/grok-imagine/index.d.ts +8 -0
  31. package/lib/grok-imagine/index.d.ts.map +1 -0
  32. package/lib/grok-imagine/net.d.ts +10 -0
  33. package/lib/grok-imagine/net.d.ts.map +1 -0
  34. package/lib/grok-imagine/parse.d.ts +20 -0
  35. package/lib/grok-imagine/parse.d.ts.map +1 -0
  36. package/lib/grok-imagine/types.d.ts +191 -0
  37. package/lib/grok-imagine/types.d.ts.map +1 -0
  38. package/lib/grok-imagine.d.ts +3 -263
  39. package/lib/grok-imagine.d.ts.map +1 -1
  40. package/lib/http-json.d.ts +2 -9
  41. package/lib/http-json.d.ts.map +1 -1
  42. package/lib/index.js +57 -37
  43. package/lib/index.js.map +4 -4
  44. package/lib/invariant.js.map +1 -1
  45. package/lib/kimi-errors.d.ts +2 -12
  46. package/lib/kimi-errors.d.ts.map +1 -1
  47. package/lib/runtime/gateway-protocol.d.ts +47 -0
  48. package/lib/runtime/gateway-protocol.d.ts.map +1 -0
  49. package/lib/runtime/grok-errors.d.ts +13 -0
  50. package/lib/runtime/grok-errors.d.ts.map +1 -0
  51. package/lib/runtime/http-json.d.ts +10 -0
  52. package/lib/runtime/http-json.d.ts.map +1 -0
  53. package/lib/runtime/kimi-errors.d.ts +13 -0
  54. package/lib/runtime/kimi-errors.d.ts.map +1 -0
  55. package/media/en/settings_accounts.png +0 -0
  56. package/media/en/settings_capabilities.png +0 -0
  57. package/media/en/settings_gateway.png +0 -0
  58. package/media/settings_accounts.png +0 -0
  59. package/media/settings_capabilities.png +0 -0
  60. package/media/settings_gateway.png +0 -0
  61. package/media/settings_overview.png +0 -0
  62. package/media/zh-CN/settings_accounts.png +0 -0
  63. package/media/zh-CN/settings_capabilities.png +0 -0
  64. package/media/zh-CN/settings_gateway.png +0 -0
  65. package/package.json +225 -220
  66. package/patches/dsh-agy@0.1.2.patch +25 -25
  67. package/scripts/release.mjs +187 -186
  68. package/scripts/smoke-deployed-routes.mjs +146 -146
  69. package/scripts/verify-deployed-catalog.mjs +87 -87
  70. package/src/adapter.ts +0 -348
  71. package/src/alias-adapter.ts +0 -147
  72. package/src/auth-routes.ts +0 -921
  73. package/src/auth.ts +0 -67
  74. package/src/bin.ts +0 -350
  75. package/src/capability-routes.ts +0 -279
  76. package/src/capability-runtime.ts +0 -314
  77. package/src/capability-settings.ts +0 -671
  78. package/src/capability-tools.ts +0 -685
  79. package/src/catalog.ts +0 -271
  80. package/src/client/GrokBuildSettings.tsx +0 -771
  81. package/src/client/api.ts +0 -88
  82. package/src/client/components/AboutTab.tsx +0 -30
  83. package/src/client/components/AccountsTab.tsx +0 -241
  84. package/src/client/components/Badge.tsx +0 -33
  85. package/src/client/components/CapabilitiesTab.tsx +0 -265
  86. package/src/client/components/CliPullPreview.tsx +0 -116
  87. package/src/client/components/CopyButton.tsx +0 -57
  88. package/src/client/components/GatewayTab.tsx +0 -469
  89. package/src/client/components/NoticeBanner.tsx +0 -46
  90. package/src/client/components/ProgressBar.tsx +0 -53
  91. package/src/client/components/ProviderCard.tsx +0 -606
  92. package/src/client/components/SettingsTabs.tsx +0 -75
  93. package/src/client/components/ToggleSwitch.tsx +0 -71
  94. package/src/client/constants.ts +0 -230
  95. package/src/client/display.ts +0 -61
  96. package/src/client/dshClientAdapter.ts +0 -127
  97. package/src/client/gatewaySnippets.ts +0 -37
  98. package/src/client/index.tsx +0 -156
  99. package/src/client/locales.ts +0 -540
  100. package/src/client/microStyles.ts +0 -52
  101. package/src/client/parsers.ts +0 -398
  102. package/src/client/styles.ts +0 -325
  103. package/src/client/types.ts +0 -199
  104. package/src/codex-http.ts +0 -447
  105. package/src/codex-images.ts +0 -503
  106. package/src/codex-model-capabilities.ts +0 -320
  107. package/src/codex-search.ts +0 -245
  108. package/src/codex-usage.ts +0 -263
  109. package/src/compatibility.ts +0 -55
  110. package/src/dsh-host-adapter.ts +0 -173
  111. package/src/gateway-anthropic-messages.ts +0 -84
  112. package/src/gateway-auth.ts +0 -102
  113. package/src/gateway-backend.ts +0 -274
  114. package/src/gateway-body.ts +0 -49
  115. package/src/gateway-config.ts +0 -76
  116. package/src/gateway-http.ts +0 -104
  117. package/src/gateway-openai-chat.ts +0 -124
  118. package/src/gateway-openai-responses.ts +0 -53
  119. package/src/gateway-parse.ts +0 -224
  120. package/src/gateway-protocol.ts +0 -52
  121. package/src/gateway-routes.ts +0 -158
  122. package/src/gateway.ts +0 -258
  123. package/src/grok-errors.ts +0 -24
  124. package/src/grok-imagine.ts +0 -1627
  125. package/src/grok-import.ts +0 -151
  126. package/src/http-json.ts +0 -82
  127. package/src/ids.ts +0 -59
  128. package/src/imagine-routes.ts +0 -463
  129. package/src/index.ts +0 -735
  130. package/src/invariant.ts +0 -17
  131. package/src/kimi-errors.ts +0 -26
  132. package/src/media-store.ts +0 -927
  133. package/src/oauth-import-routes.ts +0 -324
  134. package/src/oauth-providers.ts +0 -152
  135. package/src/oauth-session.ts +0 -183
  136. package/src/oauth-sources.ts +0 -1104
  137. package/src/oauth.ts +0 -620
  138. package/src/provider.ts +0 -128
  139. package/src/proxy.ts +0 -11
  140. package/src/redact.ts +0 -72
  141. package/src/session.ts +0 -218
  142. package/src/store.ts +0 -217
  143. package/src/web-origin.ts +0 -296
  144. package/src/web-routes.ts +0 -38
@@ -1,463 +0,0 @@
1
- /**
2
- * Same-origin GET routes for generated Imagine images and video artifacts.
3
- * The Host webServer only accepts exact paths, so this registrar keeps a
4
- * bounded table of opaque ids and registers one exact disposer per remembered
5
- * image ref or media artifact.
6
- * @module dsh-coding-subscription-oauth/imagine-routes
7
- */
8
-
9
- import type { IncomingMessage, ServerResponse } from "node:http";
10
- import type { ImageAttachmentRef } from "@deepseek-ai/dsh-attachment";
11
- import {
12
- DEFAULT_IMAGE_DOWNLOAD_MAX_BYTES,
13
- type ImagineImageAttachmentRef,
14
- type ImagineImageMediaType,
15
- imagineImageDownloadHeaders,
16
- imagineImagePath,
17
- isSafeImagineAttachmentId,
18
- parseImagineImagePath,
19
- } from "./grok-imagine.ts";
20
- import {
21
- createTrustedImagineAuthz,
22
- imagineMediaPath,
23
- isSafeMediaArtifactId,
24
- MEDIA_STORE_MAX_BYTES,
25
- type MediaArtifactMeta,
26
- type MediaDownloadView,
27
- MediaStoreError,
28
- type MediaStoreVideoType,
29
- mediaDownloadHeaders,
30
- parseImagineMediaPath,
31
- type TrustedImagineAuthz,
32
- } from "./media-store.ts";
33
- import { LOOPBACK_OWNER_REQUEST_POLICY, type OwnerRequestPolicy } from "./web-origin.ts";
34
-
35
- /** Hard ceiling for live exact download routes. Callers cannot raise this. */
36
- export const IMAGINE_ROUTE_MAX_ENTRIES = 64;
37
-
38
- /** Hard ceiling for remembered image routes. Callers cannot raise this. */
39
- export const IMAGINE_IMAGE_ROUTE_TTL_MS = 60 * 60 * 1000;
40
-
41
- const IMAGE_MEDIA_TYPES = new Set<string>(["image/png", "image/jpeg", "image/webp", "image/gif"]);
42
- const VIDEO_MEDIA_TYPES = new Set<string>(["video/mp4", "video/webm"]);
43
-
44
- /** Structural `ctx.webServer` + optional `ctx.effect` surface used by the registrar. */
45
- export interface ImagineRouteContext {
46
- readonly webServer: {
47
- register(route: {
48
- kind: "exact";
49
- path: string;
50
- handler: (req: IncomingMessage, res: ServerResponse) => void | Promise<void>;
51
- }): () => void;
52
- };
53
- effect?(setup: () => () => void | Promise<void>, label?: string): unknown;
54
- }
55
-
56
- /** Attachment seam used at GET time. Only metadata is retained in the registry. */
57
- export interface ImagineRouteAttachmentStore {
58
- readonly imageLimits?: { readonly maxImageBytes?: number };
59
- readImage(
60
- ref: ImagineImageAttachmentRef,
61
- signal?: AbortSignal,
62
- ): Promise<{ ref: ImagineImageAttachmentRef; data: Uint8Array }>;
63
- }
64
-
65
- /** Structural media download seam. Production adapts `MediaStore.openDownload`. */
66
- export interface ImagineMediaDownloadStore {
67
- readForDownload(artifactId: string, authz: TrustedImagineAuthz): Promise<MediaDownloadView>;
68
- }
69
-
70
- export interface ImagineRouteOptions {
71
- readonly attachments: ImagineRouteAttachmentStore;
72
- readonly media: ImagineMediaDownloadStore;
73
- readonly now?: () => number;
74
- /** Capped at {@link IMAGINE_ROUTE_MAX_ENTRIES}. */
75
- readonly maxEntries?: number;
76
- /** Capped at {@link IMAGINE_IMAGE_ROUTE_TTL_MS}. */
77
- readonly imageTtlMs?: number;
78
- readonly ownerRequestPolicy?: OwnerRequestPolicy;
79
- }
80
-
81
- export interface ImagineRouteRegistry {
82
- rememberImages(refs: readonly ImageAttachmentRef[] | readonly ImagineImageAttachmentRef[]): void;
83
- rememberArtifact(meta: MediaArtifactMeta): void;
84
- revokeImages(): void;
85
- revokeArtifacts(): void;
86
- dispose(): void;
87
- }
88
-
89
- interface ImageRouteEntry {
90
- readonly kind: "image";
91
- readonly id: string;
92
- readonly path: string;
93
- readonly routeToken: symbol;
94
- ref: ImagineImageAttachmentRef;
95
- expiresAt: number;
96
- readonly disposeRoute: () => void;
97
- }
98
-
99
- interface MediaRouteEntry {
100
- readonly kind: "media";
101
- readonly id: string;
102
- readonly path: string;
103
- readonly routeToken: symbol;
104
- meta: MediaArtifactMeta;
105
- expiresAt: number;
106
- readonly disposeRoute: () => void;
107
- }
108
-
109
- type RouteEntry = ImageRouteEntry | MediaRouteEntry;
110
-
111
- type RouteHandler = (req: IncomingMessage, res: ServerResponse) => void | Promise<void>;
112
-
113
- /** Register the bounded exact-path Imagine download registry. */
114
- export function registerImagineRoutes(ctx: ImagineRouteContext, options: ImagineRouteOptions): ImagineRouteRegistry {
115
- const now = options.now ?? Date.now;
116
- const maxEntries = clampPositive(options.maxEntries, IMAGINE_ROUTE_MAX_ENTRIES);
117
- const imageTtlMs = clampPositive(options.imageTtlMs, IMAGINE_IMAGE_ROUTE_TTL_MS);
118
- const ownerRequestPolicy = options.ownerRequestPolicy ?? LOOPBACK_OWNER_REQUEST_POLICY;
119
- const entries = new Map<string, RouteEntry>();
120
- let disposed = false;
121
-
122
- const wrapDisposer = (release: () => void): (() => void) => {
123
- let released = false;
124
- return () => {
125
- if (released) return;
126
- released = true;
127
- try {
128
- release();
129
- } catch {
130
- // One route disposer must not strand the rest of the table.
131
- }
132
- };
133
- };
134
-
135
- const evict = (key: string): void => {
136
- const entry = entries.get(key);
137
- if (entry === undefined) return;
138
- entries.delete(key);
139
- entry.disposeRoute();
140
- };
141
-
142
- const evictExpired = (at: number): void => {
143
- for (const [key, entry] of [...entries]) {
144
- if (entry.expiresAt <= at) evict(key);
145
- }
146
- };
147
-
148
- const evictOldest = (): void => {
149
- const oldest = entries.keys().next().value;
150
- if (oldest !== undefined) evict(oldest);
151
- };
152
-
153
- const lookupKey = (kind: RouteEntry["kind"], id: string): string => `${kind}:${id}`;
154
-
155
- const registerExact = (path: string, handler: RouteHandler): (() => void) =>
156
- wrapDisposer(
157
- ctx.webServer.register({
158
- kind: "exact",
159
- path,
160
- handler,
161
- }),
162
- );
163
-
164
- const isCurrent = (kind: RouteEntry["kind"], id: string, routeToken: symbol): boolean => {
165
- if (disposed) return false;
166
- const entry = entries.get(lookupKey(kind, id));
167
- return entry !== undefined && entry.kind === kind && entry.routeToken === routeToken && entry.expiresAt > now();
168
- };
169
-
170
- const handleGet = async (
171
- kind: RouteEntry["kind"],
172
- id: string,
173
- routeToken: symbol,
174
- req: IncomingMessage,
175
- res: ServerResponse,
176
- ): Promise<void> => {
177
- if ((req.method ?? "") !== "GET") {
178
- json(res, 405, { error: "method not allowed" });
179
- return;
180
- }
181
- if (!ownerRequestPolicy.authorize(req).authorized) {
182
- json(res, 403, { error: "forbidden" });
183
- return;
184
- }
185
- if (!isCurrent(kind, id, routeToken)) {
186
- const key = lookupKey(kind, id);
187
- const current = entries.get(key);
188
- if (current?.routeToken === routeToken && current.expiresAt <= now()) evict(key);
189
- json(res, 404, { error: "not found" });
190
- return;
191
- }
192
- const key = lookupKey(kind, id);
193
- const entry = entries.get(key);
194
- if (entry === undefined || entry.kind !== kind) {
195
- json(res, 404, { error: "not found" });
196
- return;
197
- }
198
- try {
199
- if (entry.kind === "image") {
200
- await serveImage(options.attachments, entry, req, res, () => isCurrent(kind, id, routeToken));
201
- } else {
202
- await serveMedia(options.media, entry, res, () => isCurrent(kind, id, routeToken));
203
- }
204
- } catch (error: unknown) {
205
- if (res.headersSent) return;
206
- if (!isCurrent(kind, id, routeToken)) {
207
- json(res, 404, { error: "not found" });
208
- return;
209
- }
210
- json(res, statusFor(error), { error: publicErrorMessage(error) });
211
- }
212
- };
213
-
214
- const rememberImage = (input: ImageAttachmentRef | ImagineImageAttachmentRef): void => {
215
- if (disposed) return;
216
- const at = now();
217
- evictExpired(at);
218
- const ref = cloneImageRef(input);
219
- if (ref === undefined) return;
220
- if (ref.bytes > maxImageBytes(options.attachments)) return;
221
- let path: string;
222
- try {
223
- path = imagineImagePath(ref.attachmentId);
224
- } catch {
225
- return;
226
- }
227
- if (parseImagineImagePath(path) !== ref.attachmentId) return;
228
- const key = lookupKey("image", ref.attachmentId);
229
- const existing = entries.get(key);
230
- if (existing?.kind === "image") {
231
- entries.delete(key);
232
- existing.ref = ref;
233
- existing.expiresAt = at + imageTtlMs;
234
- entries.set(key, existing);
235
- return;
236
- }
237
- while (entries.size >= maxEntries) evictOldest();
238
- const routeToken = Symbol(ref.attachmentId);
239
- const release = registerExact(path, (req, res) => handleGet("image", ref.attachmentId, routeToken, req, res));
240
- entries.set(key, {
241
- kind: "image",
242
- id: ref.attachmentId,
243
- path,
244
- routeToken,
245
- ref,
246
- expiresAt: at + imageTtlMs,
247
- disposeRoute: release,
248
- });
249
- };
250
-
251
- const rememberArtifact = (input: MediaArtifactMeta): void => {
252
- if (disposed) return;
253
- const at = now();
254
- evictExpired(at);
255
- const meta = cloneArtifactMeta(input);
256
- if (meta === undefined || meta.expiresAt <= at) return;
257
- let path: string;
258
- try {
259
- path = imagineMediaPath(meta.artifactId);
260
- } catch {
261
- return;
262
- }
263
- if (parseImagineMediaPath(path) !== meta.artifactId) return;
264
- const key = lookupKey("media", meta.artifactId);
265
- const existing = entries.get(key);
266
- if (existing?.kind === "media") {
267
- entries.delete(key);
268
- existing.meta = meta;
269
- existing.expiresAt = meta.expiresAt;
270
- entries.set(key, existing);
271
- return;
272
- }
273
- while (entries.size >= maxEntries) evictOldest();
274
- const routeToken = Symbol(meta.artifactId);
275
- const release = registerExact(path, (req, res) => handleGet("media", meta.artifactId, routeToken, req, res));
276
- entries.set(key, {
277
- kind: "media",
278
- id: meta.artifactId,
279
- path,
280
- routeToken,
281
- meta,
282
- expiresAt: meta.expiresAt,
283
- disposeRoute: release,
284
- });
285
- };
286
-
287
- const dispose = (): void => {
288
- if (disposed) return;
289
- disposed = true;
290
- for (const key of [...entries.keys()]) evict(key);
291
- };
292
-
293
- if (typeof ctx.effect === "function") {
294
- ctx.effect(() => dispose, "dsh-coding-subscription-oauth: imagine download routes");
295
- }
296
-
297
- return {
298
- rememberImages(refs) {
299
- for (const ref of refs) rememberImage(ref);
300
- },
301
- rememberArtifact,
302
- revokeImages() {
303
- for (const [key, entry] of [...entries]) {
304
- if (entry.kind === "image") evict(key);
305
- }
306
- },
307
- revokeArtifacts() {
308
- for (const [key, entry] of [...entries]) {
309
- if (entry.kind === "media") evict(key);
310
- }
311
- },
312
- dispose,
313
- };
314
- }
315
-
316
- async function serveImage(
317
- attachments: ImagineRouteAttachmentStore,
318
- entry: ImageRouteEntry,
319
- req: IncomingMessage,
320
- res: ServerResponse,
321
- alive: () => boolean,
322
- ): Promise<void> {
323
- const limit = maxImageBytes(attachments);
324
- if (entry.ref.bytes > limit) {
325
- json(res, 404, { error: "not found" });
326
- return;
327
- }
328
- const stored = await attachments.readImage(cloneImageRef(entry.ref) ?? entry.ref, requestSignal(req));
329
- if (res.headersSent) return;
330
- if (!alive()) {
331
- json(res, 404, { error: "not found" });
332
- return;
333
- }
334
- if (!sameImageIdentity(entry.ref, stored.ref) || stored.data.byteLength > limit) {
335
- json(res, 404, { error: "not found" });
336
- return;
337
- }
338
- const headers = imagineImageDownloadHeaders({
339
- ...stored.ref,
340
- bytes: stored.data.byteLength,
341
- });
342
- res.writeHead(200, {
343
- "Content-Type": headers["Content-Type"],
344
- "Content-Length": String(stored.data.byteLength),
345
- "Cache-Control": headers["Cache-Control"],
346
- "X-Content-Type-Options": headers["X-Content-Type-Options"],
347
- });
348
- res.end(Buffer.from(stored.data));
349
- }
350
-
351
- async function serveMedia(
352
- media: ImagineMediaDownloadStore,
353
- entry: MediaRouteEntry,
354
- res: ServerResponse,
355
- alive: () => boolean,
356
- ): Promise<void> {
357
- const authz = createTrustedImagineAuthz({ authorized: true });
358
- const view = await media.readForDownload(entry.id, authz);
359
- if (res.headersSent) return;
360
- if (!alive()) {
361
- json(res, 404, { error: "not found" });
362
- return;
363
- }
364
- if (
365
- view.meta.artifactId !== entry.id ||
366
- view.meta.mediaType !== entry.meta.mediaType ||
367
- view.meta.bytes !== view.body.byteLength ||
368
- view.body.byteLength > MEDIA_STORE_MAX_BYTES
369
- ) {
370
- json(res, 404, { error: "not found" });
371
- return;
372
- }
373
- const headers = mediaDownloadHeaders({ ...entry.meta, bytes: view.body.byteLength });
374
- res.writeHead(200, {
375
- "Content-Type": headers["Content-Type"],
376
- "Content-Length": headers["Content-Length"],
377
- "Content-Disposition": headers["Content-Disposition"],
378
- "Cache-Control": headers["Cache-Control"],
379
- "X-Content-Type-Options": headers["X-Content-Type-Options"],
380
- });
381
- res.end(Buffer.from(view.body));
382
- }
383
-
384
- function requestSignal(req: IncomingMessage): AbortSignal | undefined {
385
- const candidate = req as IncomingMessage & { signal?: unknown };
386
- return candidate.signal instanceof AbortSignal ? candidate.signal : undefined;
387
- }
388
-
389
- function maxImageBytes(attachments: ImagineRouteAttachmentStore): number {
390
- const configured = attachments.imageLimits?.maxImageBytes;
391
- if (typeof configured !== "number" || !Number.isFinite(configured) || configured <= 0) {
392
- return DEFAULT_IMAGE_DOWNLOAD_MAX_BYTES;
393
- }
394
- return Math.min(Math.floor(configured), DEFAULT_IMAGE_DOWNLOAD_MAX_BYTES);
395
- }
396
-
397
- function cloneImageRef(input: ImageAttachmentRef | ImagineImageAttachmentRef): ImagineImageAttachmentRef | undefined {
398
- if (typeof input.attachmentId !== "string" || !isSafeImagineAttachmentId(input.attachmentId)) return undefined;
399
- if (!IMAGE_MEDIA_TYPES.has(input.mediaType)) return undefined;
400
- if (!Number.isFinite(input.bytes) || input.bytes < 0) return undefined;
401
- if (!Number.isFinite(input.width) || !Number.isFinite(input.height)) return undefined;
402
- const cloned: ImagineImageAttachmentRef = {
403
- attachmentId: input.attachmentId,
404
- mediaType: input.mediaType as ImagineImageMediaType,
405
- bytes: Math.trunc(input.bytes),
406
- width: Math.trunc(input.width),
407
- height: Math.trunc(input.height),
408
- };
409
- if (typeof input.name === "string") cloned.name = input.name;
410
- return cloned;
411
- }
412
-
413
- function cloneArtifactMeta(input: MediaArtifactMeta): MediaArtifactMeta | undefined {
414
- if (typeof input.artifactId !== "string" || !isSafeMediaArtifactId(input.artifactId)) return undefined;
415
- if (!VIDEO_MEDIA_TYPES.has(input.mediaType)) return undefined;
416
- if (!Number.isFinite(input.bytes) || input.bytes <= 0) return undefined;
417
- if (!Number.isFinite(input.createdAt) || input.createdAt <= 0) return undefined;
418
- if (!Number.isFinite(input.expiresAt) || input.expiresAt <= input.createdAt) return undefined;
419
- const cloned: MediaArtifactMeta = {
420
- artifactId: input.artifactId,
421
- mediaType: input.mediaType as MediaStoreVideoType,
422
- bytes: Math.trunc(input.bytes),
423
- createdAt: input.createdAt,
424
- expiresAt: input.expiresAt,
425
- };
426
- if (typeof input.name === "string") cloned.name = input.name;
427
- return cloned;
428
- }
429
-
430
- function sameImageIdentity(expected: ImagineImageAttachmentRef, actual: ImagineImageAttachmentRef): boolean {
431
- return actual.attachmentId === expected.attachmentId && IMAGE_MEDIA_TYPES.has(actual.mediaType);
432
- }
433
-
434
- function statusFor(error: unknown): number {
435
- if (error instanceof MediaStoreError) {
436
- if (error.code === "NOT_FOUND" || error.code === "EXPIRED" || error.code === "INVALID_ID") return 404;
437
- if (error.code === "FORBIDDEN") return 403;
438
- }
439
- return 500;
440
- }
441
-
442
- function publicErrorMessage(error: unknown): string {
443
- if (error instanceof MediaStoreError) {
444
- if (error.code === "NOT_FOUND" || error.code === "EXPIRED" || error.code === "INVALID_ID") return "not found";
445
- if (error.code === "FORBIDDEN") return "forbidden";
446
- }
447
- return "download failed";
448
- }
449
-
450
- function clampPositive(value: number | undefined, ceiling: number): number {
451
- if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return ceiling;
452
- return Math.min(Math.floor(value), ceiling);
453
- }
454
-
455
- function json(res: ServerResponse, status: number, value: unknown): void {
456
- if (res.headersSent) return;
457
- res.writeHead(status, {
458
- "content-type": "application/json; charset=utf-8",
459
- "cache-control": "no-store",
460
- "x-content-type-options": "nosniff",
461
- });
462
- res.end(JSON.stringify(value));
463
- }