widefleet-darwin-arm64 0.3.2 → 0.4.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.
Files changed (83) hide show
  1. package/README.md +26 -10
  2. package/package.json +3 -1
  3. package/release.json +1 -1
  4. package/starter/AGENTS.md +4 -14
  5. package/starter/README.md +13 -16
  6. package/starter/package.json +3 -2
  7. package/starter/pnpm-lock.yaml +33 -75
  8. package/starter/pnpm-workspace.yaml +1 -0
  9. package/starters/tanstack-start/.gitattributes +2 -0
  10. package/starters/tanstack-start/.gitignore +19 -0
  11. package/starters/tanstack-start/.oxfmtrc.json +33 -0
  12. package/starters/tanstack-start/.oxlintrc.json +69 -0
  13. package/starters/tanstack-start/AGENTS.md +24 -0
  14. package/starters/tanstack-start/LICENSE +21 -0
  15. package/starters/tanstack-start/README.md +66 -0
  16. package/starters/tanstack-start/package.json +47 -0
  17. package/starters/tanstack-start/pnpm-lock.yaml +3130 -0
  18. package/starters/tanstack-start/pnpm-workspace.yaml +6 -0
  19. package/starters/tanstack-start/src/client.tsx +20 -0
  20. package/starters/tanstack-start/src/env.d.ts +7 -0
  21. package/starters/tanstack-start/src/lib/capture-error.ts +47 -0
  22. package/starters/tanstack-start/src/lib/errors.ts +42 -0
  23. package/starters/tanstack-start/src/lib/notes.functions.ts +86 -0
  24. package/starters/tanstack-start/src/lib/report-error.ts +7 -0
  25. package/starters/tanstack-start/src/lib/server/browser-errors.ts +88 -0
  26. package/starters/tanstack-start/src/lib/server/capture-error.ts +35 -0
  27. package/starters/tanstack-start/src/lib/server/context.ts +7 -0
  28. package/starters/tanstack-start/src/lib/server/data.ts +48 -0
  29. package/starters/tanstack-start/src/lib/server/identity.ts +30 -0
  30. package/starters/tanstack-start/src/register.d.ts +13 -0
  31. package/starters/tanstack-start/src/router.tsx +12 -0
  32. package/starters/tanstack-start/src/routes/__root.tsx +28 -0
  33. package/starters/tanstack-start/src/routes/index.tsx +127 -0
  34. package/starters/tanstack-start/src/routes/photos.$id.ts +27 -0
  35. package/starters/tanstack-start/src/server.ts +67 -0
  36. package/starters/tanstack-start/src/start.ts +28 -0
  37. package/starters/tanstack-start/src/styles.css +122 -0
  38. package/starters/tanstack-start/tools/build.ts +26 -0
  39. package/starters/tanstack-start/tools/oxlint/anti-slop/LICENSE +21 -0
  40. package/starters/tanstack-start/tools/oxlint/anti-slop/UPSTREAM.md +7 -0
  41. package/starters/tanstack-start/tools/oxlint/anti-slop/effect/index.ts +21 -0
  42. package/starters/tanstack-start/tools/oxlint/anti-slop/effect/rules/no-manual-effect-error-tag.ts +52 -0
  43. package/starters/tanstack-start/tools/oxlint/anti-slop/effect/rules/no-manual-tag-comparison.ts +45 -0
  44. package/starters/tanstack-start/tools/oxlint/anti-slop/effect/rules/no-manual-tagged-construction.ts +37 -0
  45. package/starters/tanstack-start/tools/oxlint/anti-slop/effect/rules/no-service-constructor-imports.ts +52 -0
  46. package/starters/tanstack-start/tools/oxlint/anti-slop/effect/rules/prefer-effect-match.ts +54 -0
  47. package/starters/tanstack-start/tools/oxlint/anti-slop/effect/shared/tagged-values.ts +97 -0
  48. package/starters/tanstack-start/tools/oxlint/anti-slop/index.ts +47 -0
  49. package/starters/tanstack-start/tools/oxlint/anti-slop/rules/no-array-filter-map.ts +28 -0
  50. package/starters/tanstack-start/tools/oxlint/anti-slop/rules/no-chained-type-assertions.ts +77 -0
  51. package/starters/tanstack-start/tools/oxlint/anti-slop/rules/no-conditional-empty-object-spread.ts +49 -0
  52. package/starters/tanstack-start/tools/oxlint/anti-slop/rules/no-known-value-widening.ts +415 -0
  53. package/starters/tanstack-start/tools/oxlint/anti-slop/rules/no-module-mocking.ts +80 -0
  54. package/starters/tanstack-start/tools/oxlint/anti-slop/rules/no-object-parameters.ts +83 -0
  55. package/starters/tanstack-start/tools/oxlint/anti-slop/rules/no-reduce-accumulator-copy.ts +109 -0
  56. package/starters/tanstack-start/tools/oxlint/anti-slop/rules/no-reflect-apply.ts +28 -0
  57. package/starters/tanstack-start/tools/oxlint/anti-slop/rules/no-reflect-get.ts +28 -0
  58. package/starters/tanstack-start/tools/oxlint/anti-slop/rules/no-runtime-typeof.ts +77 -0
  59. package/starters/tanstack-start/tools/oxlint/anti-slop/rules/no-shape-in-symbol-names.ts +46 -0
  60. package/starters/tanstack-start/tools/oxlint/anti-slop/rules/no-unknown-parameters.ts +69 -0
  61. package/starters/tanstack-start/tools/oxlint/anti-slop/rules/no-unknown-returns.ts +82 -0
  62. package/starters/tanstack-start/tools/oxlint/anti-slop/rules/no-unknown-type-aliases.ts +54 -0
  63. package/starters/tanstack-start/tools/oxlint/anti-slop/rules/no-unsafe-dictionary-type.ts +154 -0
  64. package/starters/tanstack-start/tools/oxlint/anti-slop/rules/no-widen-then-assert.ts +366 -0
  65. package/starters/tanstack-start/tools/oxlint/anti-slop/rules/require-readable-spacing.ts +47 -0
  66. package/starters/tanstack-start/tools/oxlint/anti-slop/rules/require-safety-comment-for-type-assertion.ts +131 -0
  67. package/starters/tanstack-start/tools/oxlint/anti-slop/shared/array-method.ts +94 -0
  68. package/starters/tanstack-start/tools/oxlint/anti-slop/shared/dictionary-types.ts +515 -0
  69. package/starters/tanstack-start/tools/oxlint/anti-slop/shared/function-parameters.ts +49 -0
  70. package/starters/tanstack-start/tools/oxlint/anti-slop/shared/lexical-type-parameters.ts +61 -0
  71. package/starters/tanstack-start/tools/oxlint/anti-slop/shared/reflect-method.ts +24 -0
  72. package/starters/tanstack-start/tools/oxlint/anti-slop/shared/scope.ts +15 -0
  73. package/starters/tanstack-start/tools/oxlint/anti-slop/shared/type-alias-resolution.ts +250 -0
  74. package/starters/tanstack-start/tools/oxlint/anti-slop/vendor/eslint-stylistic/LICENSE +22 -0
  75. package/starters/tanstack-start/tools/oxlint/anti-slop/vendor/eslint-stylistic/UPSTREAM.md +28 -0
  76. package/starters/tanstack-start/tools/oxlint/anti-slop/vendor/eslint-stylistic/padding-line-ast.ts +51 -0
  77. package/starters/tanstack-start/tools/oxlint/anti-slop/vendor/eslint-stylistic/padding-line-between-statements.ts +906 -0
  78. package/starters/tanstack-start/tools/oxlint/anti-slop/vendor/eslint-stylistic/padding-line-options.d.ts +87 -0
  79. package/starters/tanstack-start/tools/types.ts +31 -0
  80. package/starters/tanstack-start/tsconfig.json +20 -0
  81. package/starters/tanstack-start/vite.config.ts +49 -0
  82. package/starters/tanstack-start/wrangler.jsonc +17 -0
  83. package/widefleet +0 -0
