@guren/core 1.8.0 → 1.9.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/dist/index.d.ts CHANGED
@@ -1,22 +1,22 @@
1
- import { ApiTokenStore, ApiToken, SessionStore, SessionData, OAuthStateStore, OAuthStatePayload } from '@guren/server';
2
- export * from '@guren/server';
3
- export { AccessorDefinitions, AccessorFn, AwsDataApiDatabase, AwsDataApiDatabaseOptions, AwsDataApiSeederContext, BelongsToManyRecord, BelongsToManyRelationResult, BelongsToRecord, BelongsToRelationResult, BelongsToRequiredRecord, CastType, D1DatabaseHandle, D1DatabaseOptions, DrizzleAdapter, EagerLoadConstraint, FindManyOptions, GroupCondition, HasManyRecord, HasManyRelationResult, HasManyThroughRecord, HasManyThroughRelationResult, HasOneRecord, HasOneRelationResult, HookCallback, HookName, InferModelInsert, InferModelRecord, MassAssignmentException, MigrationRunSummary, MigrationStatusEntry, Model, ModelHooks, ModelNotFoundException, ModelObserver, ModelObserverConstructor, ModelPaginationMeta, ModelQueryOptions, MorphManyRecord, MorphManyRelationResult, MorphToRecord, MorphToRelationResult, MutatorDefinitions, MutatorFn, MySqlDatabase, MySqlDatabaseOptions, MySqlSeederContext, ORMAdapter, ORMAdapterAdvanced, OrderByClause, OrderByInput, OrderDefinition, OrderDirection, PaginateOptions, PaginatedResult, PlainObject, PostgresDatabase, PostgresDatabaseOptions, PostgresSeederContext, QueryBuilder, QueryBuilderOptions, ScopeFunction, SeederContext, SeederHandler, SeederRunSummary, SimpleCondition, SoftDeletes, SoftDeletesStatic, SqliteDatabase, SqliteDatabaseOptions, SqliteSeederContext, TransactionHandle, TransactionModelScope, WhereClause, WhereCondition, WhereGroupCallback, WhereOperator, WithRelations, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, runSeeders } from '@guren/orm';
4
-
1
+ import { ApiToken, ApiTokenStore, Command, Job, OAuthStatePayload, OAuthStateStore, SessionData, SessionStore, StorageManager } from "@guren/server";
2
+ import { AccessorDefinitions, AccessorFn, AwsDataApiDatabase, AwsDataApiDatabaseOptions, AwsDataApiSeederContext, BelongsToManyRecord, BelongsToManyRelationResult, BelongsToRecord, BelongsToRelationResult, BelongsToRequiredRecord, CastType, D1DatabaseHandle, D1DatabaseOptions, DrizzleAdapter, EagerLoadConstraint, FindManyOptions, GroupCondition, HasManyRecord, HasManyRelationResult, HasManyThroughRecord, HasManyThroughRelationResult, HasOneRecord, HasOneRelationResult, HookCallback, HookName, InferModelInsert, InferModelRecord, MassAssignmentException, MigrationRunSummary, MigrationStatusEntry, Model, Model as Model$1, ModelHooks, ModelNotFoundException, ModelObserver, ModelObserverConstructor, ModelPaginationMeta, ModelQueryOptions, MorphManyRecord, MorphManyRelationResult, MorphToRecord, MorphToRelationResult, MutatorDefinitions, MutatorFn, MySqlDatabase, MySqlDatabaseOptions, MySqlSeederContext, ORMAdapter, ORMAdapterAdvanced, OrderByClause, OrderByInput, OrderDefinition, OrderDirection, PaginateOptions, PaginatedResult, PlainObject, PlainObject as PlainObject$1, PostgresDatabase, PostgresDatabaseOptions, PostgresSeederContext, QueryBuilder, QueryBuilderOptions, ScopeFunction, SeederContext, SeederHandler, SeederRunSummary, SimpleCondition, SoftDeletes, SoftDeletesStatic, SqliteDatabase, SqliteDatabaseOptions, SqliteSeederContext, TransactionHandle, TransactionModelScope, WhereClause, WhereCondition, WhereGroupCallback, WhereOperator, WithRelations, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, runSeeders } from "@guren/orm";
3
+ export * from "@guren/server";
4
+ //#region src/api-token-store.d.ts
5
5
  /**
6
6
  * Options for DatabaseApiTokenStore.
7
7
  */
8
8
  interface DatabaseApiTokenStoreOptions {
9
- /**
10
- * How the `abilities` column stores the ability list.
11
- *
12
- * - `'json'` (default) passes the array straight through — use with a
13
- * JSON-capable column (pg `jsonb`/`json`, sqlite `text(..., { mode: 'json' })`).
14
- * - `'text'` serializes to a JSON string for plain text columns.
15
- *
16
- * Reads always accept both representations.
17
- * @default 'json'
18
- */
19
- abilitiesMode?: 'json' | 'text';
9
+ /**
10
+ * How the `abilities` column stores the ability list.
11
+ *
12
+ * - `'json'` (default) passes the array straight through — use with a
13
+ * JSON-capable column (pg `jsonb`/`json`, sqlite `text(..., { mode: 'json' })`).
14
+ * - `'text'` serializes to a JSON string for plain text columns.
15
+ *
16
+ * Reads always accept both representations.
17
+ * @default 'json'
18
+ */
19
+ abilitiesMode?: 'json' | 'text';
20
20
  }
21
21
  /**
22
22
  * Database-backed API token store built on the Guren ORM.
@@ -41,39 +41,40 @@ interface DatabaseApiTokenStoreOptions {
41
41
  * ```
42
42
  */
