@mandujs/core 0.21.0 → 0.22.1

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 (122) hide show
  1. package/package.json +101 -69
  2. package/src/auth/__tests__/login.test.ts +419 -0
  3. package/src/auth/__tests__/password.test.ts +122 -0
  4. package/src/auth/__tests__/reset.test.ts +296 -0
  5. package/src/auth/__tests__/tokens.test.ts +274 -0
  6. package/src/auth/__tests__/verification.test.ts +274 -0
  7. package/src/auth/index.ts +76 -0
  8. package/src/auth/login.ts +225 -0
  9. package/src/auth/password.ts +120 -0
  10. package/src/auth/reset.ts +243 -0
  11. package/src/auth/tokens.ts +612 -0
  12. package/src/auth/verification.ts +253 -0
  13. package/src/bundler/__tests__/cli-bench-utils.test.ts +149 -0
  14. package/src/bundler/__tests__/cold-start.test.ts +504 -0
  15. package/src/bundler/__tests__/csp-nonce.test.ts +278 -0
  16. package/src/bundler/__tests__/dev-reliability.test.ts +619 -0
  17. package/src/bundler/__tests__/extended-watch.test.ts +710 -0
  18. package/src/bundler/__tests__/fast-refresh.test.ts +596 -0
  19. package/src/bundler/__tests__/hdr.test.ts +353 -0
  20. package/src/bundler/__tests__/hmr-client.test.ts +532 -0
  21. package/src/bundler/__tests__/manifest-schema.test.ts +266 -0
  22. package/src/bundler/__tests__/prod-smoke.test.ts +138 -0
  23. package/src/bundler/__tests__/slot-dispatch.test.ts +573 -0
  24. package/src/bundler/__tests__/url-cap-and-slot-regex.test.ts +286 -0
  25. package/src/bundler/__tests__/vendor-cache.test.ts +455 -0
  26. package/src/bundler/build.test.ts +8 -1
  27. package/src/bundler/build.ts +310 -18
  28. package/src/bundler/css.ts +326 -323
  29. package/src/bundler/dev.ts +1611 -59
  30. package/src/bundler/fast-refresh-plugin.ts +307 -0
  31. package/src/bundler/hmr-types.ts +252 -0
  32. package/src/bundler/manifest-schema.ts +301 -0
  33. package/src/bundler/safe-build.test.ts +128 -0
  34. package/src/bundler/safe-build.ts +77 -0
  35. package/src/bundler/scenario-matrix.ts +229 -0
  36. package/src/bundler/types.ts +11 -0
  37. package/src/bundler/vendor-cache-types.ts +130 -0
  38. package/src/bundler/vendor-cache.ts +526 -0
  39. package/src/client/router.ts +214 -56
  40. package/src/db/__tests__/db.test.ts +485 -0
  41. package/src/db/index.ts +513 -0
  42. package/src/db/migrations/__tests__/runner.test.ts +661 -0
  43. package/src/db/migrations/history-table.ts +345 -0
  44. package/src/db/migrations/lock.ts +269 -0
  45. package/src/db/migrations/runner.ts +633 -0
  46. package/src/desktop/__tests__/smoke.test.ts +100 -0
  47. package/src/desktop/__tests__/window.test.ts +172 -0
  48. package/src/desktop/__tests__/worker.test.ts +266 -0
  49. package/src/desktop/index.ts +43 -0
  50. package/src/desktop/types.ts +158 -0
  51. package/src/desktop/window.ts +492 -0
  52. package/src/desktop/worker.ts +180 -0
  53. package/src/email/__tests__/email.test.ts +355 -0
  54. package/src/email/index.ts +282 -0
  55. package/src/email/resend.ts +163 -0
  56. package/src/email/smtp.ts +64 -0
  57. package/src/filling/__tests__/session-sqlite.test.ts +454 -0
  58. package/src/filling/context.ts +72 -78
  59. package/src/filling/cookie-codec.ts +299 -0
  60. package/src/filling/deps.ts +25 -1
  61. package/src/filling/filling.ts +28 -3
  62. package/src/filling/session-sqlite.ts +617 -0
  63. package/src/filling/session.ts +265 -216
  64. package/src/guard/decision-memory.test.ts +52 -22
  65. package/src/id/__tests__/id.test.ts +120 -0
  66. package/src/id/index.ts +105 -0
  67. package/src/kitchen/index.ts +2 -2
  68. package/src/kitchen/kitchen-handler.ts +86 -0
  69. package/src/kitchen/stream/activity-sse.ts +2 -1
  70. package/src/middleware/csrf.ts +328 -0
  71. package/src/middleware/index.ts +40 -0
  72. package/src/middleware/oauth/__tests__/oauth.test.ts +574 -0
  73. package/src/middleware/oauth/index.ts +505 -0
  74. package/src/middleware/oauth/providers.ts +115 -0
  75. package/src/middleware/rate-limit/__tests__/rate-limit.test.ts +642 -0
  76. package/src/middleware/rate-limit/index.ts +522 -0
  77. package/src/middleware/rate-limit/sqlite-store.ts +382 -0
  78. package/src/middleware/secure/__tests__/secure.test.ts +360 -0
  79. package/src/middleware/secure/csp.ts +193 -0
  80. package/src/middleware/secure/index.ts +417 -0
  81. package/src/middleware/session.ts +174 -0
  82. package/src/observability/event-bus.ts +81 -79
  83. package/src/paths.ts +37 -0
  84. package/src/perf/hmr-markers.ts +215 -0
  85. package/src/perf/index.ts +104 -0
  86. package/src/resource/__tests__/generator.test.ts +603 -2
  87. package/src/resource/ddl/__tests__/diff.test.ts +639 -0
  88. package/src/resource/ddl/__tests__/emit.test.ts +799 -0
  89. package/src/resource/ddl/__tests__/snapshot.test.ts +499 -0
  90. package/src/resource/ddl/diff.ts +392 -0
  91. package/src/resource/ddl/emit.ts +548 -0
  92. package/src/resource/ddl/persistence-types.ts +218 -0
  93. package/src/resource/ddl/snapshot.ts +447 -0
  94. package/src/resource/ddl/type-map.ts +223 -0
  95. package/src/resource/ddl/types.ts +232 -0
  96. package/src/resource/generator-repo.ts +610 -0
  97. package/src/resource/generator-schema.ts +476 -0
  98. package/src/resource/generator.ts +117 -1
  99. package/src/resource/index.ts +17 -1
  100. package/src/resource/schema.ts +30 -0
  101. package/src/router/fs-scanner.ts +3 -0
  102. package/src/runtime/__tests__/error-boundary-redaction.test.ts +141 -0
  103. package/src/runtime/__tests__/hdr-client.test.ts +223 -0
  104. package/src/runtime/__tests__/http-errors.test.ts +117 -0
  105. package/src/runtime/__tests__/not-found.test.ts +152 -0
  106. package/src/runtime/boundary.tsx +21 -1
  107. package/src/runtime/fast-refresh-runtime.ts +322 -0
  108. package/src/runtime/fast-refresh-types.ts +128 -0
  109. package/src/runtime/hmr-client.ts +409 -0
  110. package/src/runtime/http-errors.ts +113 -0
  111. package/src/runtime/index.ts +6 -0
  112. package/src/runtime/logger.ts +678 -677
  113. package/src/runtime/not-found.ts +93 -0
  114. package/src/runtime/redirect.ts +133 -0
  115. package/src/runtime/server.ts +518 -20
  116. package/src/runtime/ssr.ts +340 -10
  117. package/src/runtime/streaming-ssr.ts +222 -19
  118. package/src/scheduler/__tests__/scheduler.test.ts +514 -0
  119. package/src/scheduler/index.ts +343 -0
  120. package/src/storage/s3/__tests__/s3.test.ts +479 -0
  121. package/src/storage/s3/index.ts +412 -0
  122. package/src/testing/index.ts +58 -0
