-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex.ts
More file actions
563 lines (520 loc) · 16.3 KB
/
Copy pathindex.ts
File metadata and controls
563 lines (520 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
import {
httpActionGeneric,
internalMutationGeneric,
internalQueryGeneric,
queryGeneric,
} from "convex/server";
import type { HttpRouter } from "convex/server";
import { v } from "convex/values";
import type { ComponentApi } from "../component/_generated/component.js";
// MIME type mapping for common file types
const MIME_TYPES: Record<string, string> = {
".html": "text/html; charset=utf-8",
".js": "application/javascript; charset=utf-8",
".mjs": "application/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json; charset=utf-8",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".gif": "image/gif",
".svg": "image/svg+xml",
".ico": "image/x-icon",
".webp": "image/webp",
".woff": "font/woff",
".woff2": "font/woff2",
".ttf": "font/ttf",
".txt": "text/plain; charset=utf-8",
".map": "application/json",
".webmanifest": "application/manifest+json",
".xml": "application/xml",
};
/**
* Generate HTML page shown when no assets have been deployed yet.
*/
function getSetupHtml(): string {
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Convex Static Hosting</title>
<style>
* { box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
max-width: 640px;
margin: 0 auto;
padding: 40px 20px;
background: #fafafa;
color: #333;
line-height: 1.6;
}
h1 { color: #111; margin-bottom: 8px; }
.subtitle { color: #666; margin-bottom: 32px; }
code {
background: #e8e8e8;
padding: 2px 6px;
border-radius: 4px;
font-size: 14px;
}
pre {
background: #1a1a1a;
color: #f0f0f0;
padding: 16px;
border-radius: 8px;
overflow-x: auto;
font-size: 14px;
}
.step { margin-bottom: 24px; }
.step-num {
display: inline-block;
background: #333;
color: white;
width: 24px;
height: 24px;
border-radius: 50%;
text-align: center;
font-size: 14px;
line-height: 24px;
margin-right: 8px;
}
a { color: #0070f3; }
</style>
</head>
<body>
<h1>Almost there!</h1>
<p class="subtitle">Your Convex backend is running, but no static files have been deployed yet.</p>
<div class="step">
<span class="step-num">1</span>
<strong>Build your frontend</strong>
<pre>npm run build</pre>
</div>
<div class="step">
<span class="step-num">2</span>
<strong>Deploy your static files</strong>
<pre>npx @convex-dev/static-hosting deploy</pre>
</div>
<p>Or deploy everything in one command:</p>
<pre>npm run deploy</pre>
<p style="margin-top: 32px; color: #666; font-size: 14px;">
Learn more at <a href="https://github.com/get-convex/static-hosting">github.com/get-convex/static-hosting</a>
</p>
</body>
</html>`;
}
/**
* Get MIME type for a file path based on its extension.
*/
export function getMimeType(path: string): string {
const ext = path.substring(path.lastIndexOf(".")).toLowerCase();
return MIME_TYPES[ext] || "application/octet-stream";
}
/**
* Check if a path has a file extension.
*/
function hasFileExtension(path: string): boolean {
const lastSegment = path.split("/").pop() || "";
return lastSegment.includes(".") && !lastSegment.startsWith(".");
}
/**
* Check if asset is a hashed asset (for cache control).
* Vite produces: index-lj_vq_aF.js, style-B71cUw87.css
*/
function isHashedAsset(path: string): boolean {
return /[-.][\dA-Za-z_]{6,12}\.[a-z]+$/.test(path);
}
/**
* Register HTTP routes for serving static files.
* This creates a catch-all route that serves files from Convex storage
* with SPA fallback support.
*
* @param http - The HTTP router to register routes on
* @param component - The component API reference
* @param options - Configuration options
* @param options.pathPrefix - URL prefix for static files (default: "/")
* @param options.spaFallback - Enable SPA fallback to index.html (default: true)
*
* @example
* ```typescript
* // In your convex/http.ts
* import { httpRouter } from "convex/server";
* import { registerStaticRoutes } from "@convex-dev/static-hosting";
* import { components } from "./_generated/api";
*
* const http = httpRouter();
*
* // Serve static files at root
* registerStaticRoutes(http, components.selfHosting);
*
* // Or serve at a specific path prefix
* registerStaticRoutes(http, components.selfHosting, {
* pathPrefix: "/app",
* });
*
* export default http;
* ```
*/
/**
* Check if a content type is HTML.
*/
function isHtmlContentType(contentType: string): boolean {
return contentType.startsWith("text/html");
}
export function registerStaticRoutes(
http: HttpRouter,
component: ComponentApi,
{
pathPrefix = "/",
spaFallback = true,
cdnBaseUrl,
}: {
pathPrefix?: string;
spaFallback?: boolean;
/** Base URL for CDN blob redirects (e.g., `(req) => \`${new URL(req.url).origin}/fs/blobs\``).
* When set, assets with a blobId (non-HTML) will return a 302 redirect to `{cdnBaseUrl}/{blobId}`. */
cdnBaseUrl?: string | ((request: Request) => string);
} = {},
) {
// Normalize pathPrefix - ensure it starts with / and doesn't end with /
const normalizedPrefix =
pathPrefix === "/" ? "" : pathPrefix.replace(/\/$/, "");
const serveStaticFile = httpActionGeneric(async (ctx, request) => {
const url = new URL(request.url);
let path = url.pathname;
// Remove prefix if present
if (normalizedPrefix && path.startsWith(normalizedPrefix)) {
path = path.slice(normalizedPrefix.length) || "/";
}
// Normalize: serve index.html for root
if (path === "" || path === "/") {
path = "/index.html";
}
// Look up the asset
type AssetDoc = {
_id: string;
_creationTime: number;
path: string;
storageId?: string;
blobId?: string;
contentType: string;
deploymentId: string;
} | null;
let asset: AssetDoc = await ctx.runQuery(component.lib.getByPath, { path });
// Directory-index fallback: serve /foo/index.html when /foo or /foo/ is
// requested. Supports frameworks like Next.js `output: 'export'` that emit
// directory-based static trees (e.g. `out/about/index.html`).
if (!asset && !hasFileExtension(path)) {
const indexPath = path.endsWith("/")
? `${path}index.html`
: `${path}/index.html`;
asset = await ctx.runQuery(component.lib.getByPath, { path: indexPath });
}
// SPA fallback: if still not found and no file extension, serve index.html
if (!asset && spaFallback && !hasFileExtension(path)) {
asset = await ctx.runQuery(component.lib.getByPath, {
path: "/index.html",
});
}
// 404 if still not found
if (!asset) {
// If looking for index.html and it's not there, show setup instructions
if (path === "/index.html") {
return new Response(getSetupHtml(), {
status: 200,
headers: { "Content-Type": "text/html; charset=utf-8" },
});
}
return new Response("Not Found", {
status: 404,
headers: { "Content-Type": "text/plain" },
});
}
// CDN redirect: if asset has blobId, is not HTML, and cdnBaseUrl is configured
if (asset.blobId && cdnBaseUrl && !isHtmlContentType(asset.contentType)) {
const baseUrl =
typeof cdnBaseUrl === "function" ? cdnBaseUrl(request) : cdnBaseUrl;
const redirectUrl = `${baseUrl.replace(/\/$/, "")}/${asset.blobId}`;
// Cache control for redirect: hashed assets can cache the redirect itself
const cacheControl = isHashedAsset(path)
? "public, max-age=31536000, immutable"
: "public, max-age=0, must-revalidate";
return new Response(null, {
status: 302,
headers: {
Location: redirectUrl,
"Cache-Control": cacheControl,
},
});
}
// Serve from Convex storage
if (!asset.storageId) {
return new Response("Asset not available", {
status: 500,
headers: { "Content-Type": "text/plain" },
});
}
// Use storageId as ETag (unique per file content)
const etag = `"${asset.storageId}"`;
// Check for conditional request (If-None-Match)
const ifNoneMatch = request.headers.get("If-None-Match");
if (ifNoneMatch === etag) {
// Client has current version - return 304 Not Modified
return new Response(null, {
status: 304,
headers: {
ETag: etag,
"Cache-Control": isHashedAsset(path)
? "public, max-age=31536000, immutable"
: "public, max-age=0, must-revalidate",
},
});
}
// Get file from storage
const blob = await ctx.storage.get(asset.storageId);
if (!blob) {
return new Response("Storage error", {
status: 500,
headers: { "Content-Type": "text/plain" },
});
}
// Cache control: hashed assets can be cached forever
const cacheControl = isHashedAsset(path)
? "public, max-age=31536000, immutable"
: "public, max-age=0, must-revalidate";
return new Response(blob, {
status: 200,
headers: {
"Content-Type": asset.contentType,
"Cache-Control": cacheControl,
ETag: etag,
"X-Content-Type-Options": "nosniff",
},
});
});
// Use pathPrefix routing
http.route({
pathPrefix: pathPrefix === "/" ? "/" : `${normalizedPrefix}/`,
method: "GET",
handler: serveStaticFile,
});
// Also handle exact prefix without trailing slash
if (normalizedPrefix) {
http.route({
path: normalizedPrefix,
method: "GET",
handler: serveStaticFile,
});
}
}
/**
* Expose the upload API as INTERNAL functions for secure deployments.
* These functions can only be called via `npx convex run` or from other Convex functions.
*
* @param component - The component API reference
*
* @example
* ```typescript
* // In your convex/staticHosting.ts
* import { exposeUploadApi } from "@convex-dev/static-hosting";
* import { components } from "./_generated/api";
*
* export const { generateUploadUrl, generateUploadUrls, recordAsset, recordAssets, gcOldAssets, listAssets } =
* exposeUploadApi(components.selfHosting);
* ```
*
* Then deploy using:
* ```bash
* npm run deploy:static
* ```
*/
export function exposeUploadApi(component: ComponentApi) {
return {
/**
* Generate a signed URL for uploading a file.
* Files are stored in the app's storage (not the component's).
*/
generateUploadUrl: internalMutationGeneric({
args: {},
handler: async (ctx) => {
return await ctx.storage.generateUploadUrl();
},
}),
/**
* Record an uploaded asset in the database.
* Automatically cleans up old storage files when replacing.
* Pass storageId for Convex storage assets, or blobId for CDN assets.
*/
recordAsset: internalMutationGeneric({
args: {
path: v.string(),
storageId: v.optional(v.string()),
blobId: v.optional(v.string()),
contentType: v.string(),
deploymentId: v.string(),
},
handler: async (ctx, args) => {
const { oldStorageId, oldBlobId } = await ctx.runMutation(
component.lib.recordAsset,
{
path: args.path,
...(args.storageId ? { storageId: args.storageId } : {}),
...(args.blobId ? { blobId: args.blobId } : {}),
contentType: args.contentType,
deploymentId: args.deploymentId,
},
);
if (oldStorageId) {
try {
await ctx.storage.delete(oldStorageId);
} catch {
// Ignore - old file may have been in different storage
}
}
// Return oldBlobId so caller can clean up CDN blobs if needed
return oldBlobId ?? null;
},
}),
/**
* Garbage collect old assets and notify clients of the new deployment.
* Returns the count of deleted assets.
* Also triggers connected clients to reload via the deployment subscription.
*/
gcOldAssets: internalMutationGeneric({
args: {
currentDeploymentId: v.string(),
},
handler: async (ctx, args) => {
const { storageIds, blobIds } = await ctx.runMutation(
component.lib.gcOldAssets,
{
currentDeploymentId: args.currentDeploymentId,
},
);
for (const storageId of storageIds) {
try {
await ctx.storage.delete(storageId);
} catch {
// Ignore - old file may have been in different storage
}
}
// Update deployment info to trigger client reloads
await ctx.runMutation(component.lib.setCurrentDeployment, {
deploymentId: args.currentDeploymentId,
});
// Return both counts and blobIds for CDN cleanup
return { deleted: storageIds.length, blobIds };
},
}),
/**
* Generate multiple signed upload URLs in one call.
* Much faster than calling generateUploadUrl N times.
*/
generateUploadUrls: internalMutationGeneric({
args: { count: v.number() },
handler: async (ctx, { count }) => {
const urls: string[] = [];
for (let i = 0; i < count; i++) {
urls.push(await ctx.storage.generateUploadUrl());
}
return urls;
},
}),
/**
* Record multiple uploaded assets in one call.
*/
recordAssets: internalMutationGeneric({
args: {
assets: v.array(
v.object({
path: v.string(),
storageId: v.string(),
contentType: v.string(),
deploymentId: v.string(),
}),
),
},
handler: async (ctx, { assets }) => {
for (const asset of assets) {
await ctx.runMutation(component.lib.recordAsset, {
path: asset.path,
storageId: asset.storageId,
contentType: asset.contentType,
deploymentId: asset.deploymentId,
});
}
},
}),
/**
* List all static assets (for debugging).
*/
listAssets: internalQueryGeneric({
args: {
limit: v.optional(v.number()),
},
handler: async (ctx, args) => {
return await ctx.runQuery(component.lib.listAssets, {
limit: args.limit,
});
},
}),
};
}
/**
* Expose a query that clients can subscribe to for live reload on deploy.
* When a new deployment happens, subscribed clients will be notified.
*
* @param component - The component API reference
*
* @example
* ```typescript
* // In your convex/staticHosting.ts
* import { exposeUploadApi, exposeDeploymentQuery } from "@convex-dev/static-hosting";
* import { components } from "./_generated/api";
*
* export const { generateUploadUrl, generateUploadUrls, recordAsset, recordAssets, gcOldAssets, listAssets } =
* exposeUploadApi(components.selfHosting);
*
* export const { getCurrentDeployment } = exposeDeploymentQuery(components.selfHosting);
* ```
*/
export function exposeDeploymentQuery(component: ComponentApi) {
return {
/**
* Get the current deployment info.
* Subscribe to this query to detect when a new deployment happens.
*/
getCurrentDeployment: queryGeneric({
args: {},
handler: async (ctx) => {
return await ctx.runQuery(component.lib.getCurrentDeployment, {});
},
}),
};
}
/**
* Derive the Convex cloud URL from a .convex.site hostname.
* Useful for client-side code that needs to connect to the Convex backend
* when hosted on Convex static hosting.
*
* @example
* ```typescript
* // In your React app's main.tsx
* import { getConvexUrl } from "@convex-dev/static-hosting";
*
* const convexUrl = import.meta.env.VITE_CONVEX_URL ?? getConvexUrl();
* const convex = new ConvexReactClient(convexUrl);
* ```
*/
export function getConvexUrl(): string {
if (typeof window === "undefined") {
throw new Error("getConvexUrl() can only be called in a browser context");
}
// If hosted on Convex (.convex.site), derive API URL (.convex.cloud)
if (window.location.hostname.endsWith(".convex.site")) {
return `https://${window.location.hostname.replace(".convex.site", ".convex.cloud")}`;
}
throw new Error(
"Unable to derive Convex URL. Please set VITE_CONVEX_URL environment variable.",
);
}