43
43
  declare class DatabaseApiTokenStore implements ApiTokenStore {
44
- private readonly model;
45
- private readonly abilitiesMode;
46
- constructor(table: unknown, options?: DatabaseApiTokenStoreOptions);
47
- store(token: ApiToken): Promise<void>;
48
- findByHashedToken(hashedToken: string): Promise<ApiToken | null>;
49
- findByUserId(userId: string | number): Promise<ApiToken[]>;
50
- delete(id: string): Promise<void>;
51
- deleteForUser(userId: string | number): Promise<void>;
52
- updateLastUsed(id: string, timestamp: Date): Promise<void>;
53
- /**
54
- * Delete tokens whose expiration time has passed. Expired tokens are
55
- * already rejected by `verifyApiToken`; call this from a scheduled
56
- * job to keep the table small.
57
- */
58
- deleteExpired(now?: Date): Promise<void>;
59
- private deserialize;
60
- }
61
-
44
+ private readonly model;
45
+ private readonly abilitiesMode;
46
+ constructor(table: unknown, options?: DatabaseApiTokenStoreOptions);
47
+ store(token: ApiToken): Promise<void>;
48
+ findByHashedToken(hashedToken: string): Promise<ApiToken | null>;
49
+ findByUserId(userId: string | number): Promise<ApiToken[]>;
50
+ delete(id: string): Promise<void>;
51
+ deleteForUser(userId: string | number): Promise<void>;
52
+ updateLastUsed(id: string, timestamp: Date): Promise<void>;
53
+ /**
54
+ * Delete tokens whose expiration time has passed. Expired tokens are
55
+ * already rejected by `verifyApiToken`; call this from a scheduled
56
+ * job to keep the table small.
57
+ */
58
+ deleteExpired(now?: Date): Promise<void>;
59
+ private deserialize;
60
+ }
61
+ //#endregion
62
+ //#region src/session-store.d.ts
62
63
  /**
63
64
  * Options for DatabaseSessionStore.
64
65
  */
65
66
  interface DatabaseSessionStoreOptions {
66
- /**
67
- * How the `data` column stores the serialized session.
68
- *
69
- * - `'json'` (default) passes the object straight through — use with a
70
- * JSON-capable column (pg `jsonb`/`json`, sqlite `text(..., { mode: 'json' })`).
71
- * - `'text'` serializes to a JSON string for plain text columns.
72
- *
73
- * Reads always accept both representations.
74
- * @default 'json'
75
- */
76
- dataMode?: 'json' | 'text';
67
+ /**
68
+ * How the `data` column stores the serialized session.
69
+ *
70
+ * - `'json'` (default) passes the object straight through — use with a
71
+ * JSON-capable column (pg `jsonb`/`json`, sqlite `text(..., { mode: 'json' })`).
72
+ * - `'text'` serializes to a JSON string for plain text columns.
73
+ *
74
+ * Reads always accept both representations.
75
+ * @default 'json'
76
+ */
77
+ dataMode?: 'json' | 'text';
77
78
  }
78
79
  /**
79
80
  * Database-backed session store built on the Guren ORM — works on any
@@ -106,30 +107,31 @@ interface DatabaseSessionStoreOptions {
106
107
  * ```
107
108
  */
108
109
  declare class DatabaseSessionStore implements SessionStore {
109
- private readonly model;
110
- private readonly dataMode;
111
- constructor(table: unknown, options?: DatabaseSessionStoreOptions);
112
- read(id: string): Promise<SessionData | undefined>;
113
- write(id: string, data: SessionData, ttlSeconds: number): Promise<void>;
114
- destroy(id: string): Promise<void>;
115
- /**
116
- * Refresh an existing session's TTL with a single conditional UPDATE — no
117
- * data rewrite, no existence check. Missing rows and rows that have
118
- * already expired (but not yet been swept) are left untouched, never
119
- * resurrected — matching the `SessionStore.touch` contract and the memory
120
- * store's behavior.
121
- */
122
- touch(id: string, ttlSeconds: number): Promise<void>;
123
- /**
124
- * Delete sessions whose expiration time has passed. Expired rows are
125
- * already treated as missing (and removed) by `read`; call this from a
126
- * scheduled job to keep the table small.
127
- */
128
- deleteExpired(now?: Date): Promise<void>;
129
- private deserialize;
130
- private expiryDate;
131
- }
132
-
110
+ private readonly model;
111
+ private readonly dataMode;
112
+ constructor(table: unknown, options?: DatabaseSessionStoreOptions);
113
+ read(id: string): Promise<SessionData | undefined>;
114
+ write(id: string, data: SessionData, ttlSeconds: number): Promise<void>;
115
+ destroy(id: string): Promise<void>;
116
+ /**
117
+ * Refresh an existing session's TTL with a single conditional UPDATE — no
118
+ * data rewrite, no existence check. Missing rows and rows that have
119
+ * already expired (but not yet been swept) are left untouched, never
120
+ * resurrected — matching the `SessionStore.touch` contract and the memory
121
+ * store's behavior.
122
+ */
123
+ touch(id: string, ttlSeconds: number): Promise<void>;
124
+ /**
125
+ * Delete sessions whose expiration time has passed. Expired rows are
126
+ * already treated as missing (and removed) by `read`; call this from a
127
+ * scheduled job to keep the table small.
128
+ */
129
+ deleteExpired(now?: Date): Promise<void>;
130
+ private deserialize;
131
+ private expiryDate;
132
+ }
133
+ //#endregion
134
+ //#region src/oauth-state-store.d.ts
133
135
  /**
134
136
  * Database-backed OAuth state store built on the Guren ORM.
135
137
  *
@@ -168,49 +170,594 @@ declare class DatabaseSessionStore implements SessionStore {
168
170
  * ```
169
171
  */