@@ -0,0 +1,6 @@
1
+ packages: []
2
+ strictPeerDependencies: true
3
+ strictDepBuilds: true
4
+ allowBuilds:
5
+ esbuild: true
6
+ workerd: true
@@ -0,0 +1,20 @@
1
+ import { StartClient } from "@tanstack/react-start/client";
2
+ import { StrictMode } from "react";
3
+ import { hydrateRoot } from "react-dom/client";
4
+ import { captureError } from "./lib/capture-error.ts";
5
+
6
+ window.addEventListener("error", (event) => captureError(event.error ?? event.message));
7
+
8
+ window.addEventListener("unhandledrejection", (event) => captureError(event.reason));
9
+
10
+ hydrateRoot(
11
+ document,
12
+ <StrictMode>
13
+ <StartClient />
14
+ </StrictMode>,
15
+ {
16
+ onCaughtError: captureError,
17
+ onUncaughtError: captureError,
18
+ onRecoverableError: captureError,
19
+ },
20
+ );
@@ -0,0 +1,7 @@
1
+ declare const __WIDEFLEET_BUILD_ID__: string;
2
+
3
+ declare namespace Cloudflare {
4
+ interface Env {
5
+ WIDEFLEET_DEPLOYMENT_ID?: string;
6
+ }
7
+ }
@@ -0,0 +1,47 @@
1
+ import { describeError } from "./errors.ts";
2
+
3
+ const recent = new Map<string, number>();
4
+
5
+ let windowStart = 0;
6
+
7
+ let sent = 0;
8
+
9
+ /** Report a handled browser failure. Automatic hooks use this same bounded transport. */
10
+ export const captureError = (cause: unknown) => {
11
+ if (import.meta.env.SSR || import.meta.env.DEV) return;
12
+
13
+ try {
14
+ const now = Date.now();
15
+
16
+ if (now - windowStart >= 60_000) {
17
+ recent.clear();
18
+ windowStart = now;
19
+ sent = 0;
20
+ }
21
+
22
+ if (sent >= 20) return;
23
+ const details = describeError(cause);
24
+ const key = `${details.message}\n${details.stack}`;
25
+
26
+ if (recent.has(key)) return;
27
+ recent.set(key, now);
28
+ sent += 1;
29
+
30
+ void fetch("/_widefleet/errors", {
31
+ method: "POST",
32
+ headers: { "content-type": "application/json" },
33
+ body: JSON.stringify({
34
+ id: crypto.randomUUID(),
35
+ buildId: __WIDEFLEET_BUILD_ID__,
36
+ route: location.pathname.slice(0, 1024),
37
+ ...details,
38
+ }),
39
+ keepalive: true,
40
+ credentials: "same-origin",
41
+ }).catch(() => {
42
+ // Reporting is best-effort and must never create another unhandled rejection.
43
+ });
44
+ } catch {
45
+ // Error handling must not affect application behavior, including during page teardown.
46
+ }
47
+ };
@@ -0,0 +1,42 @@
1
+ import { z } from "zod";
2
+
3
+ export const browserError = z.strictObject({
4
+ id: z.uuid(),
5
+ buildId: z.string().min(1).max(128),
6
+ message: z.string().min(1).max(4096),
7
+ stack: z.string().max(16384).nullable(),
8
+ route: z
9
+ .string()
10
+ .max(1024)
11
+ .regex(/^\/(?!\/)[^?#]*$/),
12
+ });
13
+
14
+ export const describeError = (cause: unknown) => {
15
+ if (cause instanceof Error) {
16
+ let stack = cause.stack ?? `${cause.name}: ${cause.message}`;
17
+ let current = cause.cause;
18
+ const seen = new Set([cause]);
19
+
20
+ while (current instanceof Error && !seen.has(current) && seen.size < 5) {
21
+ seen.add(current);
22
+ stack += `\nCaused by: ${current.stack ?? current.message}`;
23
+ current = current.cause;
24
+ }
25
+
26
+ return { message: cause.message.slice(0, 4096) || cause.name, stack: stack.slice(0, 16384) };
27
+ }
28
+
29
+ const reported = z.object({ message: z.string(), stack: z.string().optional() }).safeParse(cause);
30
+
31
+ if (reported.success)
32
+ return {
33
+ message: reported.data.message.slice(0, 4096) || "Unknown error",
34
+ stack: reported.data.stack?.slice(0, 16384) ?? null,
35
+ };
36
+ const text = z.string().safeParse(cause);
37
+
38
+ return {
39
+ message: text.success ? text.data.slice(0, 4096) || "Unknown error" : "Non-Error exception",
40
+ stack: null,
41
+ };
42
+ };
@@ -0,0 +1,86 @@
1
+ import { createServerFn } from "@tanstack/react-start";
2
+ import { env } from "cloudflare:workers";
3
+ import { Result } from "better-result";
4
+ import { z } from "zod";
5
+ import { database, DataUnavailable, listNotes } from "./server/data.ts";
6
+ import { captureError } from "./server/capture-error.ts";
7
+
8
+ export const getNotes = createServerFn().handler(async ({ context }) => {
9
+ const notes = await listNotes();
10
+
11
+ if (notes.isErr()) throw notes.error;
12
+
13
+ return { title: env.APP_NAME, user: context.user, notes: notes.value };
14
+ });
15
+
16
+ export const saveNote = createServerFn({ method: "POST" })
17
+ .validator(z.instanceof(FormData))
18
+ .handler(async ({ data, context }) => {
19
+ const message = z.string().trim().min(1).max(500).safeParse(data.get("message"));
20
+ const photo = data.get("photo");
21
+
22
+ if (!message.success)
23
+ return { saved: false, message: "Bitte eine Notiz mit höchstens 500 Zeichen eingeben." };
24
+
25
+ if (
26
+ !(photo instanceof File) ||
27
+ photo.size === 0 ||
28
+ photo.size > 5 * 1024 * 1024 ||
29
+ !["image/jpeg", "image/png", "image/webp"].includes(photo.type)
30
+ )
31
+ return {
32
+ saved: false,
33
+ message: "Bitte ein Foto als JPEG, PNG oder WebP auswählen (höchstens 5 MB).",
34
+ };
35
+
36
+ const db = await database();
37
+
38
+ if (db.isErr()) {
39
+ captureError(db.error);
40
+
41
+ return { saved: false, message: db.error.message };
42
+ }
43
+
44
+ const id = crypto.randomUUID();
45
+ const key = `photos/${id}`;
46
+
47
+ const saved = await Result.tryPromise({
48
+ try: async () => {
49
+ await env.FILES.put(key, await photo.arrayBuffer(), {
50
+ httpMetadata: { contentType: photo.type },
51
+ });
52
+
53
+ try {
54
+ await db.value
55
+ .prepare(
56
+ "INSERT INTO notes (id, author_id, author, message, photo, created_at) VALUES (?, ?, ?, ?, ?, ?)",
57
+ )
58
+ .bind(
59
+ id,
60
+ context.user.id,
61
+ context.user.name,
62
+ message.data,
63
+ id,
64
+ new Date().toISOString(),
65
+ )
66
+ .run();
67
+ } catch (cause) {
68
+ await env.FILES.delete(key);
69
+ throw cause;
70
+ }
71
+ },
72
+ catch: (cause) =>
73
+ new DataUnavailable({
74
+ message: "Die Notiz konnte nicht gespeichert werden. Bitte erneut versuchen.",
75
+ cause,
76
+ }),
77
+ });
78
+
79
+ if (saved.isErr()) {
80
+ captureError(saved.error);
81
+
82
+ return { saved: false, message: saved.error.message };
83
+ }
84
+
85
+ return { saved: true, message: "Deine Notiz wurde gespeichert." };
86
+ });
@@ -0,0 +1,7 @@
1
+ import { createIsomorphicFn } from "@tanstack/react-start";
2
+ import { captureError as captureBrowserError } from "./capture-error.ts";
3
+ import { captureError as captureServerError } from "./server/capture-error.ts";
4
+
5
+ export const reportError = createIsomorphicFn()
6
+ .client(captureBrowserError)
7
+ .server(captureServerError);
@@ -0,0 +1,88 @@
1
+ import { z } from "zod";
2
+ import type { PlatformContext } from "./context.ts";
3
+ import { browserError } from "../errors.ts";
4
+
5
+ const windows = new Map<string, { start: number; count: number }>();
6
+
7
+ const duplicates = new Map<string, number>();
8
+
9
+ export const receiveBrowserError = async (request: Request, context: PlatformContext) => {
10
+ const url = new URL(request.url);
11
+
12
+ if (request.method !== "POST") return new Response(null, { status: 405 });
13
+
14
+ if (request.headers.get("origin") !== url.origin) return new Response(null, { status: 403 });
15
+
16
+ if (!request.headers.get("content-type")?.startsWith("application/json"))
17
+ return new Response(null, { status: 415 });
18
+
19
+ const now = Date.now();
20
+
21
+ for (const [key, value] of windows) {
22
+ if (now - value.start >= 60_000) windows.delete(key);
23
+ }
24
+
25
+ for (const [key, timestamp] of duplicates) {
26
+ if (now - timestamp >= 60_000) duplicates.delete(key);
27
+ }
28
+
29
+ const user = context.user.id;
30
+ const window = windows.get(user) ?? { start: now, count: 0 };
31
+
32
+ if (window.count >= 30 || (!windows.has(user) && windows.size >= 1000))
33
+ return new Response(null, { status: 429, headers: { "retry-after": "60" } });
34
+ window.count += 1;
35
+ windows.set(user, window);
36
+
37
+ const reader = request.body?.getReader();
38
+
39
+ if (!reader) return new Response(null, { status: 400 });
40
+ const buffer = new Uint8Array(32 * 1024);
41
+ let length = 0;
42
+
43
+ try {
44
+ while (true) {
45
+ const part = await reader.read();
46
+
47
+ if (part.done) break;
48
+ const value = z.instanceof(Uint8Array).parse(part.value);
49
+
50
+ if (length + value.length > buffer.length) {
51
+ await reader.cancel();
52
+
53
+ return new Response(null, { status: 413 });
54
+ }
55
+
56
+ buffer.set(value, length);
57
+ length += value.length;
58
+ }
59
+
60
+ const parsed = browserError.safeParse(
61
+ JSON.parse(new TextDecoder().decode(buffer.subarray(0, length))),
62
+ );
63
+
64
+ if (!parsed.success) return new Response(null, { status: 400 });
65
+ const entry = parsed.data;
66
+ const key = `${user}:${entry.id}`;
67
+
68
+ if (!duplicates.has(key)) {
69
+ if (duplicates.size >= 1000) return new Response(null, { status: 429 });
70
+ duplicates.set(key, now);
71
+ console.error(
72
+ JSON.stringify({
73
+ widefleet: 1,
74
+ kind: "error",
75
+ source: "browser",
76
+ ...entry,
77
+ requestId: context.requestId,
78
+ }),
79
+ );
80
+ }
81
+
82
+ return new Response(null, { status: 204 });
83
+ } catch {
84
+ return new Response(null, { status: 400 });
85
+ } finally {
86
+ reader.releaseLock();
87
+ }
88
+ };
@@ -0,0 +1,35 @@
1
+ import { env } from "cloudflare:workers";
2
+ import { getGlobalStartContext } from "@tanstack/react-start";
3
+ import { getRequest } from "@tanstack/react-start/server";
4
+ import { isNotFound, isRedirect } from "@tanstack/react-router";
5
+ import { z } from "zod";
6
+ import { describeError } from "../errors.ts";
7
+ import type { PlatformContext } from "./context.ts";
8
+
9
+ /** Report a technical failure without exposing its details in the response. */
10
+ export const captureError = (cause: unknown, context?: PlatformContext, request?: Request) => {
11
+ try {
12
+ if (isRedirect(cause) || isNotFound(cause) || cause instanceof z.ZodError) return;
13
+ const status = z.object({ status: z.number() }).safeParse(cause);
14
+
15
+ if (status.success && status.data.status < 500) return;
16
+ const current = context ?? getGlobalStartContext();
17
+
18
+ if (!current || current.reportedErrors.has(cause)) return;
19
+ current.reportedErrors.add(cause);
20
+ console.error(
21
+ JSON.stringify({
22
+ widefleet: 1,
23
+ kind: "error",
24
+ source: "server",
25
+ buildId: __WIDEFLEET_BUILD_ID__,
26
+ deploymentId: env.WIDEFLEET_DEPLOYMENT_ID ?? null,
27
+ requestId: current.requestId,
28
+ route: new URL((request ?? getRequest()).url).pathname,
29
+ ...describeError(cause),
30
+ }),
31
+ );
32
+ } catch {
33
+ // A reporting failure must not replace the original application error.
34
+ }
35
+ };
@@ -0,0 +1,7 @@
1
+ import type { AppUser } from "./identity.ts";
2
+
3
+ export interface PlatformContext {
4
+ user: AppUser;
5
+ requestId: string;
6
+ reportedErrors: Set<unknown>;
7
+ }
@@ -0,0 +1,48 @@
1
+ import { env } from "cloudflare:workers";
2
+ import { Result, TaggedError } from "better-result";
3
+ import { z } from "zod";
4
+
5
+ export class DataUnavailable extends TaggedError("DataUnavailable")<{
6
+ message: string;
7
+ cause: unknown;
8
+ }> {}
9
+
10
+ const note = z.object({
11
+ id: z.uuid(),
12
+ author: z.string(),
13
+ message: z.string(),
14
+ photo: z.string().nullable(),
15
+ created_at: z.string(),
16
+ });
17
+
18
+ export const database = () =>
19
+ Result.tryPromise({
20
+ try: async () => {
21
+ await env.DB.prepare(
22
+ "CREATE TABLE IF NOT EXISTS notes (id TEXT PRIMARY KEY, author_id TEXT NOT NULL, author TEXT NOT NULL, message TEXT NOT NULL, photo TEXT, created_at TEXT NOT NULL)",
23
+ ).run();
24
+
25
+ return env.DB;
26
+ },
27
+ catch: (cause) =>
28
+ new DataUnavailable({ message: "Die Datenbank ist gerade nicht erreichbar.", cause }),
29
+ });
30
+
31
+ export const listNotes = () =>
32
+ Result.gen(async function* () {
33
+ const db = yield* Result.await(database());
34
+
35
+ return Result.tryPromise({
36
+ try: async () => {
37
+ const result = await db
38
+ .prepare(
39
+ "SELECT id, author, message, photo, created_at FROM notes ORDER BY created_at DESC LIMIT 100",
40
+ )
41
+ .all();
42
+
43
+ return z.array(note).parse(result.results);
44
+ },
45
+ catch: (cause) =>
46
+ new DataUnavailable({ message: "Notizen konnten nicht geladen werden.", cause }),
47
+ });
48
+ });
@@ -0,0 +1,30 @@
1
+ import { Result, TaggedError } from "better-result";
2
+ import { z } from "zod";
3
+
4
+ const accessContext = z.strictObject({
5
+ id: z.string().min(1),
6
+ name: z.string(),
7
+ email: z.string().nullable(),
8
+ groups: z.array(z.string()),
9
+ });
10
+
11
+ export type AppUser = z.infer<typeof accessContext>;
12
+
13
+ export class InvalidIdentity extends TaggedError("InvalidIdentity")<{ message: string }> {}
14
+
15
+ // These headers are trustworthy only on the app's private, authenticated ingress.
16
+ // The platform proxy removes client-supplied identity headers before SSO verification.
17
+ export const userFromHeaders = (headers: Headers) => {
18
+ const identity = accessContext.safeParse({
19
+ id: headers.get("x-auth-request-user"),
20
+ name: headers.get("x-auth-request-preferred-username") ?? "",
21
+ email: headers.get("x-auth-request-email"),
22
+ groups: (headers.get("x-auth-request-groups") ?? "")
23
+ .split(",")
24
+ .flatMap((group) => (group.trim() ? [group.trim()] : [])),
25
+ });
26
+
27
+ return identity.success
28
+ ? Result.ok(identity.data)
29
+ : Result.err(new InvalidIdentity({ message: "A verified platform identity is required" }));
30
+ };
@@ -0,0 +1,13 @@
1
+ import type { getRouter } from "./router.tsx";
2
+ import type { startInstance } from "./start.ts";
3
+ import type { PlatformContext } from "./lib/server/context.ts";
4
+
5
+ // Keep registration on the same export as Start's generated route-tree declaration.
6
+ declare module "@tanstack/react-start" {
7
+ interface Register {
8
+ ssr: true;
9
+ router: Awaited<ReturnType<typeof getRouter>>;
10
+ config: Awaited<ReturnType<typeof startInstance.getOptions>>;
11
+ server: { requestContext: PlatformContext };
12
+ }
13
+ }
@@ -0,0 +1,12 @@
1
+ import { createRouter } from "@tanstack/react-router";
2
+ import { routeTree } from "../.platform/routeTree.gen.ts";
3
+ import { reportError } from "./lib/report-error.ts";
4
+
5
+ export const getRouter = () =>
6
+ createRouter({
7
+ routeTree,
8
+ scrollRestoration: true,
9
+ defaultOnCatch: reportError,
10
+ defaultErrorComponent: () => <p role="alert">Die Seite konnte nicht geladen werden.</p>,
11
+ defaultNotFoundComponent: () => <p>Seite nicht gefunden.</p>,
12
+ });
@@ -0,0 +1,28 @@
1
+ import { createRootRoute, HeadContent, Scripts } from "@tanstack/react-router";
2
+ import type { ReactNode } from "react";
3
+ import stylesheet from "../styles.css?url";
4
+
5
+ export const Route = createRootRoute({
6
+ head: () => ({
7
+ meta: [
8
+ { charSet: "utf-8" },
9
+ { name: "viewport", content: "width=device-width, initial-scale=1" },
10
+ ],
11
+ links: [{ rel: "stylesheet", href: stylesheet }],
12
+ }),
13
+ shellComponent: Document,
14
+ });
15
+
16
+ function Document({ children }: { children: ReactNode }) {
17
+ return (
18
+ <html lang="de">
19
+ <head>
20
+ <HeadContent />
21
+ </head>
22
+ <body>
23
+ {children}
24
+ <Scripts />
25
+ </body>
26
+ </html>
27
+ );
28
+ }
@@ -0,0 +1,127 @@
1
+ import { createFileRoute, useRouter } from "@tanstack/react-router";
2
+ import { useEffect, useState } from "react";
3
+ import { getNotes, saveNote } from "../lib/notes.functions.ts";
4
+ import { captureError } from "../lib/capture-error.ts";
5
+
6
+ export const Route = createFileRoute("/")({
7
+ loader: () => getNotes(),
8
+ head: ({ loaderData }) => ({ meta: [{ title: loaderData?.title ?? "Team-Notizen" }] }),
9
+ component: Notes,
10
+ });
11
+
12
+ function Notes() {
13
+ const data = Route.useLoaderData();
14
+ const router = useRouter();
15
+ const [result, setResult] = useState<{ saved: boolean; message: string }>();
16
+ const [pending, setPending] = useState(false);
17
+ const [ready, setReady] = useState(false);
18
+
19
+ useEffect(() => setReady(true), []);
20
+
21
+ const submit = async (form: HTMLFormElement) => {
22
+ setPending(true);
23
+ setResult(undefined);
24
+
25
+ try {
26
+ const saved = await saveNote({ data: new FormData(form) });
27
+
28
+ setResult(saved);
29
+
30
+ if (saved.saved) {
31
+ form.reset();
32
+ await router.invalidate();
33
+ }
34
+ } catch (cause) {
35
+ captureError(cause);
36
+ setResult((current) =>
37
+ current?.saved
38
+ ? {
39
+ saved: true,
40
+ message:
41
+ "Deine Notiz wurde gespeichert. Bitte lade die Seite neu, um die Ansicht zu aktualisieren.",
42
+ }
43
+ : { saved: false, message: "Die Anfrage ist fehlgeschlagen. Bitte erneut versuchen." },
44
+ );
45
+ } finally {
46
+ setPending(false);
47
+ }
48
+ };
49
+
50
+ return (
51
+ <main>
52
+ <header>
53
+ <p className="eyebrow">UNSER TEAM</p>
54
+ <h1>{data.title}</h1>
55
+ <p>Beobachtungen, Ideen und kleine Fortschritte aus unserem Alltag.</p>
56
+ <p className="identity">Angemeldet als {data.user.name || data.user.id}</p>
57
+ </header>
58
+ <section aria-labelledby="new-note">
59
+ <h2 id="new-note">Was möchtest du teilen?</h2>
60
+ {result && <p role={result.saved ? "status" : "alert"}>{result.message}</p>}
61
+ <form
62
+ method="post"
63
+ encType="multipart/form-data"
64
+ onSubmit={(event) => {
65
+ event.preventDefault();
66
+ void submit(event.currentTarget);
67
+ }}
68
+ >
69
+ <label htmlFor="message">Deine Notiz</label>
70
+ <textarea
71
+ id="message"
72
+ name="message"
73
+ required
74
+ maxLength={500}
75
+ rows={4}
76
+ placeholder="Was gibt es Neues?"
77
+ />
78
+ <label htmlFor="photo">Ein Foto dazu</label>
79
+ <input
80
+ id="photo"
81
+ name="photo"
82
+ type="file"
83
+ accept="image/jpeg,image/png,image/webp"
84
+ required
85
+ aria-describedby="photo-hint"
86
+ />
87
+ <p id="photo-hint" className="hint">
88
+ JPEG, PNG oder WebP, bis 5 MB.
89
+ </p>
90
+ <button disabled={pending || !ready}>
91
+ {pending ? "Wird gespeichert …" : "Notiz teilen"}
92
+ </button>
93
+ </form>
94
+ </section>
95
+ <section aria-labelledby="notes">
96
+ <h2 id="notes">Aus dem Team</h2>
97
+ {data.notes.length === 0 ? (
98
+ <p>Noch ist es hier ruhig. Teile die erste Notiz mit deinem Team.</p>
99
+ ) : (
100
+ <div className="notes">
101
+ {data.notes.map((note) => (
102
+ <article key={note.id}>
103
+ {note.photo && (
104
+ <img
105
+ src={`/photos/${note.photo}`}
106
+ alt={`Foto zur Notiz von ${note.author}`}
107
+ loading="lazy"
108
+ />
109
+ )}
110
+ <div className="content">
111
+ <p>{note.message}</p>
112
+ <footer>
113
+ {note.author}
114
+ <br />
115
+ <time dateTime={note.created_at}>
116
+ {new Date(note.created_at).toISOString().slice(0, 10)}
117
+ </time>
118
+ </footer>
119
+ </div>
120
+ </article>
121
+ ))}
122
+ </div>
123
+ )}
124
+ </section>
125
+ </main>
126
+ );
127
+ }
@@ -0,0 +1,27 @@
1
+ import { createFileRoute } from "@tanstack/react-router";
2
+ import { env } from "cloudflare:workers";
3
+ import { z } from "zod";
4
+
5
+ export const Route = createFileRoute("/photos/$id")({
6
+ server: {
7
+ handlers: {
8
+ GET: async ({ params }) => {
9
+ const id = z.uuid().safeParse(params.id);
10
+
11
+ if (!id.success) return new Response("Foto nicht gefunden.", { status: 404 });
12
+ const file = await env.FILES.get(`photos/${id.data}`);
13
+
14
+ if (!file) return new Response("Foto nicht gefunden.", { status: 404 });
15
+
16
+ return new Response(await file.arrayBuffer(), {
17
+ headers: {
18
+ "content-type": file.httpMetadata?.contentType ?? "application/octet-stream",
19
+ "cache-control": "private, no-store",
20
+ "x-content-type-options": "nosniff",
21
+ "content-security-policy": "default-src 'none'; sandbox",
22
+ },
23
+ });
24
+ },
25
+ },
26
+ },
27
+ });