@@ -0,0 +1,412 @@
1
+ /**
2
+ * @mandujs/core/storage/s3
3
+ *
4
+ * Thin, S3-compatible object storage helper backed by **native `Bun.S3Client`**
5
+ * (no AWS SDK, no external deps). The same client works against AWS S3,
6
+ * Cloudflare R2, MinIO, DigitalOcean Spaces, and any other S3-compatible
7
+ * service — the only thing that changes is the `endpoint` URL.
8
+ *
9
+ * ## Credentials
10
+ *
11
+ * Bun reads `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` (and optionally
12
+ * `AWS_SESSION_TOKEN`) — plus the `S3_*` variants — from the environment at
13
+ * initialization time. You can also pass them explicitly to the underlying
14
+ * `Bun.S3Client`, but this helper intentionally does **not** surface that
15
+ * option: routing secrets through env vars (or a `.env` file loaded by Bun)
16
+ * keeps credentials out of application code. See
17
+ * https://bun.com/docs/runtime/s3#credentials for the full matrix.
18
+ *
19
+ * ## Endpoint
20
+ *
21
+ * Pass `endpoint` on the client config for R2/MinIO/GCS/Supabase/etc. Omit it
22
+ * for AWS (Bun infers the endpoint from `region` + `bucket`).
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * import { createS3Client } from "@mandujs/core/storage/s3";
27
+ *
28
+ * const storage = createS3Client({
29
+ * bucket: "uploads",
30
+ * endpoint: "https://<account>.r2.cloudflarestorage.com",
31
+ * region: "auto",
32
+ * });
33
+ *
34
+ * const url = await storage.upload(file, { key: `u/${id}.png` });
35
+ * const presigned = await storage.presign({ key: "u/next.png", method: "PUT", contentType: "image/png" });
36
+ * ```
37
+ *
38
+ * @module storage/s3
39
+ */
40
+
41
+ // ─── Public types ───────────────────────────────────────────────────────────
42
+
43
+ /**
44
+ * S3 client configuration. Credentials are **not** part of this interface —
45
+ * they come from `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` env vars that
46
+ * Bun auto-reads. See module docs.
47
+ */
48
+ export interface S3Config {
49
+ /** Bucket name. Required. */
50
+ bucket: string;
51
+ /**
52
+ * Custom endpoint URL. Required for R2/MinIO/GCS/etc.; omit for AWS (Bun
53
+ * infers from `region`).
54
+ */
55
+ endpoint?: string;
56
+ /**
57
+ * Force path-style URLs (`endpoint/bucket/key`) instead of virtual-hosted
58
+ * (`bucket.endpoint/key`). MinIO usually needs this set to `true`. AWS and
59
+ * R2 work with either but default to virtual-hosted. Default: `false`.
60
+ */
61
+ forcePathStyle?: boolean;
62
+ /**
63
+ * Region. Bun defaults to `us-east-1` for AWS; set `"auto"` for Cloudflare
64
+ * R2. No default applied here — we pass through as-is so Bun's own
65
+ * defaulting logic stays authoritative.
66
+ */
67
+ region?: string;
68
+ }
69
+
70
+ /** Options for uploading a single object. */
71
+ export interface S3UploadOptions {
72
+ /** Target object key (path inside the bucket). Required. */
73
+ key: string;
74
+ /**
75
+ * Content-Type header. Inferred from the key's file extension when omitted
76
+ * — see `getContentType` below for the covered extensions.
77
+ */
78
+ contentType?: string;
79
+ /**
80
+ * User metadata. Keys are lowercased and prefixed with `x-amz-meta-` by S3.
81
+ * Values must be ASCII — non-ASCII characters will be rejected by most
82
+ * providers; we do not validate here.
83
+ */
84
+ metadata?: Record<string, string>;
85
+ /**
86
+ * Canned ACL. Applied to this upload only. Omit to inherit the bucket
87
+ * default (recommended for private buckets).
88
+ */
89
+ acl?: "private" | "public-read";
90
+ }
91
+
92
+ /** Options for generating a presigned URL. */
93
+ export interface S3PresignOptions {
94
+ /** Object key. Required. */
95
+ key: string;
96
+ /** HTTP method. Default: `"PUT"` (client-direct upload is the common case). */
97
+ method?: "GET" | "PUT";
98
+ /** URL lifetime in **seconds**. Default: 900 (15 minutes). */
99
+ expiresIn?: number;
100
+ /**
101
+ * `Content-Type` baked into the signature. Only meaningful for `PUT`; the
102
+ * uploading client MUST send a matching header or the signature will fail.
103
+ */
104
+ contentType?: string;
105
+ }
106
+
107
+ /** Opaque client instance. */
108
+ export interface S3Client {
109
+ /**
110
+ * Uploads a blob/buffer and resolves to the canonical object URL
111
+ * (endpoint + bucket + key).
112
+ */
113
+ upload(
114
+ body: Blob | ArrayBuffer | Uint8Array,
115
+ options: S3UploadOptions,
116
+ ): Promise<string>;
117
+
118
+ /** Generates a presigned URL for client-direct upload (PUT) or download (GET). */
119
+ presign(options: S3PresignOptions): Promise<string>;
120
+
121
+ /** Deletes an object. Resolves silently if the object does not exist. */
122
+ delete(key: string): Promise<void>;
123
+
124
+ /** Returns a readable stream for the object body. Throws if not found. */
125
+ getReadable(key: string): Promise<ReadableStream>;
126
+
127
+ /**
128
+ * Head check — `true` if the object exists, `false` on 404. Any other error
129
+ * (network failure, 403, malformed response) is re-thrown.
130
+ */
131
+ exists(key: string): Promise<boolean>;
132
+ }
133
+
134
+ // ─── Bun runtime surface (structural; no `any`) ─────────────────────────────
135
+
136
+ /** Options accepted by `S3File.write`. Mirrors Bun's BlobPropertyBag extensions. */
137
+ interface BunS3WriteOptions {
138
+ type?: string;
139
+ acl?: "private" | "public-read";
140
+ }
141
+
142
+ /** Options accepted by `S3File.presign`. */
143
+ interface BunS3PresignOptions {
144
+ method?: "GET" | "PUT";
145
+ expiresIn?: number;
146
+ type?: string;
147
+ }
148
+
149
+ /** Minimal shape of the `S3File` handle returned by `client.file(key)`. */
150
+ interface BunS3File {
151
+ write(
152
+ body: Blob | ArrayBuffer | Uint8Array,
153
+ options?: BunS3WriteOptions,
154
+ ): Promise<number>;
155
+ presign(options?: BunS3PresignOptions): string;
156
+ delete(): Promise<void>;
157
+ exists(): Promise<boolean>;
158
+ stream(): ReadableStream;
159
+ }
160
+
161
+ /** Options accepted by the `Bun.S3Client` constructor. */
162
+ interface BunS3ClientConfig {
163
+ bucket: string;
164
+ endpoint?: string;
165
+ region?: string;
166
+ virtualHostedStyle?: boolean;
167
+ }
168
+
169
+ /** Minimal `Bun.S3Client` instance shape used by this module. */
170
+ export interface BunS3ClientInstance {
171
+ file(key: string): BunS3File;
172
+ }
173
+
174
+ /**
175
+ * Constructor surface — `Bun.S3Client` is a class. We only need the `new`
176
+ * signature structurally, so we type it as a callable returning an instance.
177
+ */
178
+ export type BunS3ClientCtor = new (config: BunS3ClientConfig) => BunS3ClientInstance;
179
+
180
+ // ─── Content-type inference ─────────────────────────────────────────────────
181
+
182
+ const EXTENSION_MAP: ReadonlyMap<string, string> = new Map([
183
+ ["jpg", "image/jpeg"],
184
+ ["jpeg", "image/jpeg"],
185
+ ["png", "image/png"],
186
+ ["webp", "image/webp"],
187
+ ["gif", "image/gif"],
188
+ ["pdf", "application/pdf"],
189
+ ["txt", "text/plain"],
190
+ ["json", "application/json"],
191
+ ["csv", "text/csv"],
192
+ ["zip", "application/zip"],
193
+ ["mp4", "video/mp4"],
194
+ ["webm", "video/webm"],
195
+ ]);
196
+
197
+ /**
198
+ * Maps a key's trailing file extension to a MIME type. Returns
199
+ * `application/octet-stream` for unknown/missing extensions.
200
+ *
201
+ * Exported for tests and for callers that want to inspect the mapping without
202
+ * uploading (e.g., for building a `Content-Type` header on a presigned PUT).
203
+ */
204
+ export function getContentType(key: string): string {
205
+ const lastDot = key.lastIndexOf(".");
206
+ if (lastDot === -1 || lastDot === key.length - 1) {
207
+ return "application/octet-stream";
208
+ }
209
+ const ext = key.slice(lastDot + 1).toLowerCase();
210
+ return EXTENSION_MAP.get(ext) ?? "application/octet-stream";
211
+ }
212
+
213
+ // ─── URL construction ───────────────────────────────────────────────────────
214
+
215
+ /**
216
+ * Builds the canonical object URL that `upload()` returns. Uses the same
217
+ * path-vs-virtual-host logic Bun itself applies, so the URL matches what
218
+ * `fetch()` would resolve.
219
+ *
220
+ * For AWS (no endpoint set), we return an `s3://<bucket>/<key>` URI — the
221
+ * caller may not know the region and we don't want to guess at a public URL.
222
+ */
223
+ function buildObjectUrl(
224
+ config: S3Config,
225
+ key: string,
226
+ ): string {
227
+ const encodedKey = encodeKey(key);
228
+
229
+ if (!config.endpoint) {
230
+ // Bun infers the AWS endpoint; returning s3:// keeps this provider-agnostic
231
+ // without pretending to know if the bucket is public-read.
232
+ return `s3://${config.bucket}/${encodedKey}`;
233
+ }
234
+
235
+ const base = config.endpoint.replace(/\/+$/, "");
236
+ if (config.forcePathStyle) {
237
+ return `${base}/${config.bucket}/${encodedKey}`;
238
+ }
239
+
240
+ // Virtual-hosted style: splice bucket into the hostname.
241
+ try {
242
+ const url = new URL(base);
243
+ url.hostname = `${config.bucket}.${url.hostname}`;
244
+ return `${url.toString().replace(/\/+$/, "")}/${encodedKey}`;
245
+ } catch {
246
+ // Malformed endpoint — fall back to path style so we still return a
247
+ // deterministic, debuggable URL.
248
+ return `${base}/${config.bucket}/${encodedKey}`;
249
+ }
250
+ }
251
+
252
+ /** URL-encodes every path segment of an S3 key while preserving `/` separators. */
253
+ function encodeKey(key: string): string {
254
+ return key
255
+ .split("/")
256
+ .map((segment) => encodeURIComponent(segment))
257
+ .join("/");
258
+ }
259
+
260
+ // ─── Bun runtime probe ──────────────────────────────────────────────────────
261
+
262
+ function getBunS3ClientCtor(): BunS3ClientCtor {
263
+ const g = globalThis as unknown as { Bun?: { S3Client?: BunS3ClientCtor } };
264
+ if (!g.Bun || !g.Bun.S3Client) {
265
+ throw new Error(
266
+ "[@mandujs/core/storage/s3] Bun.S3Client is unavailable — this module requires the Bun runtime (>= 1.3).",
267
+ );
268
+ }
269
+ return g.Bun.S3Client;
270
+ }
271
+
272
+ // ─── Factory ────────────────────────────────────────────────────────────────
273
+
274
+ /**
275
+ * Internal factory accepting an injectable `S3Client` constructor — used by
276
+ * unit tests to swap in a fake implementation. Production callers use
277
+ * {@link createS3Client}, which binds this to `Bun.S3Client`.
278
+ */
279
+ export function _createS3ClientWith(
280
+ Ctor: BunS3ClientCtor,
281
+ config: S3Config,
282
+ ): S3Client {
283
+ if (!config.bucket || typeof config.bucket !== "string") {
284
+ throw new TypeError(
285
+ "[@mandujs/core/storage/s3] createS3Client: 'bucket' is required.",
286
+ );
287
+ }
288
+
289
+ const bunClient = new Ctor({
290
+ bucket: config.bucket,
291
+ endpoint: config.endpoint,
292
+ region: config.region,
293
+ // forcePathStyle === true ⇒ virtualHostedStyle: false (the Bun default).
294
+ // forcePathStyle === false ⇒ leave Bun's default untouched.
295
+ // Only set virtualHostedStyle explicitly if the user *opts out* of path
296
+ // style for a service that normally defaults to it. The map here is 1:1.
297
+ virtualHostedStyle: config.forcePathStyle === true ? false : undefined,
298
+ });
299
+
300
+ async function upload(
301
+ body: Blob | ArrayBuffer | Uint8Array,
302
+ options: S3UploadOptions,
303
+ ): Promise<string> {
304
+ if (!options.key) {
305
+ throw new TypeError(
306
+ "[@mandujs/core/storage/s3] upload: 'key' is required.",
307
+ );
308
+ }
309
+ const file = bunClient.file(options.key);
310
+ const contentType = options.contentType ?? getContentType(options.key);
311
+
312
+ await file.write(body, {
313
+ type: contentType,
314
+ ...(options.acl !== undefined ? { acl: options.acl } : {}),
315
+ });
316
+
317
+ // NOTE: metadata is accepted in our public type for forward-compat, but
318
+ // Bun 1.3's `S3File.write` does not surface a `metadata` option. Dropping
319
+ // it silently would be a bug waiting to happen, so we throw at call time.
320
+ if (options.metadata && Object.keys(options.metadata).length > 0) {
321
+ throw new Error(
322
+ "[@mandujs/core/storage/s3] upload: 'metadata' is not yet supported by Bun.S3Client.write. Use a presigned URL with custom headers, or file an issue upstream.",
323
+ );
324
+ }
325
+
326
+ return buildObjectUrl(config, options.key);
327
+ }
328
+
329
+ async function presign(options: S3PresignOptions): Promise<string> {
330
+ if (!options.key) {
331
+ throw new TypeError(
332
+ "[@mandujs/core/storage/s3] presign: 'key' is required.",
333
+ );
334
+ }
335
+ const method = options.method ?? "PUT";
336
+ const expiresIn = options.expiresIn ?? 900;
337
+ const file = bunClient.file(options.key);
338
+
339
+ // Bun.S3File.presign is synchronous; we wrap in a Promise so the public
340
+ // API stays consistent with the rest of the helper surface.
341
+ const url = file.presign({
342
+ method,
343
+ expiresIn,
344
+ ...(options.contentType !== undefined ? { type: options.contentType } : {}),
345
+ });
346
+ return url;
347
+ }
348
+
349
+ async function deleteObject(key: string): Promise<void> {
350
+ const file = bunClient.file(key);
351
+ try {
352
+ await file.delete();
353
+ } catch (err) {
354
+ // S3 returns success for delete-of-missing-key; but some S3-compatible
355
+ // providers (and network hiccups) can surface a 404-shaped error. We
356
+ // swallow "not found" and re-throw everything else.
357
+ if (isNotFoundError(err)) return;
358
+ throw err;
359
+ }
360
+ }
361
+
362
+ async function getReadable(key: string): Promise<ReadableStream> {
363
+ const file = bunClient.file(key);
364
+ // `file.stream()` is synchronous and returns a ReadableStream that lazily
365
+ // issues the GET when you start consuming. We preserve that laziness and
366
+ // let errors surface on first read rather than proactively HEAD-ing here.
367
+ return file.stream();
368
+ }
369
+
370
+ async function exists(key: string): Promise<boolean> {
371
+ const file = bunClient.file(key);
372
+ try {
373
+ return await file.exists();
374
+ } catch (err) {
375
+ if (isNotFoundError(err)) return false;
376
+ throw err;
377
+ }
378
+ }
379
+
380
+ return {
381
+ upload,
382
+ presign,
383
+ delete: deleteObject,
384
+ getReadable,
385
+ exists,
386
+ };
387
+ }
388
+
389
+ /**
390
+ * Creates an S3-compatible storage client.
391
+ *
392
+ * @throws if `config.bucket` is missing, or if called outside the Bun runtime.
393
+ */
394
+ export function createS3Client(config: S3Config): S3Client {
395
+ return _createS3ClientWith(getBunS3ClientCtor(), config);
396
+ }
397
+
398
+ // ─── Error helpers ──────────────────────────────────────────────────────────
399
+
400
+ /**
401
+ * Structural check for "object not found" errors raised by Bun's S3 layer.
402
+ * Bun emits an `S3Error` instance with `code` set; we also handle the
403
+ * HTTP-status-bearing variants some providers surface.
404
+ */
405
+ function isNotFoundError(err: unknown): boolean {
406
+ if (!err || typeof err !== "object") return false;
407
+ const e = err as { name?: unknown; code?: unknown; status?: unknown };
408
+ if (e.code === "NoSuchKey") return true;
409
+ if (e.code === "NotFound") return true;
410
+ if (e.status === 404) return true;
411
+ return false;
412
+ }
@@ -3,6 +3,8 @@
3
3
  * 서버 없이 라우트/filling 단위 테스트