170
172
  declare class DatabaseOAuthStateStore implements OAuthStateStore {
171
- private readonly model;
172
- constructor(table: unknown);
173
- store(stateHash: string, payload: OAuthStatePayload): Promise<void>;
174
- find(stateHash: string): Promise<OAuthStatePayload | null>;
175
- /**
176
- * Fetch the row for `stateHash`, clearing it out and returning null if
177
- * expired. Shared by `find` and `consume`, which otherwise diverge only
178
- * in what they do with a live row.
179
- */
180
- private fetchLive;
181
- delete(stateHash: string): Promise<void>;
182
- /**
183
- * Atomically fetch and delete a state, guaranteeing exactly one concurrent
184
- * caller for the same hash receives the payload.
185
- *
186
- * This guarantee depends on the configured ORM adapter's `delete()`
187
- * reporting whether a row actually matched — either the deleted row
188
- * (RETURNING) or an affected-row count. `DrizzleAdapter`, the framework's
189
- * default and only shipped adapter, always does this: RETURNING drivers
190
- * (Postgres, SQLite, D1) resolve to the deleted row or `undefined` only
191
- * when zero rows matched; MySQL resolves to a result carrying
192
- * `affectedRows` (verified by inspection, not a dedicated test).
193
- *
194
- * The `ORMAdapter.delete` contract also permits a bare `void` return.
195
- * A custom adapter (via `Model.useAdapter()`) that returns `void`
196
- * unconditionally — on both a successful delete and a no-op — gives
197
- * `consume()` no way to tell which caller won: the value is identical for
198
- * both, so no post-hoc check can attribute the deletion. Rather than
199
- * silently rejecting every real login for such adapters,
200
- * `deleteRemovedRow` treats an unrecognized non-null result as removed —
201
- * this reopens the pre-consume find-then-delete race window (multiple
202
- * concurrent callers can pass) for adapters that can't report a match,
203
- * but does not break login. It is fail-closed (returns null / rejects)
204
- * only for `null`/`undefined`, DrizzleAdapter's definitive "no rows
205
- * matched" signal.
206
- */
207
- consume(stateHash: string): Promise<OAuthStatePayload | null>;
208
- /**
209
- * Delete OAuth states whose expiration time has passed. Expired states
210
- * are already rejected by `find`; call this from a scheduled job to keep
211
- * the table small.
212
- */
213
- deleteExpired(now?: Date): Promise<void>;
214
- }
215
-
216
- export { DatabaseApiTokenStore, type DatabaseApiTokenStoreOptions, DatabaseOAuthStateStore, DatabaseSessionStore, type DatabaseSessionStoreOptions };
173
+ private readonly model;
174
+ constructor(table: unknown);
175
+ store(stateHash: string, payload: OAuthStatePayload): Promise<void>;
176
+ find(stateHash: string): Promise<OAuthStatePayload | null>;
177
+ /**
178
+ * Fetch the row for `stateHash`, clearing it out and returning null if
179
+ * expired. Shared by `find` and `consume`, which otherwise diverge only
180
+ * in what they do with a live row.
181
+ */
182
+ private fetchLive;
183
+ delete(stateHash: string): Promise<void>;
184
+ /**
185
+ * Atomically fetch and delete a state, guaranteeing exactly one concurrent
186
+ * caller for the same hash receives the payload.
187
+ *
188
+ * This guarantee depends on the configured ORM adapter's `delete()`
189
+ * reporting whether a row actually matched — either the deleted row
190
+ * (RETURNING) or an affected-row count. `DrizzleAdapter`, the framework's
191
+ * default and only shipped adapter, always does this: RETURNING drivers
192
+ * (Postgres, SQLite, D1) resolve to the deleted row or `undefined` only
193
+ * when zero rows matched; MySQL resolves to a result carrying
194
+ * `affectedRows` (verified by inspection, not a dedicated test).
195
+ *
196
+ * The `ORMAdapter.delete` contract also permits a bare `void` return.
197
+ * A custom adapter (via `Model.useAdapter()`) that returns `void`
198
+ * unconditionally — on both a successful delete and a no-op — gives
199
+ * `consume()` no way to tell which caller won: the value is identical for
200
+ * both, so no post-hoc check can attribute the deletion. Rather than
201
+ * silently rejecting every real login for such adapters,
202
+ * `deleteRemovedRow` treats an unrecognized non-null result as removed —
203
+ * this reopens the pre-consume find-then-delete race window (multiple
204
+ * concurrent callers can pass) for adapters that can't report a match,
205
+ * but does not break login. It is fail-closed (returns null / rejects)
206
+ * only for `null`/`undefined`, DrizzleAdapter's definitive "no rows
207
+ * matched" signal.
208
+ */
209
+ consume(stateHash: string): Promise<OAuthStatePayload | null>;
210
+ /**
211
+ * Delete OAuth states whose expiration time has passed. Expired states
212
+ * are already rejected by `find`; call this from a scheduled job to keep
213
+ * the table small.
214
+ */
215
+ deleteExpired(now?: Date): Promise<void>;
216
+ }
217
+ //#endregion
218
+ //#region src/attachments/types.d.ts
219
+ /**
220
+ * Public types for the attachments layer (RFC 0013).
221
+ *
222
+ * One table, one service, one processor interface: attachments ride the ORM's
223
+ * polymorphic `attachable` morph convention, bytes live on a `StorageManager`
224
+ * disk, and image work happens behind {@link ImageProcessor}.
225
+ */
226
+ /**
227
+ * A named image variant specification, declared on the model via
228
+ * `hasOneAttached({ variants: { thumb: { width: 320 } } })`.
229
+ *
230
+ * `fit` is limited to what `Bun.Image` actually supports (`'fill'` and
231
+ * `'inside'`); `'cover'` is reserved for a future, non-breaking addition.
232
+ */
233
+ interface VariantSpec {
234
+ width?: number;
235
+ height?: number;
236
+ /**
237
+ * How the image is fitted when both dimensions are given.
238
+ * @default 'inside'
239
+ */
240
+ fit?: 'fill' | 'inside';
241
+ /** Output format. Defaults to the source format. */
242
+ format?: 'jpeg' | 'png' | 'webp' | 'avif';
243
+ /** Encoder quality (1-100) for lossy formats. */
244
+ quality?: number;
245
+ }
246
+ /**
247
+ * Per-variant status entry stored in the attachment row's `variants` JSON
248
+ * column. Every *declared* variant gets an entry at attach time — recording
249
+ * declared names, not just generated ones, is what lets `attachmentUrl()`
250
+ * distinguish "not yet generated" (fall back to the original) from "never
251
+ * declared" (throw) after a reload.
252
+ *
253
+ * - `pending` — generation is queued (`attach(..., { queued: true })`)
254
+ * and a worker has not finished it yet
255
+ * - `ready` — the variant object exists at `path`
256
+ * - `failed` — generation was attempted and failed
257
+ * - `unavailable` — the runtime has no image processor
258
+ */
259
+ interface AttachmentVariantRecord {
260
+ status: 'pending' | 'ready' | 'failed' | 'unavailable';
261
+ /** Object key of the generated variant (status `ready`). */
262
+ path?: string;
263
+ width?: number;
264
+ height?: number;
265
+ format?: 'jpeg' | 'png' | 'webp' | 'avif';
266
+ /** Encoded size in bytes. */
267
+ size?: number;
268
+ }
269
+ /**
270
+ * A row of the `attachments` table, as returned by the attachment statics.
271
+ */
272
+ interface AttachmentRecord {
273
+ /** ULID — sortable, unguessable object-key prefix. */
274
+ id: string;
275
+ /** Model class name (the ORM's `Model.morphMap` convention). */
276
+ attachableType: string;
277
+ /** Owning record's primary key, stored as text (covers int and uuid PKs). */
278
+ attachableId: string;
279
+ /** Collection name declared on the model (`'cover'`, `'images'`, ...). */
280
+ collection: string;
281
+ /** StorageManager disk name the bytes live on. */
282
+ disk: string;
283
+ /** Object key of the original. */
284
+ path: string;
285
+ /** Original client filename (sanitized). */
286
+ name: string;
287
+ contentType: string;
288
+ /** Size of the stored original in bytes. */
289
+ size: number;
290
+ /** Pixel width — `null` for non-images and undecoded uploads. */
291
+ width: number | null;
292
+ height: number | null;
293
+ /** Per-declared-variant status records, `null` when none were declared. */
294
+ variants: Record<string, AttachmentVariantRecord> | null;
295
+ /** ThumbHash LQIP data URL — images only, `null` without a processor. */
296
+ placeholder: string | null;
297
+ createdAt: Date;
298
+ updatedAt: Date;
299
+ }
300
+ /**
301
+ * The resource-facing shape returned by `withAttachments()`, ready for
302
+ * `JsonResource.toArray()` so pages can carry typed attachment props.
303
+ *
304
+ * `variants` has an entry for every *declared* variant name; a variant that
305
+ * is not `ready` yet falls back to the original's URL, so pages keep
306
+ * rendering (the `placeholder` LQIP covers the perceived-latency gap).
307
+ */
308
+ interface AttachmentData {
309
+ id: string;
310
+ collection: string;
311
+ name: string;
312
+ contentType: string;
313
+ size: number;
314
+ width: number | null;
315
+ height: number | null;
316
+ url: string;
317
+ placeholder: string | null;
318
+ variants: Record<string, {
319
+ url: string;
320
+ width: number | null;
321
+ height: number | null;
322
+ }>;
323
+ }
324
+ /**
325
+ * Image processing behind the attachments pipeline.
326
+ *
327
+ * The default implementation wraps `Bun.Image` and is resolved only when the
328
+ * runtime has it; apps on other runtimes may inject their own (e.g. a
329
+ * sharp-backed one) via `configureAttachments({ processor })`.
330
+ *
331
+ * Implementations signal an OS-level codec gap by throwing an error whose
332
+ * `code` is `'ERR_IMAGE_FORMAT_UNSUPPORTED'` — format support is a runtime
333
+ * property (OS codecs), never a static table, so that error code is the only
334
+ * authority the pipeline branches on.
335
+ */
336
+ interface ImageProcessor {
337
+ /**
338
+ * Full decode: validates the bytes, enforces `maxPixels`, reports
339
+ * dimensions. Header sniffing is *not* validation — truncated files pass
340
+ * it — so implementations must decode pixels before resolving.
341
+ */
342
+ probe(input: Uint8Array, limits: {
343
+ maxPixels: number;
344
+ }): Promise<{
345
+ width: number;
346
+ height: number;
347
+ format: string;
348
+ placeholder?: string;
349
+ }>;
350
+ /** Generate one variant: resize per the spec and encode. */
351
+ process(input: Uint8Array, spec: VariantSpec): Promise<{
352
+ bytes: Uint8Array;
353
+ width: number;
354
+ height: number;
355
+ format: string;
356
+ }>;
357
+ }
358
+ /**
359
+ * What an attachment collection accepts as image input.
360
+ *
361
+ * - unset — opaque bytes: no image pipeline at all, `width`/`height`/
362
+ * `placeholder` stay `null` (a `draftPdf` collection)
363
+ * - `'allow'` — images are decoded and measured when recognized; anything
364
+ * else is stored as opaque bytes
365
+ * - `'require'`— input must be a decodable image; non-images are rejected
366
+ * with a 422 `ValidationException`
367
+ * - `'forbid'` — inputs that sniff as images are rejected with 422
368
+ */
369
+ type ImagePolicy = 'forbid' | 'allow' | 'require';
370
+ /**
371
+ * The bytes-only attach input. Filesystem path strings are deliberately not
372
+ * accepted anywhere in this API: `Bun.Image`'s path form is an
373
+ * arbitrary-file-read primitive if a user-influenced string ever reaches it,
374
+ * so the pipeline never exposes the shape at all.
375
+ */
376
+ type AttachmentSource = File | Blob | Uint8Array;
377
+ //#endregion
378
+ //#region src/attachments/declaration.d.ts
379
+ /**
380
+ * How HEIC/HEIF input is handled. The default is `'reject'` (415): HEIC
381
+ * decoding depends on OS codecs — it works on macOS dev machines and fails
382
+ * on Linux production — and the default must not let that skew pass
383
+ * silently. `'convert'` opts in: the service attempts decode-and-convert to
384
+ * JPEG and still answers 415 when the runtime cannot decode HEIC
385
+ * (`ERR_IMAGE_FORMAT_UNSUPPORTED`).
386
+ */
387
+ type HeicPolicy = 'reject' | 'convert';
388
+ interface AttachedCollectionOptions<V extends string = never> {
389
+ /**
390
+ * Image handling for this collection. Defaults to `'require'` when
391
+ * `variants` are declared (variant generation needs a decodable image)
392
+ * and to opaque-bytes handling otherwise.
393
+ */
394
+ image?: ImagePolicy;
395
+ accepts?: {
396
+ heic?: HeicPolicy;
397
+ };
398
+ /** Named variants, generated at attach time (or recorded as unavailable). */
399
+ variants?: Record<V, VariantSpec>;
400
+ }
401
+ /**
402
+ * One collection's declaration as stored on the model's
403
+ * `static attachments`. Produced by {@link hasOneAttached} /
404
+ * {@link hasManyAttached}; the generics carry the collection kind and the
405
+ * declared variant names into the mixin's compile-time checks.
406
+ */
407
+ interface AttachmentCollectionSpec<TKind extends 'one' | 'many' = 'one' | 'many', V extends string = string> {
408
+ kind: TKind;
409
+ image?: ImagePolicy;
410
+ accepts?: {
411
+ heic?: HeicPolicy;
412
+ };
413
+ variants?: Record<V, VariantSpec>;
414
+ }
415
+ /** The declaration object passed into `Attachable(Base, declaration)`. */
416
+ type AttachmentsDeclaration = Record<string, AttachmentCollectionSpec<'one' | 'many', string>>;
417
+ /**
418
+ * Declare a single-attachment collection (`attach` replaces the previous
419
+ * attachment, purging its row and objects).
420
+ *
421
+ * @example
422
+ * export class Post extends Attachable(defineModel(posts), {
423
+ * cover: hasOneAttached({
424
+ * image: 'require',
425
+ * variants: { thumb: { width: 320 }, og: { width: 1200 } },
426
+ * }),
427
+ * draftPdf: hasOneAttached(), // opaque bytes; width/height/placeholder null
428
+ * }) {}
429
+ */
430
+ declare function hasOneAttached<const V extends string = never>(options?: AttachedCollectionOptions<V>): AttachmentCollectionSpec<'one', V>;
431
+ /**
432
+ * Declare a multi-attachment collection (`attach` appends).
433
+ *
434
+ * @example
435
+ * export class Post extends Attachable(defineModel(posts), {
436
+ * images: hasManyAttached({ image: 'require' }),
437
+ * }) {}
438
+ */
439
+ declare function hasManyAttached<const V extends string = never>(options?: AttachedCollectionOptions<V>): AttachmentCollectionSpec<'many', V>;
440
+ //#endregion
441
+ //#region src/attachments/engine.d.ts
442
+ interface AttachOptions {
443
+ /** Filename to store (defaults to the `File`'s own name). */
444
+ name?: string;
445
+ /** Disk to store on, overriding the configured default. */
446
+ disk?: string;
447
+ /**
448
+ * Defer the full decode and variant generation to the queue: the request
449
+ * path runs only the synchronous gates (byte cap, header dimensions, HEIC
450
+ * signature), stores the original, seeds declared variants as `pending`,
451
+ * and dispatches `GenerateVariantsJob`. Until the worker runs, variant
452
+ * URLs fall back to the original. Requires a queue — either
453
+ * `configureAttachments({ queue })` or an already-booted QueueManager.
454
+ */
455
+ queued?: boolean;
456
+ }
457
+ interface ConfigureAttachmentsOptions {
458
+ /**
459
+ * The app's Drizzle `attachments` table (the app owns the table; the
460
+ * framework ships the schema snippet — see the attachments guide).
461
+ * Column property names must match the documented contract: `id`,
462
+ * `attachableType`, `attachableId`, `collection`, `disk`, `path`, `name`,
463
+ * `contentType`, `size`, `width`, `height`, `variants` (JSON-capable),
464
+ * `placeholder`, `createdAt`, `updatedAt`.
465
+ */
466
+ table: unknown;
467
+ /** The app's StorageManager, resolved lazily (e.g. `() => container.make('storage')`). */
468
+ storage: () => StorageManager;
469
+ /** Default disk name for new attachments. */
470
+ disk: string;
471
+ /**
472
+ * Per-disk visibility: `'public'` disks serve via `disk.url()`, `'private'`
473
+ * ones via `disk.temporaryUrl()`. Per disk, not per attachment, because at
474
+ * least one driver (R2) has no per-object visibility. Undeclared disks
475
+ * default to `'public'`.
476
+ */
477
+ disks?: Record<string, 'public' | 'private'>;
478
+ /**
479
+ * Decode cap in pixels (decompression-bomb defense). Header-declared and
480
+ * decoded dimensions above this are rejected before a pixel buffer is
481
+ * allocated. No "unlimited" setting exists; photography/archival apps
482
+ * raise it deliberately and should isolate their image workers.
483
+ * @default 52_000_000
484
+ */
485
+ maxPixels?: number;
486
+ /**
487
+ * Encoded-input cap in bytes, checked before any decode. Pixel count and
488
+ * upload size defend against different attacks; this is the cheapest gate.
489
+ * @default 50_000_000
490
+ */
491
+ maxImageBytes?: number;
492
+ /**
493
+ * Image processor override. Defaults to the Bun-native processor when the
494
+ * runtime has `Bun.Image`; pass `null` to force the processor-less path
495
+ * (variants recorded as `unavailable`, validation stops at the header
496
+ * gates) or your own implementation (e.g. sharp-backed) on other runtimes.
497
+ */
498
+ processor?: ImageProcessor | null;
499
+ /**
500
+ * The app's QueueManager, resolved lazily (e.g.
501
+ * `() => container.make('queue')`). Enables `attach(..., { queued: true })`:
502
+ * the engine materializes the manager's default driver and dispatches
503
+ * `GenerateVariantsJob` on it. Materializing the default driver installs
504
+ * it as the process-wide dispatch target (`QueueManager` semantics), so
505
+ * pass the same manager the rest of the app dispatches through — a
506
+ * second manager here would redirect every later `Job.dispatch()` in the
507
+ * process. Without this option, `queued: true` falls back to the
508
+ * globally configured queue driver and throws a clear error when there
509
+ * is none.
510
+ */
511
+ queue?: () => unknown;
512
+ /**
513
+ * How long `temporaryUrl()` links for private disks stay valid, in
514
+ * milliseconds.
515
+ * @default 300_000 (5 minutes)
516
+ */
517
+ urlExpiresIn?: number;
518
+ }
519
+ /**
520
+ * What `GenerateVariantsJob` needs to finish a deferred attach. The specs
521
+ * are snapshotted at dispatch time (they come from the model declaration,
522
+ * never the call site), so an in-flight job is unaffected by later
523
+ * declaration edits and the worker needs no model registry to resolve them.
524
+ */
525
+ interface GenerateVariantsPayload {
526
+ attachmentId: string;
527
+ image?: ImagePolicy;
528
+ heic?: HeicPolicy;
529
+ variants?: Record<string, VariantSpec>;
530
+ }
531
+ interface PruneOptions {
532
+ /** Also delete `attachments/` storage prefixes that no row references. */
533
+ objects?: boolean;
534
+ /** Report what would be removed without deleting anything. */
535
+ dryRun?: boolean;
536
+ }
537
+ interface PruneReport {
538
+ /** Rows examined. */
539
+ scannedRows: number;
540
+ /** Rows whose owning record no longer exists (deleted unless dry-run). */
541
+ orphanRows: Array<{
542
+ id: string;
543
+ attachableType: string;
544
+ attachableId: string;
545
+ }>;
546
+ /**
547
+ * Morph types that could not be verified and were left untouched: types
548
+ * missing from `Model.morphMap`, or whose existence query failed. A type
549
+ * that cannot be checked is never treated as absent — that would turn an
550
+ * outage into a mass deletion.
551
+ */
552
+ skippedTypes: Array<{
553
+ type: string;
554
+ reason: string;
555
+ }>;
556
+ /** Per disk, storage prefixes under `attachments/` with no row (with `objects`). */
557
+ orphanObjectPrefixes: Array<{
558
+ disk: string;
559
+ prefix: string;
560
+ }>;
561
+ /** Disks that could not be listed and were left untouched (with `objects`). */
562
+ skippedDisks: Array<{
563
+ disk: string;
564
+ reason: string;
565
+ }>;
566
+ }
567
+ //#endregion
568
+ //#region src/attachments/Attachable.d.ts
569
+ /** A record id accepted by the attachment statics (int and uuid/text PKs). */
570
+ type AttachableRecordId = string | number;
571
+ /**
572
+ * The loosest shape a declaration member must have. Deliberately minimal:
573
+ * a tighter bound (the full `AttachmentCollectionSpec`) would become the
574
+ * contextual type of the `hasOneAttached()` / `hasManyAttached()` calls and
575
+ * make TypeScript infer their variant-name parameter as `string` instead of
576
+ * the declared keys — silently disabling every variant-name check.
577
+ */
578
+ type DeclarationShape = Record<string, {
579
+ kind: 'one' | 'many';
580
+ }>;
581
+ /** The variant names declared on one collection spec. */
582
+ type VariantNamesOf<TSpec> = TSpec extends {
583
+ variants?: infer TVariants;
584
+ } ? keyof NonNullable<TVariants> & string : never;
585
+ /** `hasOne` loads as nullable-single, `hasMany` as an array. */
586
+ type AttachedProps<TDecl, K extends keyof TDecl> = { [P in K]: TDecl[P] extends {
587
+ kind: 'many';
588
+ } ? AttachmentData[] : AttachmentData | null; };
589
+ /** `detach` takes an attachment id only on a `hasMany` collection. */
590
+ type DetachRest<TSpec> = TSpec extends {
591
+ kind: 'many';
592
+ } ? [attachmentId?: string] : [];
593
+ /**
594
+ * Rejects declaration keys that shadow a real column of the base model's
595
+ * table (the attachment would hide the column at `withAttachments` time).
596
+ * A base whose record type is untyped (`keyof` collapses to `string`) is
597
+ * exempt — there is nothing concrete to check against.
598
+ */
599
+ type CollisionFreeDeclaration<TBase extends typeof Model$1, TDecl> = string extends keyof TBase['recordType'] & string ? unknown : { [K in Extract<keyof TDecl, keyof TBase['recordType']>]: never; };
600
+ /**
601
+ * The statics the `Attachable` mixin adds. All of them delegate to the
602
+ * engine wired by `configureAttachments()`; every collection argument is
603
+ * `keyof` the declaration, so typos, wrong kinds, and undeclared variant
604
+ * names are compile errors.
605
+ */
606
+ interface AttachableStatic<TBase extends typeof Model$1, TDecl extends DeclarationShape> {
607
+ /** The declaration, statically readable (this is what `guren check` and codegen read). */
608
+ readonly attachments: TDecl;
609
+ /**
610
+ * Store bytes as an attachment on `collection`. `source` is bytes only
611
+ * (`File | Blob | Uint8Array`) — path strings are never accepted. On a
612
+ * `hasOne` collection the previous attachment is replaced (row and
613
+ * objects purged); on `hasMany` the new one is appended. Validation and
614
+ * variant specs come from the declaration, not the call site.
615
+ */
616
+ attach<K extends keyof TDecl & string>(recordId: AttachableRecordId, collection: K, source: AttachmentSource, options?: AttachOptions): Promise<AttachmentRecord>;
617
+ /**
618
+ * Remove attachment rows and their stored objects. On a `hasMany`
619
+ * collection an `attachmentId` narrows it to one attachment; omitted, the
620
+ * whole collection is detached.
621
+ */
622
+ detach<K extends keyof TDecl & string>(recordId: AttachableRecordId, collection: K, ...attachmentId: DetachRest<TDecl[NoInfer<K>]>): Promise<void>;
623
+ /**
624
+ * Batch-load attachments for a page of records (one indexed query per
625
+ * call), attaching each requested collection as a typed property:
626
+ * `hasOne` → `AttachmentData | null`, `hasMany` → `AttachmentData[]`.
627
+ */
628
+ withAttachments<TRecord extends {
629
+ id: string | number;
630
+ }, K extends keyof TDecl & string>(records: readonly TRecord[], names: readonly K[]): Promise<Array<TRecord & AttachedProps<TDecl, K>>>;
631
+ /**
632
+ * URL for a collection's attachment: `disk.url()` on public disks,
633
+ * `disk.temporaryUrl()` on private ones. A declared-but-not-ready variant
634
+ * falls back to the original's URL; a variant name that was never
635
+ * declared throws. Returns `null` when nothing is attached.
636
+ */
637
+ attachmentUrl<K extends keyof TDecl & string>(record: PlainObject$1 | AttachableRecordId, collection: K, options?: {
638
+ variant?: VariantNamesOf<TDecl[NoInfer<K>]>;
639
+ }): Promise<string | null>;
640
+ /**
641
+ * Remove every attachment of a record (all collections), objects first,
642
+ * rows after. Call it from destroy actions — model delete hooks are not a
643
+ * reliable purge trigger, so the contract is explicit-plus-sweep.
644
+ */
645
+ purgeAttachments(recordId: AttachableRecordId): Promise<void>;
646
+ }
647
+ /**
648
+ * Mixin that declares attachment collections on a model (RFC 0013). The
649
+ * declaration is a static argument in the class heritage clause, so it is
650
+ * statically readable (the same property `guren check` and `guren context`
651
+ * rely on for the model's other surfaces), and its collection names, kinds,
652
+ * and variant names are inferred as compile-time facts.
653
+ *
654
+ * Composes with other mixins the way `SoftDeletes` does.
655
+ *
656
+ * @example
657
+ * import { Attachable, hasOneAttached, hasManyAttached } from '@guren/core'
658
+ *
659
+ * export class Post extends Attachable(defineModel(posts), {
660
+ * cover: hasOneAttached({
661
+ * image: 'require',
662
+ * variants: { thumb: { width: 320 }, og: { width: 1200 } },
663
+ * }),
664
+ * images: hasManyAttached({ image: 'require' }),
665
+ * draftPdf: hasOneAttached(),
666
+ * }) {}
667
+ *
668
+ * // Later, anywhere:
669
+ * await Post.attach(post.id, 'cover', await this.file('cover'))
670
+ * const [withCover] = await Post.withAttachments([post], ['cover'])
671
+ * const url = await Post.attachmentUrl(post, 'cover', { variant: 'thumb' })
672
+ */
673
+ declare function Attachable<TBase extends typeof Model$1, const TDecl extends DeclarationShape>(Base: TBase, declaration: TDecl & CollisionFreeDeclaration<TBase, TDecl>): TBase & AttachableStatic<TBase, TDecl>;
674
+ //#endregion
675
+ //#region src/attachments/configure.d.ts
676
+ interface ConfiguredAttachments {
677
+ /**
678
+ * A ready-made model bound to the app's `attachments` table, with
679
+ * `morphTo('attachable', 'attachable')` pre-declared — for morph relations
680
+ * (`Post.morphMany('attachments', Attachment, 'attachable')`) and advanced
681
+ * queries. The app-local name lives in app namespace; the framework itself
682
+ * exports no bare `Attachment` (it would collide with the mail /
683
+ * notification / Slack attachment vocabulary).
684
+ */
685
+ Attachment: typeof Model$1;
686
+ }
687
+ /**
688
+ * Wire the attachments layer, once per app (the `DatabaseSessionStore`
689
+ * precedent: the app owns the table, the framework returns the model).
690
+ * The attachment statics on `Attachable` models resolve this configuration
691
+ * lazily and throw a clear error when it was never called.
692
+ *
693
+ * @example
694
+ * ```ts
695
+ * // config/attachments.ts
696
+ * import { configureAttachments } from '@guren/core'
697
+ * import { attachments } from '@/db/schema'
698
+ *
699
+ * export const { Attachment } = configureAttachments({
700
+ * table: attachments,
701
+ * storage: () => container.make('storage'),
702
+ * disk: 'media',
703
+ * })
704
+ * ```
705
+ */
706
+ declare function configureAttachments(options: ConfigureAttachmentsOptions): ConfiguredAttachments;
707
+ //#endregion
708
+ //#region src/attachments/prune-command.d.ts
709
+ /**
710
+ * Console sweeper for the attachments layer (RFC 0013 §8). The polymorphic
711
+ * `attachableType`/`attachableId` pair cannot carry a foreign key, so no
712
+ * database cascade exists; deletion is explicit (`purgeAttachments()` in
713
+ * destroy actions) plus this sweep for whatever slipped past it — records
714
+ * deleted through paths that never purged, and, with `--objects`, storage
715
+ * prefixes left behind by crashed or raced jobs.
716
+ *
717
+ * Register it in the app's console kernel:
718
+ *
719
+ * ```ts
720
+ * // src/console.ts
721
+ * import { AttachmentsPruneCommand } from '@guren/core'
722
+ * kernel.register(AttachmentsPruneCommand)
723
+ * ```
724
+ *
725
+ * Orphan rows are detected by resolving each `attachableType` through
726
+ * `Model.morphMap` and querying for the records — set
727
+ * `Model.morphMap = { Post, User, ... }` for every model that declares
728
+ * attachments, or their rows are reported as unverifiable and left alone.
729
+ */
730
+ declare class AttachmentsPruneCommand extends Command {
731
+ static signature: string;
732
+ static description: string;
733
+ handle(): Promise<void>;
734
+ }
735
+ //#endregion
736
+ //#region src/attachments/generate-variants-job.d.ts
737
+ /**
738
+ * Queue job behind `attach(..., { queued: true })` (RFC 0013 Part 2): runs
739
+ * the deferred full decode, converts HEIC originals where the collection
740
+ * opted in, and generates the declared variants, flipping their `pending`
741
+ * status records to `ready`/`failed`.
742
+ *
743
+ * `configureAttachments()` registers this job, so any worker process that
744
+ * boots the app's config can process it. The worker is where the image
745
+ * work happens — point it at a runtime with an image processor (Bun with
746
+ * `Bun.Image`, or a custom `configureAttachments({ processor })`), or every
747
+ * variant settles as `unavailable`.
748
+ */
749
+ declare class GenerateVariantsJob extends Job<GenerateVariantsPayload> {
750
+ /**
751
+ * Pinned wire name: queued messages must survive bundler identifier
752
+ * mangling and any future rename of this class.
753
+ */
754
+ static jobName: string;
755
+ handle(payload: GenerateVariantsPayload): Promise<void>;
756
+ /**
757
+ * After the last retry, stop `pending` variants from looking in-flight
758
+ * forever — their URLs already fall back to the original either way.
759
+ */
760
+ failed(payload: GenerateVariantsPayload, _error: Error): Promise<void>;
761
+ }
762
+ //#endregion
763
+ export { type AccessorDefinitions, type AccessorFn, type AttachOptions, Attachable, type AttachableRecordId, type AttachableStatic, type AttachedCollectionOptions, type AttachmentCollectionSpec, type AttachmentData, type AttachmentRecord, type AttachmentSource, type AttachmentVariantRecord, type AttachmentsDeclaration, AttachmentsPruneCommand, type AwsDataApiDatabase, type AwsDataApiDatabaseOptions, type AwsDataApiSeederContext, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type BelongsToRequiredRecord, type CastType, type ConfigureAttachmentsOptions, type ConfiguredAttachments, type D1DatabaseHandle, type D1DatabaseOptions, DatabaseApiTokenStore, type DatabaseApiTokenStoreOptions, DatabaseOAuthStateStore, DatabaseSessionStore, type DatabaseSessionStoreOptions, DrizzleAdapter, type EagerLoadConstraint, type FindManyOptions, GenerateVariantsJob, type GenerateVariantsPayload, type GroupCondition, type HasManyRecord, type HasManyRelationResult, type HasManyThroughRecord, type HasManyThroughRelationResult, type HasOneRecord, type HasOneRelationResult, type HeicPolicy, type HookCallback, type HookName, type ImagePolicy, type ImageProcessor, type InferModelInsert, type InferModelRecord, MassAssignmentException, type MigrationRunSummary, type MigrationStatusEntry, Model, type ModelHooks, ModelNotFoundException, type ModelObserver, type ModelObserverConstructor, type ModelPaginationMeta, type ModelQueryOptions, type MorphManyRecord, type MorphManyRelationResult, type MorphToRecord, type MorphToRelationResult, type MutatorDefinitions, type MutatorFn, type MySqlDatabase, type MySqlDatabaseOptions, type MySqlSeederContext, type ORMAdapter, type ORMAdapterAdvanced, type OrderByClause, type OrderByInput, type OrderDefinition, type OrderDirection, type PaginateOptions, type PaginatedResult, type PlainObject, type PostgresDatabase, type PostgresDatabaseOptions, type PostgresSeederContext, type PruneOptions, type PruneReport, QueryBuilder, type QueryBuilderOptions, type ScopeFunction, type SeederContext, type SeederHandler, type SeederRunSummary, type SimpleCondition, SoftDeletes, type SoftDeletesStatic, type SqliteDatabase, type SqliteDatabaseOptions, type SqliteSeederContext, type TransactionHandle, type TransactionModelScope, type VariantSpec, type WhereClause, type WhereCondition, type WhereGroupCallback, type WhereOperator, type WithRelations, configureAttachments, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, hasManyAttached, hasOneAttached, runSeeders };