4
4
  */
5
5
 
6
+ import path from "path";
7
+ import os from "os";
6
8
  import { ManduContext } from "../filling/context";
7
9
  import type { ManduFilling } from "../filling/filling";
8
10
  import type { RouteSpec, RoutesManifest } from "../spec/schema";
@@ -187,3 +189,59 @@ export function createTestManifest(routes: Partial<RouteSpec>[]): RoutesManifest
187
189
  export function createTestIsland(name: string, strategy: string = "visible") {
188
190
  return { __island: true, __hydrate: strategy, __name: name };
189
191
  }
192
+
193
+ // ========== createMockMcpContext ==========
194
+
195
+ /**
196
+ * Mock MCP context shape mirroring the real MCP server context
197
+ * (see `packages/mcp/src/utils/project.ts`).
198
+ *
199
+ * Use this in tests for MCP tool plugins and slot/contract validators
200
+ * that accept an MCP-context-like object.
201
+ */
202
+ export interface MockMcpContext {
203
+ paths: {
204
+ repoRoot: string;
205
+ manduDir: string;
206
+ manifestPath: string;
207
+ specsDir: string;
208
+ slotsDir: string;
209
+ };
210
+ readConfig: () => Promise<Record<string, unknown>>;
211
+ readManifest: () => Promise<RoutesManifest>;
212
+ }
213
+
214
+ /**
215
+ * Create a mock MCP context suitable for unit-testing MCP tools without
216
+ * spinning up an actual project on disk.
217
+ *
218
+ * @example
219
+ * ```typescript
220
+ * const ctx = createMockMcpContext({
221
+ * config: { guard: { preset: "fsd" } },
222
+ * manifest: createTestManifest([{ id: "home", kind: "page", pattern: "/" }]),
223
+ * });
224
+ * await myTool.execute(ctx, { input: "..." });
225
+ * ```
226
+ */
227
+ export function createMockMcpContext(options: {
228
+ root?: string;
229
+ config?: Record<string, unknown>;
230
+ manifest?: RoutesManifest;
231
+ } = {}): MockMcpContext {
232
+ const root = options.root ?? path.join(os.tmpdir(), "mandu-mock-mcp");
233
+ const config = options.config ?? {};
234
+ const manifest = options.manifest ?? { version: 1, routes: [] };
235
+
236
+ return {
237
+ paths: {
238
+ repoRoot: root,
239
+ manduDir: path.join(root, ".mandu"),
240
+ manifestPath: path.join(root, ".mandu", "routes.manifest.json"),
241
+ specsDir: path.join(root, "spec"),
242
+ slotsDir: path.join(root, "spec", "slots"),
243
+ },
244
+ readConfig: async () => config,
245
+ readManifest: async () => manifest,
246
+ };
247
+ }