@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.js CHANGED
@@ -1,300 +1,1578 @@
1
- // src/index.ts
2
- export * from "@guren/server";
3
- import {
4
- Model as Model4,
5
- defineModel,
6
- ModelNotFoundException,
7
- MassAssignmentException,
8
- QueryBuilder,
9
- SoftDeletes,
10
- DrizzleAdapter,
11
- createPostgresDatabase,
12
- createMySqlDatabase,
13
- createSqliteDatabase,
14
- createD1Database,
15
- createAwsDataApiDatabase,
16
- runSeeders,
17
- defineSeeder
18
- } from "@guren/orm";
19
-
20
- // src/api-token-store.ts
21
- import { Model } from "@guren/orm";
22
-
23
- // src/store-utils.ts
1
+ import { Command, HttpException, Job, ValidationException, getQueueDriver, registerJob, setQueueDriver } from "@guren/server";
2
+ import { DrizzleAdapter, MassAssignmentException, Model, Model as Model$1, ModelNotFoundException, QueryBuilder, SoftDeletes, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, runSeeders } from "@guren/orm";
24
3
  import { isExpired, toDate, toOptionalExpiry } from "@guren/server/support/expiry";
4
+ export * from "@guren/server";
5
+ //#region src/store-utils.ts
6
+ /**
7
+ * Decode a JSON-capable column that may hold either the native value
8
+ * (drizzle json mode) or a text-encoded string. Corrupt text falls back
9
+ * instead of throwing, so one bad row cannot break every read.
10
+ *
11
+ * Stays here: it is a drizzle column concern, and the Redis stores decode
12
+ * their own JSON payloads through `redis-values.ts` instead.
13
+ */
25
14
  function decodeJsonColumn(value, fallback) {
26
- if (typeof value === "string") {
27
- try {
28
- return JSON.parse(value);
29
- } catch {
30
- return fallback;
31
- }
32
- }
33
- return value ?? fallback;
34
- }
35
-
36
- // src/api-token-store.ts
15
+ if (typeof value === "string") try {
16
+ return JSON.parse(value);
17
+ } catch {
18
+ return fallback;
19
+ }
20
+ return value ?? fallback;
21
+ }
22
+ //#endregion
23
+ //#region src/api-token-store.ts
24
+ /**
25
+ * Database-backed API token store built on the Guren ORM.
26
+ *
27
+ * Pass the Drizzle table for your `api_tokens` schema. Column property
28
+ * names must match the {@link ApiToken} fields (`id`, `name`,
29
+ * `hashedToken`, `userId`, `abilities`, `lastUsedAt`, `expiresAt`,
30
+ * `createdAt`). The ORM must be configured (the standard
31
+ * `DatabaseProvider` setup) before the store is used.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * import { DatabaseApiTokenStore, createApiToken } from '@guren/core'
36
+ * import { apiTokens } from '@/db/schema'
37
+ *
38
+ * const store = new DatabaseApiTokenStore(apiTokens)
39
+ *
40
+ * const { plainTextToken } = await createApiToken(store, {
41
+ * name: 'Mobile App Token',
42
+ * userId: user.id,
43
+ * })
44
+ * ```
45
+ */
37
46
  var DatabaseApiTokenStore = class {
38
- model;
39
- abilitiesMode;
40
- constructor(table, options = {}) {
41
- this.abilitiesMode = options.abilitiesMode ?? "json";
42
- this.model = class ApiTokenModel extends Model {
43
- static table = table;
44
- };
45
- }
46
- async store(token) {
47
- await this.model.forceCreate({
48
- ...token,
49
- abilities: this.abilitiesMode === "text" ? JSON.stringify(token.abilities) : token.abilities
50
- });
51
- }
52
- async findByHashedToken(hashedToken) {
53
- const record = await this.model.where({ hashedToken }).first();
54
- return record ? this.deserialize(record) : null;
55
- }
56
- async findByUserId(userId) {
57
- const records = await this.model.where({ userId }).get();
58
- return records.map((record) => this.deserialize(record));
59
- }
60
- async delete(id) {
61
- await this.model.where({ id }).delete();
62
- }
63
- async deleteForUser(userId) {
64
- await this.model.where({ userId }).delete();
65
- }
66
- async updateLastUsed(id, timestamp) {
67
- await this.model.forceUpdate({ id }, { lastUsedAt: timestamp });
68
- }
69
- /**
70
- * Delete tokens whose expiration time has passed. Expired tokens are
71
- * already rejected by `verifyApiToken`; call this from a scheduled
72
- * job to keep the table small.
73
- */
74
- async deleteExpired(now = /* @__PURE__ */ new Date()) {
75
- await this.model.where("expiresAt", "<", now).delete();
76
- }
77
- // Not replaceable with `static casts`: QueryBuilder reads (`where().first()/.get()`)
78
- // bypass model casts, and cast-based writes would fight drizzle column modes
79
- // (Date → ISO string breaks timestamp columns; json-stringify double-encodes jsonb).
80
- deserialize(record) {
81
- const abilities = decodeJsonColumn(record.abilities, []);
82
- return {
83
- id: String(record.id),
84
- name: String(record.name),
85
- hashedToken: String(record.hashedToken),
86
- userId: typeof record.userId === "bigint" ? record.userId.toString() : record.userId,
87
- // Corrupt text degrades to no abilities (deny-by-default) instead of
88
- // throwing on every verification of the affected token. A value that
89
- // decodes to something other than a list of strings degrades the same
90
- // way: `tokenCan` would otherwise run `String.prototype.includes` on it,
91
- // so a stored `'"*"'` would grant every ability.
92
- abilities: Array.isArray(abilities) ? abilities.filter((ability) => typeof ability === "string") : [],
93
- lastUsedAt: toDate(record.lastUsedAt),
94
- // Null means "never expires"; a present-but-unparseable value means a
95
- // malformed row, which must not read as immortal (`verifyApiToken`
96
- // skips its expiry check entirely when this is null).
97
- expiresAt: toOptionalExpiry(record.expiresAt),
98
- createdAt: toDate(record.createdAt) ?? /* @__PURE__ */ new Date(0)
99
- };
100
- }
47
+ model;
48
+ abilitiesMode;
49
+ constructor(table, options = {}) {
50
+ this.abilitiesMode = options.abilitiesMode ?? "json";
51
+ this.model = class ApiTokenModel extends Model$1 {
52
+ static table = table;
53
+ };
54
+ }
55
+ async store(token) {
56
+ await this.model.forceCreate({
57
+ ...token,
58
+ abilities: this.abilitiesMode === "text" ? JSON.stringify(token.abilities) : token.abilities
59
+ });
60
+ }
61
+ async findByHashedToken(hashedToken) {
62
+ const record = await this.model.where({ hashedToken }).first();
63
+ return record ? this.deserialize(record) : null;
64
+ }
65
+ async findByUserId(userId) {
66
+ return (await this.model.where({ userId }).get()).map((record) => this.deserialize(record));
67
+ }
68
+ async delete(id) {
69
+ await this.model.where({ id }).delete();
70
+ }
71
+ async deleteForUser(userId) {
72
+ await this.model.where({ userId }).delete();
73
+ }
74
+ async updateLastUsed(id, timestamp) {
75
+ await this.model.forceUpdate({ id }, { lastUsedAt: timestamp });
76
+ }
77
+ /**
78
+ * Delete tokens whose expiration time has passed. Expired tokens are
79
+ * already rejected by `verifyApiToken`; call this from a scheduled
80
+ * job to keep the table small.
81
+ */
82
+ async deleteExpired(now = /* @__PURE__ */ new Date()) {
83
+ await this.model.where("expiresAt", "<", now).delete();
84
+ }
85
+ deserialize(record) {
86
+ const abilities = decodeJsonColumn(record.abilities, []);
87
+ return {
88
+ id: String(record.id),
89
+ name: String(record.name),
90
+ hashedToken: String(record.hashedToken),
91
+ userId: typeof record.userId === "bigint" ? record.userId.toString() : record.userId,
92
+ abilities: Array.isArray(abilities) ? abilities.filter((ability) => typeof ability === "string") : [],
93
+ lastUsedAt: toDate(record.lastUsedAt),
94
+ expiresAt: toOptionalExpiry(record.expiresAt),
95
+ createdAt: toDate(record.createdAt) ?? /* @__PURE__ */ new Date(0)
96
+ };
97
+ }
101
98
  };
102
-
103
- // src/session-store.ts
104
- import { Model as Model2 } from "@guren/orm";
99
+ //#endregion
100
+ //#region src/session-store.ts
101
+ /**
102
+ * Database-backed session store built on the Guren ORM — works on any
103
+ * configured connection (SQLite, Postgres, MySQL, or Cloudflare D1), which
104
+ * makes it the serverless default: no Redis required on Lambda, Vercel, or
105
+ * Workers, and reads are strongly consistent (login → redirect → read works).
106
+ *
107
+ * Pass the Drizzle table for your `sessions` schema. Column property names
108
+ * must match `id` (text primary key), `data`, and `expiresAt`:
109
+ *
110
+ * ```ts
111
+ * export const sessions = sqliteTable('sessions', {
112
+ * id: text('id').primaryKey(),
113
+ * data: text('data', { mode: 'json' }).$type<Record<string, unknown>>().notNull(),
114
+ * expiresAt: integer('expires_at', { mode: 'timestamp_ms' }).notNull(),
115
+ * })
116
+ * ```
117
+ *
118
+ * Session values must be JSON-serializable: Dates come back as ISO strings,
119
+ * `undefined` properties are dropped, and `bigint` values fail to serialize —
120
+ * unlike `MemorySessionStore`, which keeps live references. Store primitives
121
+ * and plain objects/arrays in sessions.
122
+ *
123
+ * @example
124
+ * ```ts
125
+ * import { DatabaseSessionStore } from '@guren/core'
126
+ * import { sessions } from '@/db/schema'
127
+ *
128
+ * app.use(createSessionMiddleware({ store: new DatabaseSessionStore(sessions) }))
129
+ * ```
130
+ */
105
131
  var DatabaseSessionStore = class {
106
- model;
107
- dataMode;
108
- constructor(table, options = {}) {
109
- this.dataMode = options.dataMode ?? "json";
110
- this.model = class SessionModel extends Model2 {
111
- static table = table;
112
- };
113
- }
114
- async read(id) {
115
- const record = await this.model.where({ id }).first();
116
- if (!record) {
117
- return void 0;
118
- }
119
- if (isExpired(record.expiresAt)) {
120
- await this.model.where({ id, expiresAt: record.expiresAt }).delete();
121
- return void 0;
122
- }
123
- return this.deserialize(record);
124
- }
125
- async write(id, data, ttlSeconds) {
126
- const payload = {
127
- data: this.dataMode === "text" ? JSON.stringify(data) : data,
128
- expiresAt: this.expiryDate(ttlSeconds)
129
- };
130
- const existing = await this.model.where({ id }).first();
131
- if (existing) {
132
- await this.model.forceUpdate({ id }, payload);
133
- return;
134
- }
135
- try {
136
- await this.model.forceCreate({ id, ...payload });
137
- } catch (error) {
138
- const nowExists = await this.model.where({ id }).first();
139
- if (!nowExists) {
140
- throw error;
141
- }
142
- await this.model.forceUpdate({ id }, payload);
143
- }
144
- }
145
- async destroy(id) {
146
- await this.model.where({ id }).delete();
147
- }
148
- /**
149
- * Refresh an existing session's TTL with a single conditional UPDATE — no
150
- * data rewrite, no existence check. Missing rows and rows that have
151
- * already expired (but not yet been swept) are left untouched, never
152
- * resurrected — matching the `SessionStore.touch` contract and the memory
153
- * store's behavior.
154
- */
155
- async touch(id, ttlSeconds) {
156
- await this.model.where({ id }).where("expiresAt", ">", /* @__PURE__ */ new Date()).forceUpdate({ expiresAt: this.expiryDate(ttlSeconds) });
157
- }
158
- /**
159
- * Delete sessions whose expiration time has passed. Expired rows are
160
- * already treated as missing (and removed) by `read`; call this from a
161
- * scheduled job to keep the table small.
162
- */
163
- async deleteExpired(now = /* @__PURE__ */ new Date()) {
164
- await this.model.where("expiresAt", "<=", now).delete();
165
- }
166
- deserialize(record) {
167
- return decodeJsonColumn(record.data, {});
168
- }
169
- expiryDate(ttlSeconds) {
170
- return new Date(Date.now() + ttlSeconds * 1e3);
171
- }
132
+ model;
133
+ dataMode;
134
+ constructor(table, options = {}) {
135
+ this.dataMode = options.dataMode ?? "json";
136
+ this.model = class SessionModel extends Model$1 {
137
+ static table = table;
138
+ };
139
+ }
140
+ async read(id) {
141
+ const record = await this.model.where({ id }).first();
142
+ if (!record) return;
143
+ if (isExpired(record.expiresAt)) {
144
+ await this.model.where({
145
+ id,
146
+ expiresAt: record.expiresAt
147
+ }).delete();
148
+ return;
149
+ }
150
+ return this.deserialize(record);
151
+ }
152
+ async write(id, data, ttlSeconds) {
153
+ const payload = {
154
+ data: this.dataMode === "text" ? JSON.stringify(data) : data,
155
+ expiresAt: this.expiryDate(ttlSeconds)
156
+ };
157
+ if (await this.model.where({ id }).first()) {
158
+ await this.model.forceUpdate({ id }, payload);
159
+ return;
160
+ }
161
+ try {
162
+ await this.model.forceCreate({
163
+ id,
164
+ ...payload
165
+ });
166
+ } catch (error) {
167
+ if (!await this.model.where({ id }).first()) throw error;
168
+ await this.model.forceUpdate({ id }, payload);
169
+ }
170
+ }
171
+ async destroy(id) {
172
+ await this.model.where({ id }).delete();
173
+ }
174
+ /**
175
+ * Refresh an existing session's TTL with a single conditional UPDATE — no
176
+ * data rewrite, no existence check. Missing rows and rows that have
177
+ * already expired (but not yet been swept) are left untouched, never
178
+ * resurrected — matching the `SessionStore.touch` contract and the memory
179
+ * store's behavior.
180
+ */
181
+ async touch(id, ttlSeconds) {
182
+ await this.model.where({ id }).where("expiresAt", ">", /* @__PURE__ */ new Date()).forceUpdate({ expiresAt: this.expiryDate(ttlSeconds) });
183
+ }
184
+ /**
185
+ * Delete sessions whose expiration time has passed. Expired rows are
186
+ * already treated as missing (and removed) by `read`; call this from a
187
+ * scheduled job to keep the table small.
188
+ */
189
+ async deleteExpired(now = /* @__PURE__ */ new Date()) {
190
+ await this.model.where("expiresAt", "<=", now).delete();
191
+ }
192
+ deserialize(record) {
193
+ return decodeJsonColumn(record.data, {});
194
+ }
195
+ expiryDate(ttlSeconds) {
196
+ return new Date(Date.now() + ttlSeconds * 1e3);
197
+ }
172
198
  };
173
-
174
- // src/oauth-state-store.ts
175
- import { Model as Model3 } from "@guren/orm";
199
+ //#endregion
200
+ //#region src/oauth-state-store.ts
201
+ /**
202
+ * Database-backed OAuth state store built on the Guren ORM.
203
+ *
204
+ * The default `MemoryOAuthStateStore` keeps state in per-isolate memory,
205
+ * which breaks on serverless: the OAuth authorize redirect and the callback
206
+ * that follows it can land on different instances, so an in-memory map
207
+ * never sees the state that was just written. Backing the store with the
208
+ * database makes state visible to whichever instance handles the callback.
209
+ *
210
+ * Pass the Drizzle table for your `oauth_states` schema. Column property
211
+ * names must match `stateHash` (text primary key), `provider`,
212
+ * `redirectTo`, `expiresAt`, and `binding`:
213
+ *
214
+ * ```ts
215
+ * export const oauthStates = sqliteTable('oauth_states', {
216
+ * stateHash: text('state_hash').primaryKey(),
217
+ * provider: text('provider').notNull(),
218
+ * redirectTo: text('redirect_to'),
219
+ * expiresAt: integer('expires_at', { mode: 'timestamp_ms' }).notNull(),
220
+ * binding: text('binding'),
221
+ * })
222
+ * ```
223
+ *
224
+ * `binding` is required for `authorize({ bindTo })` to survive the round trip
225
+ * to the provider. Without the column the store cannot persist it, and every
226
+ * bound state comes back unbound.
227
+ *
228
+ * @example
229
+ * ```ts
230
+ * import { createOAuthManager, DatabaseOAuthStateStore } from '@guren/core'
231
+ * import { oauthStates } from '@/db/schema'
232
+ *
233
+ * export const oauth = createOAuthManager({
234
+ * stateStore: new DatabaseOAuthStateStore(oauthStates),
235
+ * })
236
+ * ```
237
+ */
176
238
  var DatabaseOAuthStateStore = class {
177
- model;
178
- constructor(table) {
179
- this.model = class OAuthStateModel extends Model3 {
180
- static table = table;
181
- };
182
- }
183
- async store(stateHash, payload) {
184
- await this.model.forceCreate({
185
- stateHash,
186
- provider: payload.provider,
187
- redirectTo: payload.redirectTo ?? null,
188
- expiresAt: payload.expiresAt,
189
- // Persisted, not derived: an unbound state verifies for any browser.
190
- binding: payload.binding ?? null
191
- });
192
- }
193
- async find(stateHash) {
194
- const record = await this.fetchLive(stateHash);
195
- return record ? mapRecordToPayload(record) : null;
196
- }
197
- /**
198
- * Fetch the row for `stateHash`, clearing it out and returning null if
199
- * expired. Shared by `find` and `consume`, which otherwise diverge only
200
- * in what they do with a live row.
201
- */
202
- async fetchLive(stateHash) {
203
- const record = await this.model.where({ stateHash }).first();
204
- if (!record) {
205
- return null;
206
- }
207
- if (isExpired(record.expiresAt)) {
208
- await this.model.where({ stateHash, expiresAt: record.expiresAt }).delete();
209
- return null;
210
- }
211
- return record;
212
- }
213
- async delete(stateHash) {
214
- await this.model.where({ stateHash }).delete();
215
- }
216
- /**
217
- * Atomically fetch and delete a state, guaranteeing exactly one concurrent
218
- * caller for the same hash receives the payload.
219
- *
220
- * This guarantee depends on the configured ORM adapter's `delete()`
221
- * reporting whether a row actually matched — either the deleted row
222
- * (RETURNING) or an affected-row count. `DrizzleAdapter`, the framework's
223
- * default and only shipped adapter, always does this: RETURNING drivers
224
- * (Postgres, SQLite, D1) resolve to the deleted row or `undefined` only
225
- * when zero rows matched; MySQL resolves to a result carrying
226
- * `affectedRows` (verified by inspection, not a dedicated test).
227
- *
228
- * The `ORMAdapter.delete` contract also permits a bare `void` return.
229
- * A custom adapter (via `Model.useAdapter()`) that returns `void`
230
- * unconditionally — on both a successful delete and a no-op — gives
231
- * `consume()` no way to tell which caller won: the value is identical for
232
- * both, so no post-hoc check can attribute the deletion. Rather than
233
- * silently rejecting every real login for such adapters,
234
- * `deleteRemovedRow` treats an unrecognized non-null result as removed —
235
- * this reopens the pre-consume find-then-delete race window (multiple
236
- * concurrent callers can pass) for adapters that can't report a match,
237
- * but does not break login. It is fail-closed (returns null / rejects)
238
- * only for `null`/`undefined`, DrizzleAdapter's definitive "no rows
239
- * matched" signal.
240
- */
241
- async consume(stateHash) {
242
- const record = await this.fetchLive(stateHash);
243
- if (!record) {
244
- return null;
245
- }
246
- const result = await this.model.where({ stateHash, expiresAt: record.expiresAt }).delete();
247
- return deleteRemovedRow(result) ? mapRecordToPayload(record) : null;
248
- }
249
- /**
250
- * Delete OAuth states whose expiration time has passed. Expired states
251
- * are already rejected by `find`; call this from a scheduled job to keep
252
- * the table small.
253
- */
254
- async deleteExpired(now = /* @__PURE__ */ new Date()) {
255
- await this.model.where("expiresAt", "<=", now).delete();
256
- }
239
+ model;
240
+ constructor(table) {
241
+ this.model = class OAuthStateModel extends Model$1 {
242
+ static table = table;
243
+ };
244
+ }
245
+ async store(stateHash, payload) {
246
+ await this.model.forceCreate({
247
+ stateHash,
248
+ provider: payload.provider,
249
+ redirectTo: payload.redirectTo ?? null,
250
+ expiresAt: payload.expiresAt,
251
+ binding: payload.binding ?? null
252
+ });
253
+ }
254
+ async find(stateHash) {
255
+ const record = await this.fetchLive(stateHash);
256
+ return record ? mapRecordToPayload(record) : null;
257
+ }
258
+ /**
259
+ * Fetch the row for `stateHash`, clearing it out and returning null if
260
+ * expired. Shared by `find` and `consume`, which otherwise diverge only
261
+ * in what they do with a live row.
262
+ */
263
+ async fetchLive(stateHash) {
264
+ const record = await this.model.where({ stateHash }).first();
265
+ if (!record) return null;
266
+ if (isExpired(record.expiresAt)) {
267
+ await this.model.where({
268
+ stateHash,
269
+ expiresAt: record.expiresAt
270
+ }).delete();
271
+ return null;
272
+ }
273
+ return record;
274
+ }
275
+ async delete(stateHash) {
276
+ await this.model.where({ stateHash }).delete();
277
+ }
278
+ /**
279
+ * Atomically fetch and delete a state, guaranteeing exactly one concurrent
280
+ * caller for the same hash receives the payload.
281
+ *
282
+ * This guarantee depends on the configured ORM adapter's `delete()`
283
+ * reporting whether a row actually matched — either the deleted row
284
+ * (RETURNING) or an affected-row count. `DrizzleAdapter`, the framework's
285
+ * default and only shipped adapter, always does this: RETURNING drivers
286
+ * (Postgres, SQLite, D1) resolve to the deleted row or `undefined` only
287
+ * when zero rows matched; MySQL resolves to a result carrying
288
+ * `affectedRows` (verified by inspection, not a dedicated test).
289
+ *
290
+ * The `ORMAdapter.delete` contract also permits a bare `void` return.
291
+ * A custom adapter (via `Model.useAdapter()`) that returns `void`
292
+ * unconditionally — on both a successful delete and a no-op — gives
293
+ * `consume()` no way to tell which caller won: the value is identical for
294
+ * both, so no post-hoc check can attribute the deletion. Rather than
295
+ * silently rejecting every real login for such adapters,
296
+ * `deleteRemovedRow` treats an unrecognized non-null result as removed —
297
+ * this reopens the pre-consume find-then-delete race window (multiple
298
+ * concurrent callers can pass) for adapters that can't report a match,
299
+ * but does not break login. It is fail-closed (returns null / rejects)
300
+ * only for `null`/`undefined`, DrizzleAdapter's definitive "no rows
301
+ * matched" signal.
302
+ */
303
+ async consume(stateHash) {
304
+ const record = await this.fetchLive(stateHash);
305
+ if (!record) return null;
306
+ return deleteRemovedRow(await this.model.where({
307
+ stateHash,
308
+ expiresAt: record.expiresAt
309
+ }).delete()) ? mapRecordToPayload(record) : null;
310
+ }
311
+ /**
312
+ * Delete OAuth states whose expiration time has passed. Expired states
313
+ * are already rejected by `find`; call this from a scheduled job to keep
314
+ * the table small.
315
+ */
316
+ async deleteExpired(now = /* @__PURE__ */ new Date()) {
317
+ await this.model.where("expiresAt", "<=", now).delete();
318
+ }
257
319
  };
320
+ /**
321
+ * Build the public payload from a live (non-expired) row. Shared by `find`
322
+ * and `consume` so the column-to-payload mapping only lives in one place.
323
+ */
258
324
  function mapRecordToPayload(record) {
259
- return {
260
- provider: String(record.provider),
261
- redirectTo: record.redirectTo == null ? void 0 : String(record.redirectTo),
262
- // fetchLive's isExpired check guarantees this parses.
263
- expiresAt: toDate(record.expiresAt),
264
- binding: record.binding == null ? void 0 : String(record.binding)
265
- };
325
+ return {
326
+ provider: String(record.provider),
327
+ redirectTo: record.redirectTo == null ? void 0 : String(record.redirectTo),
328
+ expiresAt: toDate(record.expiresAt),
329
+ binding: record.binding == null ? void 0 : String(record.binding)
330
+ };
266
331
  }
332
+ /**
333
+ * Interpret an adapter delete result as "this call removed the row". See
334
+ * the `consume()` JSDoc above for the full adapter-support tradeoff: this
335
+ * is exact for DrizzleAdapter, and best-effort (assume removed) for any
336
+ * other result shape, since a bare `void` return carries no information to
337
+ * confirm or refute a match.
338
+ */
267
339
  function deleteRemovedRow(result) {
268
- if (result == null) return false;
269
- if (typeof result === "number") return result > 0;
270
- if (Array.isArray(result)) {
271
- return result.length > 0 && deleteRemovedRow(result[0]);
272
- }
273
- if (typeof result === "object") {
274
- const record = result;
275
- for (const key of ["affectedRows", "rowsAffected", "rowCount", "changes"]) {
276
- if (typeof record[key] === "number") return record[key] > 0;
277
- }
278
- return true;
279
- }
280
- return Boolean(result);
281
- }
282
- export {
283
- DatabaseApiTokenStore,
284
- DatabaseOAuthStateStore,
285
- DatabaseSessionStore,
286
- DrizzleAdapter,
287
- MassAssignmentException,
288
- Model4 as Model,
289
- ModelNotFoundException,
290
- QueryBuilder,
291
- SoftDeletes,
292
- createAwsDataApiDatabase,
293
- createD1Database,
294
- createMySqlDatabase,
295
- createPostgresDatabase,
296
- createSqliteDatabase,
297
- defineModel,
298
- defineSeeder,
299
- runSeeders
340
+ if (result == null) return false;
341
+ if (typeof result === "number") return result > 0;
342
+ if (Array.isArray(result)) return result.length > 0 && deleteRemovedRow(result[0]);
343
+ if (typeof result === "object") {
344
+ const record = result;
345
+ for (const key of [
346
+ "affectedRows",
347
+ "rowsAffected",
348
+ "rowCount",
349
+ "changes"
350
+ ]) if (typeof record[key] === "number") return record[key] > 0;
351
+ return true;
352
+ }
353
+ return Boolean(result);
354
+ }
355
+ //#endregion
356
+ //#region src/attachments/bun-image-processor.ts
357
+ /**
358
+ * The default {@link ImageProcessor}, backed by `Bun.Image`.
359
+ *
360
+ * Resolved strictly behind the `typeof Bun !== 'undefined' && 'Image' in Bun`
361
+ * feature check — never by version: Bun 1.3.x lanes without the API simply
362
+ * get no default processor (attachments still store; variants are recorded
363
+ * as `unavailable`).
364
+ *
365
+ * Format support is decided by the OS codecs at call time: rejections carry
366
+ * `error.code === 'ERR_IMAGE_FORMAT_UNSUPPORTED'` and the pipeline branches
367
+ * on that code only — there is no hardcoded format×platform matrix, because
368
+ * measured counterexamples exist for every such table.
369
+ */
370
+ var BunImageProcessor = class {
371
+ Image;
372
+ maxPixels;
373
+ constructor(Image, maxPixels) {
374
+ this.Image = Image;
375
+ this.maxPixels = maxPixels;
376
+ }
377
+ async probe(input, limits) {
378
+ const image = new this.Image(input, { maxPixels: limits.maxPixels });
379
+ const metadata = await image.metadata();
380
+ const placeholder = await image.placeholder();
381
+ return {
382
+ width: metadata.width,
383
+ height: metadata.height,
384
+ format: metadata.format,
385
+ placeholder
386
+ };
387
+ }
388
+ async process(input, spec) {
389
+ const image = new this.Image(input, { maxPixels: this.maxPixels });
390
+ const fit = spec.fit ?? "inside";
391
+ if (spec.width != null && spec.height != null) image.resize(spec.width, spec.height, { fit });
392
+ else if (spec.width != null) image.resize(spec.width);
393
+ else if (spec.height != null) {
394
+ const metadata = await image.metadata();
395
+ const width = Math.max(1, Math.round(spec.height * metadata.width / metadata.height));
396
+ image.resize(width, spec.height, { fit });
397
+ }
398
+ const encodeOptions = spec.quality != null ? { quality: spec.quality } : void 0;
399
+ switch (spec.format) {
400
+ case "jpeg":
401
+ image.jpeg(encodeOptions);
402
+ break;
403
+ case "png":
404
+ image.png();
405
+ break;
406
+ case "webp":
407
+ image.webp(encodeOptions);
408
+ break;
409
+ case "avif":
410
+ image.avif(encodeOptions);
411
+ break;
412
+ case void 0:
413
+ }
414
+ const bytes = await image.bytes();
415
+ const output = await new this.Image(bytes).metadata();
416
+ return {
417
+ bytes,
418
+ width: output.width,
419
+ height: output.height,
420
+ format: output.format
421
+ };
422
+ }
423
+ };
424
+ /**
425
+ * Resolve the default processor for this runtime: `Bun.Image` when present,
426
+ * `null` otherwise (Node/Lambda/Workers — inject a custom processor or let
427
+ * variants degrade to `unavailable`).
428
+ */
429
+ function resolveDefaultImageProcessor(maxPixels) {
430
+ if (typeof Bun === "undefined" || !("Image" in Bun)) return null;
431
+ const Image = Bun.Image;
432
+ return new BunImageProcessor(Image, maxPixels);
433
+ }
434
+ //#endregion
435
+ //#region src/attachments/image-sniff.ts
436
+ function sniffImage(bytes) {
437
+ return sniffPng(bytes) ?? sniffJpeg(bytes) ?? sniffGif(bytes) ?? sniffWebp(bytes) ?? sniffIsoBmff(bytes);
438
+ }
439
+ function u16be(bytes, offset) {
440
+ return bytes[offset] << 8 | bytes[offset + 1];
441
+ }
442
+ function u16le(bytes, offset) {
443
+ return bytes[offset] | bytes[offset + 1] << 8;
444
+ }
445
+ function u24le(bytes, offset) {
446
+ return bytes[offset] | bytes[offset + 1] << 8 | bytes[offset + 2] << 16;
447
+ }
448
+ function u32be(bytes, offset) {
449
+ return (bytes[offset] << 24 | bytes[offset + 1] << 16 | bytes[offset + 2] << 8 | bytes[offset + 3]) >>> 0;
450
+ }
451
+ function ascii(bytes, offset, length) {
452
+ let out = "";
453
+ for (let i = 0; i < length; i++) out += String.fromCharCode(bytes[offset + i]);
454
+ return out;
455
+ }
456
+ const PNG_SIGNATURE = [
457
+ 137,
458
+ 80,
459
+ 78,
460
+ 71,
461
+ 13,
462
+ 10,
463
+ 26,
464
+ 10
465
+ ];
466
+ function sniffPng(bytes) {
467
+ if (bytes.length < 24) return null;
468
+ for (let i = 0; i < PNG_SIGNATURE.length; i++) if (bytes[i] !== PNG_SIGNATURE[i]) return null;
469
+ if (ascii(bytes, 12, 4) !== "IHDR") return { format: "png" };
470
+ return {
471
+ format: "png",
472
+ width: u32be(bytes, 16),
473
+ height: u32be(bytes, 20)
474
+ };
475
+ }
476
+ function sniffJpeg(bytes) {
477
+ if (bytes.length < 4 || bytes[0] !== 255 || bytes[1] !== 216 || bytes[2] !== 255) return null;
478
+ let offset = 2;
479
+ while (offset + 4 <= bytes.length) {
480
+ if (bytes[offset] !== 255) {
481
+ offset++;
482
+ continue;
483
+ }
484
+ const marker = bytes[offset + 1];
485
+ if (marker === 255) {
486
+ offset++;
487
+ continue;
488
+ }
489
+ if (marker === 216 || marker >= 208 && marker <= 215 || marker === 1) {
490
+ offset += 2;
491
+ continue;
492
+ }
493
+ if (marker === 217 || marker === 218) break;
494
+ const length = u16be(bytes, offset + 2);
495
+ if (length < 2) break;
496
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
497
+ if (offset + 9 > bytes.length) break;
498
+ return {
499
+ format: "jpeg",
500
+ height: u16be(bytes, offset + 5),
501
+ width: u16be(bytes, offset + 7)
502
+ };
503
+ }
504
+ offset += 2 + length;
505
+ }
506
+ return { format: "jpeg" };
507
+ }
508
+ function sniffGif(bytes) {
509
+ if (bytes.length < 10) return null;
510
+ const header = ascii(bytes, 0, 6);
511
+ if (header !== "GIF87a" && header !== "GIF89a") return null;
512
+ return {
513
+ format: "gif",
514
+ width: u16le(bytes, 6),
515
+ height: u16le(bytes, 8)
516
+ };
517
+ }
518
+ function sniffWebp(bytes) {
519
+ if (bytes.length < 16 || ascii(bytes, 0, 4) !== "RIFF" || ascii(bytes, 8, 4) !== "WEBP") return null;
520
+ const chunk = ascii(bytes, 12, 4);
521
+ if (chunk === "VP8 " && bytes.length >= 30) {
522
+ if (bytes[23] === 157 && bytes[24] === 1 && bytes[25] === 42) return {
523
+ format: "webp",
524
+ width: u16le(bytes, 26) & 16383,
525
+ height: u16le(bytes, 28) & 16383
526
+ };
527
+ return { format: "webp" };
528
+ }
529
+ if (chunk === "VP8L" && bytes.length >= 25 && bytes[20] === 47) {
530
+ const b0 = bytes[21];
531
+ const b1 = bytes[22];
532
+ const b2 = bytes[23];
533
+ const b3 = bytes[24];
534
+ return {
535
+ format: "webp",
536
+ width: 1 + ((b1 & 63) << 8 | b0),
537
+ height: 1 + ((b3 & 15) << 10 | b2 << 2 | b1 >> 6)
538
+ };
539
+ }
540
+ if (chunk === "VP8X" && bytes.length >= 30) return {
541
+ format: "webp",
542
+ width: 1 + u24le(bytes, 24),
543
+ height: 1 + u24le(bytes, 27)
544
+ };
545
+ return { format: "webp" };
546
+ }
547
+ const AVIF_BRANDS = /* @__PURE__ */ new Set(["avif", "avis"]);
548
+ const HEIC_BRANDS = /* @__PURE__ */ new Set([
549
+ "heic",
550
+ "heix",
551
+ "hevc",
552
+ "hevx",
553
+ "heim",
554
+ "heis",
555
+ "hevm",
556
+ "hevs"
557
+ ]);
558
+ function classifyBrand(brand) {
559
+ if (AVIF_BRANDS.has(brand)) return "avif";
560
+ if (HEIC_BRANDS.has(brand)) return "heic";
561
+ return null;
562
+ }
563
+ /** AVIF and HEIC/HEIF share the ISO BMFF container; the `ftyp` brands tell them apart. */
564
+ function sniffIsoBmff(bytes) {
565
+ if (bytes.length < 16 || ascii(bytes, 4, 4) !== "ftyp") return null;
566
+ const boxSize = u32be(bytes, 0);
567
+ if (boxSize < 16 || boxSize > bytes.length) return null;
568
+ let format = classifyBrand(ascii(bytes, 8, 4));
569
+ const scanEnd = Math.min(boxSize, 80);
570
+ for (let offset = 16; format === null && offset + 4 <= scanEnd; offset += 4) format = classifyBrand(ascii(bytes, offset, 4));
571
+ if (!format) return null;
572
+ const dimensions = findIspe(bytes, 0, bytes.length, 0);
573
+ return dimensions ? {
574
+ format,
575
+ ...dimensions
576
+ } : { format };
577
+ }
578
+ /** Containers worth descending into on the way to `ipco`'s `ispe` box. */
579
+ const BMFF_CONTAINERS = /* @__PURE__ */ new Set([
580
+ "meta",
581
+ "iprp",
582
+ "ipco"
583
+ ]);
584
+ function findIspe(bytes, start, end, depth) {
585
+ if (depth > 4) return null;
586
+ let offset = start;
587
+ while (offset + 8 <= end) {
588
+ const size = u32be(bytes, offset);
589
+ const type = ascii(bytes, offset + 4, 4);
590
+ if (size < 8 || offset + size > end) return null;
591
+ if (type === "ispe") {
592
+ if (offset + 20 <= end) return {
593
+ width: u32be(bytes, offset + 12),
594
+ height: u32be(bytes, offset + 16)
595
+ };
596
+ return null;
597
+ }
598
+ if (BMFF_CONTAINERS.has(type)) {
599
+ const found = findIspe(bytes, offset + (type === "meta" ? 12 : 8), offset + size, depth + 1);
600
+ if (found) return found;
601
+ }
602
+ offset += size;
603
+ }
604
+ return null;
605
+ }
606
+ //#endregion
607
+ //#region src/attachments/ulid.ts
608
+ /**
609
+ * Dependency-free monotonic ULID generator (https://github.com/ulid/spec):
610
+ * 48-bit millisecond timestamp + 80 bits of randomness, Crockford base32.
611
+ *
612
+ * Attachment ids double as object-key prefixes and as the sort key for
613
+ * `hasMany` collections, so they must be sortable — including *within* one
614
+ * millisecond, where the spec's monotonic mode applies: the random half is
615
+ * incremented instead of redrawn, keeping ids generated in the same process
616
+ * in insertion order. They must also be unguessable before the row exists
617
+ * (the random half). `byte % 32` is bias-free here because 256 is a
618
+ * multiple of 32.
619
+ */
620
+ const ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
621
+ /**
622
+ * The millisecond timestamp encoded in a ULID's first 10 characters, or
623
+ * `null` for anything that is not a 26-character Crockford string. The
624
+ * prune sweep uses it to leave recently-minted prefixes alone.
625
+ */
626
+ function ulidTime(id) {
627
+ if (!/^[0-9A-HJKMNP-TV-Z]{26}$/.test(id)) return null;
628
+ let time = 0;
629
+ for (let i = 0; i < 10; i++) time = time * 32 + ENCODING.indexOf(id[i]);
630
+ return time;
631
+ }
632
+ let lastTime = -1;
633
+ const lastRandom = /* @__PURE__ */ new Uint8Array(16);
634
+ function freshRandom() {
635
+ const bytes = /* @__PURE__ */ new Uint8Array(16);
636
+ globalThis.crypto.getRandomValues(bytes);
637
+ for (let i = 0; i < 16; i++) lastRandom[i] = bytes[i] % 32;
638
+ }
639
+ /** Increment the random half; returns false on (astronomically unlikely) overflow. */
640
+ function incrementRandom() {
641
+ for (let i = 15; i >= 0; i--) {
642
+ if (lastRandom[i] < 31) {
643
+ lastRandom[i]++;
644
+ return true;
645
+ }
646
+ lastRandom[i] = 0;
647
+ }
648
+ return false;
649
+ }
650
+ function ulid(now = Date.now()) {
651
+ let time = now > lastTime ? now : lastTime;
652
+ if (time === lastTime) {
653
+ if (!incrementRandom()) {
654
+ time += 1;
655
+ freshRandom();
656
+ }
657
+ } else freshRandom();
658
+ lastTime = time;
659
+ let chars = "";
660
+ for (let i = 0; i < 10; i++) {
661
+ chars = ENCODING[time % 32] + chars;
662
+ time = Math.floor(time / 32);
663
+ }
664
+ for (let i = 0; i < 16; i++) chars += ENCODING[lastRandom[i]];
665
+ return chars;
666
+ }
667
+ //#endregion
668
+ //#region src/attachments/engine.ts
669
+ const DEFAULT_MAX_PIXELS = 52e6;
670
+ /**
671
+ * Header sniffing only ever needs the first bytes; capping the window keeps
672
+ * the JPEG marker walk O(cap) instead of O(input) on attacker-sized bytes
673
+ * that reach the sniffer before the byte-cap gate applies (image: 'allow'
674
+ * collections must not size-reject non-image files).
675
+ */
676
+ const SNIFF_WINDOW_BYTES = 262144;
677
+ const DEFAULT_MAX_IMAGE_BYTES = 5e7;
678
+ const DEFAULT_URL_EXPIRES_IN = 3e5;
679
+ /**
680
+ * How recently minted a storage prefix may be before `--objects` refuses to
681
+ * touch it. attach() writes the object *before* the row, so a prefix without
682
+ * a row is either debris — or an attach in flight. The prefix id is a ULID,
683
+ * so its age is readable; anything younger than this window is skipped and
684
+ * picked up by the next sweep if it really was abandoned.
685
+ */
686
+ const PRUNE_OBJECTS_GRACE_MS = 36e5;
687
+ /** Existence lookups are chunked to stay inside every dialect's bind-parameter limits. */
688
+ const PRUNE_LOOKUP_CHUNK = 500;
689
+ /**
690
+ * The spellings under which an id may appear on either side of the prune
691
+ * comparison: as stored (lowercased — UUID hex case is not identity) and,
692
+ * for numeric values, the canonical numeric form ('01' and 1 are the same
693
+ * key). Used symmetrically so a representation mismatch always errs toward
694
+ * "the record exists".
695
+ */
696
+ function idSpellings(value) {
697
+ const raw = String(value).toLowerCase();
698
+ const spellings = [raw];
699
+ if (/^\d+$/.test(raw)) {
700
+ const canonical = String(Number(raw));
701
+ if (canonical !== raw) spellings.push(canonical);
702
+ }
703
+ return spellings;
704
+ }
705
+ const IMAGE_MIME = {
706
+ jpeg: "image/jpeg",
707
+ png: "image/png",
708
+ gif: "image/gif",
709
+ webp: "image/webp",
710
+ avif: "image/avif",
711
+ heic: "image/heic",
712
+ bmp: "image/bmp",
713
+ tiff: "image/tiff"
714
+ };
715
+ const VARIANT_EXTENSION = {
716
+ jpeg: "jpg",
717
+ png: "png",
718
+ webp: "webp",
719
+ avif: "avif"
720
+ };
721
+ var AttachmentEngine = class {
722
+ model;
723
+ storage;
724
+ defaultDisk;
725
+ diskVisibility;
726
+ maxPixels;
727
+ maxImageBytes;
728
+ processor;
729
+ urlExpiresIn;
730
+ queue;
731
+ dispatchJob = null;
732
+ constructor(options) {
733
+ const table = options.table;
734
+ this.model = class AttachmentModel extends Model$1 {
735
+ static table = table;
736
+ };
737
+ this.model.morphTo("attachable", "attachable");
738
+ this.storage = options.storage;
739
+ this.defaultDisk = options.disk;
740
+ this.diskVisibility = options.disks ?? {};
741
+ this.maxPixels = options.maxPixels ?? DEFAULT_MAX_PIXELS;
742
+ this.maxImageBytes = options.maxImageBytes ?? DEFAULT_MAX_IMAGE_BYTES;
743
+ this.processor = options.processor !== void 0 ? options.processor : resolveDefaultImageProcessor(this.maxPixels);
744
+ this.urlExpiresIn = options.urlExpiresIn ?? DEFAULT_URL_EXPIRES_IN;
745
+ this.queue = options.queue;
746
+ }
747
+ /** Wired by `configureAttachments()`; kept out of the constructor so this module never imports the job (which imports this module). */
748
+ setJobDispatcher(dispatch) {
749
+ this.dispatchJob = dispatch;
750
+ }
751
+ async attach(model, declaration, recordId, collection, source, options = {}) {
752
+ const spec = this.specFor(model, declaration, collection);
753
+ const normalized = await normalizeSource(source, options.name);
754
+ const queued = options.queued === true;
755
+ if (queued) this.ensureQueueDispatchable();
756
+ const inspection = await this.inspectImage(spec, collection, normalized, queued);
757
+ const id = ulid();
758
+ const name = inspection.name;
759
+ const path = `attachments/${id}/${name}`;
760
+ const diskName = options.disk ?? this.defaultDisk;
761
+ const disk = this.storage().disk(diskName);
762
+ const contentType = inspection.contentType ?? normalized.declaredContentType ?? "application/octet-stream";
763
+ const replaced = spec.kind === "one" ? await this.rowsFor(model, recordId, { collection }) : [];
764
+ await disk.put(path, Buffer.from(inspection.bytes), { contentType });
765
+ const variants = await this.buildVariants(spec, id, disk, inspection);
766
+ const now = /* @__PURE__ */ new Date();
767
+ const row = await this.model.forceCreate({
768
+ id,
769
+ attachableType: model.name,
770
+ attachableId: String(recordId),
771
+ collection,
772
+ disk: diskName,
773
+ path,
774
+ name,
775
+ contentType,
776
+ size: inspection.bytes.byteLength,
777
+ width: inspection.width,
778
+ height: inspection.height,
779
+ variants,
780
+ placeholder: inspection.placeholder,
781
+ createdAt: now,
782
+ updatedAt: now
783
+ });
784
+ if (inspection.deferred) try {
785
+ await this.dispatchGeneration({
786
+ attachmentId: id,
787
+ image: spec.image,
788
+ heic: spec.accepts?.heic,
789
+ variants: spec.variants ? structuredClone(spec.variants) : void 0
790
+ });
791
+ } catch (error) {
792
+ await this.purgeRows([row]);
793
+ throw error;
794
+ }
795
+ if (replaced.length > 0) await this.purgeRows(replaced);
796
+ return this.toRecord(row);
797
+ }
798
+ async detach(model, declaration, recordId, collection, attachmentId) {
799
+ if (this.specFor(model, declaration, collection).kind === "one" && attachmentId !== void 0) throw new Error(`${model.name}.detach(): '${collection}' is a hasOne collection — it has no attachment id to select.`);
800
+ const rows = await this.rowsFor(model, recordId, {
801
+ collection,
802
+ id: attachmentId
803
+ });
804
+ await this.purgeRows(rows);
805
+ }
806
+ async withAttachments(model, declaration, records, names) {
807
+ for (const name of names) this.specFor(model, declaration, name);
808
+ const rows = await this.rowsForPage(model, records, names);
809
+ const dataByRecord = /* @__PURE__ */ new Map();
810
+ for (const raw of rows) {
811
+ const row = this.toRecord(raw);
812
+ const spec = declaration[row.collection];
813
+ if (!spec) continue;
814
+ const data = await this.toData(row, spec);
815
+ let byCollection = dataByRecord.get(row.attachableId);
816
+ if (!byCollection) {
817
+ byCollection = /* @__PURE__ */ new Map();
818
+ dataByRecord.set(row.attachableId, byCollection);
819
+ }
820
+ let list = byCollection.get(row.collection);
821
+ if (!list) {
822
+ list = [];
823
+ byCollection.set(row.collection, list);
824
+ }
825
+ list.push(data);
826
+ }
827
+ return records.map((record) => {
828
+ const byCollection = dataByRecord.get(String(record.id));
829
+ const attached = { ...record };
830
+ for (const name of names) {
831
+ const spec = declaration[name];
832
+ const list = byCollection?.get(name) ?? [];
833
+ attached[name] = spec.kind === "many" ? list : list[list.length - 1] ?? null;
834
+ }
835
+ return attached;
836
+ });
837
+ }
838
+ async attachmentUrl(model, declaration, recordOrId, collection, options = {}) {
839
+ const spec = this.specFor(model, declaration, collection);
840
+ const variant = options.variant;
841
+ if (variant !== void 0 && !(variant in (spec.variants ?? {}))) throw new Error(`${model.name}.attachmentUrl(): variant '${variant}' is not declared on collection '${collection}'.`);
842
+ const recordId = typeof recordOrId === "object" ? recordOrId.id : recordOrId;
843
+ if (recordId == null) return null;
844
+ const rows = sortById(await this.rowsFor(model, recordId, { collection }));
845
+ const raw = spec.kind === "one" ? rows[rows.length - 1] : rows[0];
846
+ if (!raw) return null;
847
+ const row = this.toRecord(raw);
848
+ if (variant !== void 0) {
849
+ const entry = row.variants?.[variant];
850
+ if (entry?.status === "ready" && entry.path) return this.urlFor(row.disk, entry.path);
851
+ }
852
+ return this.urlFor(row.disk, row.path);
853
+ }
854
+ async purgeAttachments(model, recordId) {
855
+ const rows = await this.rowsFor(model, recordId, {});
856
+ await this.purgeRows(rows);
857
+ }
858
+ specFor(model, declaration, collection) {
859
+ const spec = declaration[collection];
860
+ if (!spec) throw new Error(`${model.name} declares no attachment collection '${collection}'. Declared: ${Object.keys(declaration).join(", ") || "(none)"}.`);
861
+ return spec;
862
+ }
863
+ /**
864
+ * The three-gate image pipeline (RFC 0013 §6): (1) encoded-byte cap,
865
+ * (2) header-dimension cap, (3) full decode. Gates 1-2 plus the HEIC
866
+ * signature rejection are pure JS and run on every runtime; only the full
867
+ * decode needs a processor.
868
+ */
869
+ async inspectImage(spec, collection, source, defer = false) {
870
+ const opaque = {
871
+ width: null,
872
+ height: null,
873
+ placeholder: null,
874
+ contentType: null,
875
+ decoded: false,
876
+ bytes: source.bytes,
877
+ name: source.name
878
+ };
879
+ const policy = spec.image;
880
+ if (policy === void 0) return opaque;
881
+ const sniffed = sniffImage(source.bytes.subarray(0, SNIFF_WINDOW_BYTES));
882
+ if (policy === "forbid") {
883
+ if (sniffed) throw new ValidationException({ [collection]: ["The file must not be an image."] });
884
+ return opaque;
885
+ }
886
+ if (!sniffed) {
887
+ if (policy === "require") throw new ValidationException({ [collection]: ["The file must be an image."] });
888
+ return opaque;
889
+ }
890
+ if (source.bytes.byteLength > this.maxImageBytes) throw new HttpException(413, `Image exceeds the maximum allowed size of ${this.maxImageBytes} bytes.`);
891
+ if (sniffed.format === "heic") {
892
+ if ((spec.accepts?.heic ?? "reject") === "reject") throw new HttpException(415, "HEIC/HEIF uploads are not accepted. Declare accepts: { heic: 'convert' } on the collection to convert them where the runtime supports it.");
893
+ if (!this.processor && !defer) throw new HttpException(415, "HEIC/HEIF conversion is not available on this runtime.");
894
+ }
895
+ if (sniffed.width != null && sniffed.height != null && sniffed.width * sniffed.height > this.maxPixels) throw new ValidationException({ [collection]: [`Image dimensions ${sniffed.width}x${sniffed.height} exceed the maximum of ${this.maxPixels} pixels.`] });
896
+ if (defer) return {
897
+ width: sniffed.width ?? null,
898
+ height: sniffed.height ?? null,
899
+ placeholder: null,
900
+ contentType: IMAGE_MIME[sniffed.format] ?? null,
901
+ decoded: false,
902
+ deferred: true,
903
+ bytes: source.bytes,
904
+ name: source.name
905
+ };
906
+ if (!this.processor) return {
907
+ width: sniffed.width ?? null,
908
+ height: sniffed.height ?? null,
909
+ placeholder: null,
910
+ contentType: IMAGE_MIME[sniffed.format] ?? null,
911
+ decoded: false,
912
+ bytes: source.bytes,
913
+ name: source.name
914
+ };
915
+ let probed;
916
+ try {
917
+ probed = await this.processor.probe(source.bytes, { maxPixels: this.maxPixels });
918
+ } catch (error) {
919
+ if (errorCode(error) === "ERR_IMAGE_FORMAT_UNSUPPORTED") throw new HttpException(415, `This runtime cannot decode ${sniffed.format} images.`);
920
+ if (policy === "require") throw new ValidationException({ [collection]: ["The file must be a valid image."] });
921
+ return opaque;
922
+ }
923
+ if (sniffed.format === "heic") {
924
+ const converted = await this.processor.process(source.bytes, { format: "jpeg" });
925
+ return {
926
+ width: converted.width,
927
+ height: converted.height,
928
+ placeholder: probed.placeholder ?? null,
929
+ contentType: "image/jpeg",
930
+ decoded: true,
931
+ bytes: converted.bytes,
932
+ name: replaceExtension(source.name, "jpg")
933
+ };
934
+ }
935
+ return {
936
+ width: probed.width,
937
+ height: probed.height,
938
+ placeholder: probed.placeholder ?? null,
939
+ contentType: IMAGE_MIME[probed.format] ?? IMAGE_MIME[sniffed.format] ?? null,
940
+ decoded: true,
941
+ bytes: source.bytes,
942
+ name: source.name
943
+ };
944
+ }
945
+ /**
946
+ * Seed one entry per *declared* variant and generate inline where a
947
+ * processor exists. Recording declared names (not just generated ones) is
948
+ * what lets `attachmentUrl()` tell "not yet generated" from "never
949
+ * declared" after a reload.
950
+ */
951
+ async buildVariants(spec, id, disk, inspection) {
952
+ const declared = Object.entries(spec.variants ?? {});
953
+ if (declared.length === 0) return null;
954
+ const variants = {};
955
+ for (const [name, variantSpec] of declared) {
956
+ if (inspection.deferred) {
957
+ variants[name] = { status: "pending" };
958
+ continue;
959
+ }
960
+ if (!this.processor) {
961
+ variants[name] = { status: "unavailable" };
962
+ continue;
963
+ }
964
+ if (!inspection.decoded) {
965
+ variants[name] = { status: "failed" };
966
+ continue;
967
+ }
968
+ try {
969
+ const result = await this.processor.process(inspection.bytes, variantSpec);
970
+ const path = `attachments/${id}/variants/${name}.${VARIANT_EXTENSION[result.format] ?? result.format}`;
971
+ await disk.put(path, Buffer.from(result.bytes), { contentType: IMAGE_MIME[result.format] ?? "application/octet-stream" });
972
+ variants[name] = {
973
+ status: "ready",
974
+ path,
975
+ width: result.width,
976
+ height: result.height,
977
+ format: result.format,
978
+ size: result.bytes.byteLength
979
+ };
980
+ } catch {
981
+ variants[name] = { status: "failed" };
982
+ }
983
+ }
984
+ return variants;
985
+ }
986
+ /**
987
+ * Worker-side completion of a deferred attach (`GenerateVariantsJob`):
988
+ * run the full decode that the request path skipped, convert a HEIC
989
+ * original where the collection opted in, generate the declared variants,
990
+ * and settle every `pending` status record. Safe against races — a row or
991
+ * object purged while the job sat in the queue is simply nothing to do.
992
+ */
993
+ async generateVariants(payload) {
994
+ const raw = await this.model.where({ id: payload.attachmentId }).first();
995
+ if (!raw) return;
996
+ const row = this.toRecord(raw);
997
+ const disk = this.storage().disk(row.disk);
998
+ if (!this.processor) {
999
+ if (payload.heic === "convert" && payload.image === "require" && row.contentType === "image/heic") {
1000
+ await this.purgeRows([raw]);
1001
+ return;
1002
+ }
1003
+ await this.settleDeferred(row, "unavailable");
1004
+ return;
1005
+ }
1006
+ const stored = await disk.get(row.path);
1007
+ if (!stored) {
1008
+ await this.settleDeferred(row, "failed");
1009
+ return;
1010
+ }
1011
+ let bytes = new Uint8Array(stored);
1012
+ let probed;
1013
+ try {
1014
+ probed = await this.processor.probe(bytes, { maxPixels: this.maxPixels });
1015
+ } catch {
1016
+ if (payload.image === "require") {
1017
+ await this.purgeRows([raw]);
1018
+ return;
1019
+ }
1020
+ await this.settleDeferred(row, "failed", { clearImageMetadata: true });
1021
+ return;
1022
+ }
1023
+ const updates = {
1024
+ width: probed.width,
1025
+ height: probed.height,
1026
+ placeholder: probed.placeholder ?? null
1027
+ };
1028
+ const sniffed = sniffImage(bytes.subarray(0, SNIFF_WINDOW_BYTES));
1029
+ let supersededPath = null;
1030
+ if (sniffed?.format === "heic" && payload.heic === "convert") {
1031
+ const converted = await this.processor.process(bytes, { format: "jpeg" });
1032
+ const name = replaceExtension(row.name, "jpg");
1033
+ const path = `attachments/${row.id}/${name}`;
1034
+ await disk.put(path, Buffer.from(converted.bytes), { contentType: "image/jpeg" });
1035
+ if (path !== row.path) supersededPath = row.path;
1036
+ bytes = converted.bytes;
1037
+ updates.name = name;
1038
+ updates.path = path;
1039
+ updates.contentType = "image/jpeg";
1040
+ updates.size = converted.bytes.byteLength;
1041
+ updates.width = converted.width;
1042
+ updates.height = converted.height;
1043
+ }
1044
+ const variants = await this.buildVariants({ variants: payload.variants }, row.id, disk, {
1045
+ bytes,
1046
+ decoded: true
1047
+ });
1048
+ if (variants) updates.variants = variants;
1049
+ updates.updatedAt = /* @__PURE__ */ new Date();
1050
+ if (!await this.model.where({ id: row.id }).first()) {
1051
+ await disk.deleteDirectory(`attachments/${row.id}`);
1052
+ return;
1053
+ }
1054
+ await this.model.forceUpdate({ id: row.id }, updates);
1055
+ if (supersededPath) try {
1056
+ await disk.delete(supersededPath);
1057
+ } catch {}
1058
+ }
1059
+ /** `GenerateVariantsJob.failed()`: settle `pending` records after the last retry. */
1060
+ async markDeferredFailed(attachmentId) {
1061
+ await this.settleDeferred({ id: attachmentId }, "failed");
1062
+ }
1063
+ /**
1064
+ * Flip every `pending` variant to a terminal status so nothing looks
1065
+ * in-flight forever. Works on a *fresh* read of the row, never a caller's
1066
+ * snapshot: under at-least-once delivery a duplicate execution can hold a
1067
+ * stale copy whose `pending` entries would otherwise clobber the variants
1068
+ * a completed run already marked `ready`.
1069
+ */
1070
+ async settleDeferred(row, status, options = {}) {
1071
+ const fresh = await this.model.where({ id: row.id }).first();
1072
+ if (!fresh) return;
1073
+ const current = this.toRecord(fresh);
1074
+ const updates = { updatedAt: /* @__PURE__ */ new Date() };
1075
+ let changed = false;
1076
+ if (current.variants) {
1077
+ const variants = { ...current.variants };
1078
+ for (const [name, entry] of Object.entries(variants)) if (entry.status === "pending") {
1079
+ variants[name] = { status };
1080
+ changed = true;
1081
+ }
1082
+ if (changed) updates.variants = variants;
1083
+ }
1084
+ if (options.clearImageMetadata) {
1085
+ updates.width = null;
1086
+ updates.height = null;
1087
+ updates.placeholder = null;
1088
+ changed = true;
1089
+ }
1090
+ if (!changed) return;
1091
+ await this.model.forceUpdate({ id: row.id }, updates);
1092
+ }
1093
+ /**
1094
+ * A queued attach needs somewhere to dispatch to: the configured
1095
+ * QueueManager's default driver, or — when no `queue` option was given —
1096
+ * whatever queue driver the app has already booted globally.
1097
+ */
1098
+ ensureQueueDispatchable() {
1099
+ if (!this.dispatchJob) throw new Error("Attachments queue dispatch is not wired. Call configureAttachments() before attaching.");
1100
+ if (this.queue) {
1101
+ const manager = this.queue();
1102
+ if (typeof manager?.driver !== "function") throw new Error("configureAttachments({ queue }) must resolve to a QueueManager (an object with a driver() method).");
1103
+ setQueueDriver(manager.driver());
1104
+ return;
1105
+ }
1106
+ if (!getQueueDriver()) throw new Error("attach() with queued: true requires a queue. Pass configureAttachments({ queue: () => queueManager }) or boot the app's queue before attaching.");
1107
+ }
1108
+ async dispatchGeneration(payload) {
1109
+ this.ensureQueueDispatchable();
1110
+ await this.dispatchJob(payload);
1111
+ }
1112
+ /**
1113
+ * The single indexed query behind `withAttachments()`. An empty `records`
1114
+ * or `names` short-circuits: either would send an empty `IN ()` list to the
1115
+ * adapter rather than matching nothing.
1116
+ */
1117
+ async rowsForPage(model, records, names) {
1118
+ const ids = records.map((record) => String(record.id));
1119
+ if (ids.length === 0 || names.length === 0) return [];
1120
+ return sortById(await this.model.where({
1121
+ attachableType: model.name,
1122
+ attachableId: ids,
1123
+ collection: [...names]
1124
+ }));
1125
+ }
1126
+ async rowsFor(model, recordId, filter) {
1127
+ const where = {
1128
+ attachableType: model.name,
1129
+ attachableId: String(recordId)
1130
+ };
1131
+ if (filter.collection !== void 0) where.collection = filter.collection;
1132
+ if (filter.id !== void 0) where.id = filter.id;
1133
+ return await this.model.where(where);
1134
+ }
1135
+ /**
1136
+ * Objects first, rows after (RFC 0013 §8): a crash between the two leaves
1137
+ * a row pointing at nothing, which the next `url()` surfaces loudly — the
1138
+ * reverse would leave invisible orphaned objects only a bucket audit finds.
1139
+ */
1140
+ async purgeRows(rows) {
1141
+ for (const row of rows) await this.storage().disk(String(row.disk)).deleteDirectory(`attachments/${String(row.id)}`);
1142
+ const ids = rows.map((row) => String(row.id));
1143
+ for (let start = 0; start < ids.length; start += PRUNE_LOOKUP_CHUNK) await this.model.where({ id: ids.slice(start, start + PRUNE_LOOKUP_CHUNK) }).delete();
1144
+ }
1145
+ /**
1146
+ * The sweeper behind `attachments:prune` (RFC 0013 §8): no DB cascade can
1147
+ * exist for a polymorphic pair, so deletion is explicit-plus-sweep. Rows
1148
+ * are removed only on *positive* evidence the record is gone — the owning
1149
+ * type resolved through `Model.morphMap` and the record queried and found
1150
+ * missing. Anything unverifiable (type not in the morph map, a failing
1151
+ * query, an unlistable disk) is reported and left alone.
1152
+ */
1153
+ async pruneOrphans(options = {}) {
1154
+ const rows = await this.model.withoutGlobalScopes();
1155
+ const report = {
1156
+ scannedRows: rows.length,
1157
+ orphanRows: [],
1158
+ skippedTypes: [],
1159
+ orphanObjectPrefixes: [],
1160
+ skippedDisks: []
1161
+ };
1162
+ const byType = /* @__PURE__ */ new Map();
1163
+ for (const row of rows) {
1164
+ const type = String(row.attachableType);
1165
+ const group = byType.get(type);
1166
+ if (group) group.push(row);
1167
+ else byType.set(type, [row]);
1168
+ }
1169
+ const morphMap = Model$1.morphMap ?? {};
1170
+ const orphans = [];
1171
+ for (const [type, group] of byType) {
1172
+ const relatedModel = morphMap[type];
1173
+ if (!relatedModel) {
1174
+ report.skippedTypes.push({
1175
+ type,
1176
+ reason: `'${type}' is not in Model.morphMap — set Model.morphMap = { ${type} } so its records can be checked.`
1177
+ });
1178
+ continue;
1179
+ }
1180
+ const ids = Array.from(new Set(group.map((row) => String(row.attachableId))));
1181
+ const existing = /* @__PURE__ */ new Set();
1182
+ const unverifiable = /* @__PURE__ */ new Set();
1183
+ for (let start = 0; start < ids.length; start += PRUNE_LOOKUP_CHUNK) {
1184
+ const chunk = ids.slice(start, start + PRUNE_LOOKUP_CHUNK);
1185
+ const lookupValues = chunk.flatMap((id) => /^\d+$/.test(id) ? [id, Number(id)] : [id]);
1186
+ try {
1187
+ const records = await relatedModel.withoutGlobalScopes().where({ id: lookupValues });
1188
+ for (const record of records) for (const spelling of idSpellings(record.id)) existing.add(spelling);
1189
+ } catch (error) {
1190
+ for (const id of chunk) unverifiable.add(id);
1191
+ report.skippedTypes.push({
1192
+ type,
1193
+ reason: `querying ${type} failed (${error instanceof Error ? error.message : String(error)}) — records that cannot be checked are not deleted ones.`
1194
+ });
1195
+ }
1196
+ }
1197
+ for (const row of group) {
1198
+ const stored = String(row.attachableId);
1199
+ if (unverifiable.has(stored)) continue;
1200
+ if (idSpellings(stored).some((spelling) => existing.has(spelling))) continue;
1201
+ orphans.push(row);
1202
+ report.orphanRows.push({
1203
+ id: String(row.id),
1204
+ attachableType: type,
1205
+ attachableId: stored
1206
+ });
1207
+ }
1208
+ }
1209
+ if (!options.dryRun && orphans.length > 0) await this.purgeRows(orphans);
1210
+ if (options.objects) await this.pruneOrphanObjects(rows, orphans, report, options.dryRun === true);
1211
+ return report;
1212
+ }
1213
+ /** With `--objects`: storage prefixes under `attachments/` that no surviving row references. */
1214
+ async pruneOrphanObjects(rows, removedRows, report, dryRun) {
1215
+ const removed = new Set(removedRows.map((row) => String(row.id)));
1216
+ const liveIds = new Set(rows.map((row) => String(row.id)).filter((id) => !removed.has(id)));
1217
+ let registered = [];
1218
+ try {
1219
+ registered = this.storage().getDiskNames();
1220
+ } catch {}
1221
+ const diskNames = /* @__PURE__ */ new Set([
1222
+ ...registered,
1223
+ this.defaultDisk,
1224
+ ...Object.keys(this.diskVisibility),
1225
+ ...rows.map((row) => String(row.disk))
1226
+ ]);
1227
+ for (const diskName of diskNames) {
1228
+ let prefixes;
1229
+ let disk;
1230
+ try {
1231
+ disk = this.storage().disk(diskName);
1232
+ prefixes = await disk.directories("attachments");
1233
+ } catch (error) {
1234
+ report.skippedDisks.push({
1235
+ disk: diskName,
1236
+ reason: error instanceof Error ? error.message : String(error)
1237
+ });
1238
+ continue;
1239
+ }
1240
+ for (const prefix of prefixes) {
1241
+ const id = prefix.split("/").pop() ?? prefix;
1242
+ if (liveIds.has(id)) continue;
1243
+ const mintedAt = ulidTime(id);
1244
+ if (mintedAt !== null && Date.now() - mintedAt < PRUNE_OBJECTS_GRACE_MS) continue;
1245
+ report.orphanObjectPrefixes.push({
1246
+ disk: diskName,
1247
+ prefix
1248
+ });
1249
+ if (!dryRun) try {
1250
+ await disk.deleteDirectory(prefix);
1251
+ } catch (error) {
1252
+ report.skippedDisks.push({
1253
+ disk: diskName,
1254
+ reason: `deleting ${prefix} failed: ${error instanceof Error ? error.message : String(error)}`
1255
+ });
1256
+ }
1257
+ }
1258
+ }
1259
+ }
1260
+ visibilityOf(diskName) {
1261
+ return this.diskVisibility[diskName] ?? "public";
1262
+ }
1263
+ async urlFor(diskName, path) {
1264
+ const disk = this.storage().disk(diskName);
1265
+ if (this.visibilityOf(diskName) === "private") return disk.temporaryUrl(path, new Date(Date.now() + this.urlExpiresIn));
1266
+ return disk.url(path);
1267
+ }
1268
+ async toData(row, spec) {
1269
+ const originalUrl = await this.urlFor(row.disk, row.path);
1270
+ const variants = {};
1271
+ for (const name of Object.keys(spec.variants ?? {})) {
1272
+ const entry = row.variants?.[name];
1273
+ if (entry?.status === "ready" && entry.path) variants[name] = {
1274
+ url: await this.urlFor(row.disk, entry.path),
1275
+ width: entry.width ?? null,
1276
+ height: entry.height ?? null
1277
+ };
1278
+ else variants[name] = {
1279
+ url: originalUrl,
1280
+ width: null,
1281
+ height: null
1282
+ };
1283
+ }
1284
+ return {
1285
+ id: row.id,
1286
+ collection: row.collection,
1287
+ name: row.name,
1288
+ contentType: row.contentType,
1289
+ size: row.size,
1290
+ width: row.width,
1291
+ height: row.height,
1292
+ url: originalUrl,
1293
+ placeholder: row.placeholder,
1294
+ variants
1295
+ };
1296
+ }
1297
+ toRecord(row) {
1298
+ return {
1299
+ id: String(row.id),
1300
+ attachableType: String(row.attachableType),
1301
+ attachableId: String(row.attachableId),
1302
+ collection: String(row.collection),
1303
+ disk: String(row.disk),
1304
+ path: String(row.path),
1305
+ name: String(row.name),
1306
+ contentType: String(row.contentType),
1307
+ size: Number(row.size),
1308
+ width: row.width == null ? null : Number(row.width),
1309
+ height: row.height == null ? null : Number(row.height),
1310
+ variants: row.variants == null ? null : decodeJsonColumn(row.variants, {}),
1311
+ placeholder: row.placeholder == null ? null : String(row.placeholder),
1312
+ createdAt: toDate(row.createdAt) ?? /* @__PURE__ */ new Date(0),
1313
+ updatedAt: toDate(row.updatedAt) ?? /* @__PURE__ */ new Date(0)
1314
+ };
1315
+ }
1316
+ };
1317
+ let activeEngine = null;
1318
+ /** Install the engine `configureAttachments()` built. Last call wins; `null` unconfigures (tests). */
1319
+ function setActiveAttachmentEngine(engine) {
1320
+ activeEngine = engine;
1321
+ }
1322
+ function resolveAttachmentEngine(caller) {
1323
+ if (!activeEngine) throw new Error(`${caller} requires attachments to be configured. Call configureAttachments({ table, storage, disk }) once at boot (e.g. in config/attachments.ts) before using the attachment statics.`);
1324
+ return activeEngine;
1325
+ }
1326
+ async function normalizeSource(source, nameOverride) {
1327
+ if (source instanceof Uint8Array) return {
1328
+ bytes: source,
1329
+ name: sanitizeFilename(nameOverride ?? "file"),
1330
+ declaredContentType: null
1331
+ };
1332
+ if (typeof Blob !== "undefined" && source instanceof Blob) {
1333
+ const bytes = new Uint8Array(await source.arrayBuffer());
1334
+ const fileName = "name" in source && typeof source.name === "string" ? source.name : void 0;
1335
+ return {
1336
+ bytes,
1337
+ name: sanitizeFilename(nameOverride ?? fileName ?? "file"),
1338
+ declaredContentType: source.type || null
1339
+ };
1340
+ }
1341
+ throw new TypeError("attach() accepts bytes only (File, Blob, or Uint8Array). Filesystem path strings are not supported.");
1342
+ }
1343
+ /**
1344
+ * Filenames become part of the object key, so they must not steer it: no
1345
+ * path separators, no control characters, never empty or dot-only.
1346
+ */
1347
+ function sanitizeFilename(name) {
1348
+ const cleaned = (name.split(/[/\\]/).pop() ?? "").replace(/[\u0000-\u001f\u007f]/g, "").trim().slice(0, 200);
1349
+ if (cleaned === "" || /^\.+$/.test(cleaned)) return "file";
1350
+ return cleaned;
1351
+ }
1352
+ function replaceExtension(name, extension) {
1353
+ const stem = name.replace(/\.[^.]*$/, "");
1354
+ return `${stem === "" ? "file" : stem}.${extension}`;
1355
+ }
1356
+ function errorCode(error) {
1357
+ if (error && typeof error === "object" && "code" in error) {
1358
+ const code = error.code;
1359
+ return typeof code === "string" ? code : void 0;
1360
+ }
1361
+ }
1362
+ /** ULIDs sort lexicographically by creation time; compare code units, not locales. */
1363
+ function sortById(rows) {
1364
+ return [...rows].sort((a, b) => {
1365
+ const left = String(a.id);
1366
+ const right = String(b.id);
1367
+ if (left < right) return -1;
1368
+ if (left > right) return 1;
1369
+ return 0;
1370
+ });
1371
+ }
1372
+ //#endregion
1373
+ //#region src/attachments/Attachable.ts
1374
+ /**
1375
+ * Mixin that declares attachment collections on a model (RFC 0013). The
1376
+ * declaration is a static argument in the class heritage clause, so it is
1377
+ * statically readable (the same property `guren check` and `guren context`
1378
+ * rely on for the model's other surfaces), and its collection names, kinds,
1379
+ * and variant names are inferred as compile-time facts.
1380
+ *
1381
+ * Composes with other mixins the way `SoftDeletes` does.
1382
+ *
1383
+ * @example
1384
+ * import { Attachable, hasOneAttached, hasManyAttached } from '@guren/core'
1385
+ *
1386
+ * export class Post extends Attachable(defineModel(posts), {
1387
+ * cover: hasOneAttached({
1388
+ * image: 'require',
1389
+ * variants: { thumb: { width: 320 }, og: { width: 1200 } },
1390
+ * }),
1391
+ * images: hasManyAttached({ image: 'require' }),
1392
+ * draftPdf: hasOneAttached(),
1393
+ * }) {}
1394
+ *
1395
+ * // Later, anywhere:
1396
+ * await Post.attach(post.id, 'cover', await this.file('cover'))
1397
+ * const [withCover] = await Post.withAttachments([post], ['cover'])
1398
+ * const url = await Post.attachmentUrl(post, 'cover', { variant: 'thumb' })
1399
+ */
1400
+ function Attachable(Base, declaration) {
1401
+ const AttachableModel = class extends Base {};
1402
+ const decl = declaration;
1403
+ Object.assign(AttachableModel, {
1404
+ attachments: declaration,
1405
+ attach(recordId, collection, source, options) {
1406
+ return resolveAttachmentEngine(`${this.name}.attach()`).attach(this, decl, recordId, collection, source, options);
1407
+ },
1408
+ detach(recordId, collection, attachmentId) {
1409
+ return resolveAttachmentEngine(`${this.name}.detach()`).detach(this, decl, recordId, collection, attachmentId);
1410
+ },
1411
+ withAttachments(records, names) {
1412
+ return resolveAttachmentEngine(`${this.name}.withAttachments()`).withAttachments(this, decl, records, names);
1413
+ },
1414
+ attachmentUrl(record, collection, options) {
1415
+ return resolveAttachmentEngine(`${this.name}.attachmentUrl()`).attachmentUrl(this, decl, record, collection, options);
1416
+ },
1417
+ purgeAttachments(recordId) {
1418
+ return resolveAttachmentEngine(`${this.name}.purgeAttachments()`).purgeAttachments(this, recordId);
1419
+ }
1420
+ });
1421
+ return AttachableModel;
1422
+ }
1423
+ //#endregion
1424
+ //#region src/attachments/generate-variants-job.ts
1425
+ /**
1426
+ * Queue job behind `attach(..., { queued: true })` (RFC 0013 Part 2): runs
1427
+ * the deferred full decode, converts HEIC originals where the collection
1428
+ * opted in, and generates the declared variants, flipping their `pending`
1429
+ * status records to `ready`/`failed`.
1430
+ *
1431
+ * `configureAttachments()` registers this job, so any worker process that
1432
+ * boots the app's config can process it. The worker is where the image
1433
+ * work happens — point it at a runtime with an image processor (Bun with
1434
+ * `Bun.Image`, or a custom `configureAttachments({ processor })`), or every
1435
+ * variant settles as `unavailable`.
1436
+ */
1437
+ var GenerateVariantsJob = class extends Job {
1438
+ /**
1439
+ * Pinned wire name: queued messages must survive bundler identifier
1440
+ * mangling and any future rename of this class.
1441
+ */
1442
+ static jobName = "GenerateVariantsJob";
1443
+ async handle(payload) {
1444
+ await resolveAttachmentEngine("GenerateVariantsJob").generateVariants(payload);
1445
+ }
1446
+ /**
1447
+ * After the last retry, stop `pending` variants from looking in-flight
1448
+ * forever — their URLs already fall back to the original either way.
1449
+ */
1450
+ async failed(payload, _error) {
1451
+ try {
1452
+ await resolveAttachmentEngine("GenerateVariantsJob").markDeferredFailed(payload.attachmentId);
1453
+ } catch {}
1454
+ }
300
1455
  };
1456
+ //#endregion
1457
+ //#region src/attachments/configure.ts
1458
+ /**
1459
+ * Wire the attachments layer, once per app (the `DatabaseSessionStore`
1460
+ * precedent: the app owns the table, the framework returns the model).
1461
+ * The attachment statics on `Attachable` models resolve this configuration
1462
+ * lazily and throw a clear error when it was never called.
1463
+ *
1464
+ * @example
1465
+ * ```ts
1466
+ * // config/attachments.ts
1467
+ * import { configureAttachments } from '@guren/core'
1468
+ * import { attachments } from '@/db/schema'
1469
+ *
1470
+ * export const { Attachment } = configureAttachments({
1471
+ * table: attachments,
1472
+ * storage: () => container.make('storage'),
1473
+ * disk: 'media',
1474
+ * })
1475
+ * ```
1476
+ */
1477
+ function configureAttachments(options) {
1478
+ const engine = new AttachmentEngine(options);
1479
+ engine.setJobDispatcher((payload) => GenerateVariantsJob.dispatch(payload));
1480
+ registerJob(GenerateVariantsJob);
1481
+ setActiveAttachmentEngine(engine);
1482
+ return { Attachment: engine.model };
1483
+ }
1484
+ //#endregion
1485
+ //#region src/attachments/prune-command.ts
1486
+ /**
1487
+ * Console sweeper for the attachments layer (RFC 0013 §8). The polymorphic
1488
+ * `attachableType`/`attachableId` pair cannot carry a foreign key, so no
1489
+ * database cascade exists; deletion is explicit (`purgeAttachments()` in
1490
+ * destroy actions) plus this sweep for whatever slipped past it — records
1491
+ * deleted through paths that never purged, and, with `--objects`, storage
1492
+ * prefixes left behind by crashed or raced jobs.
1493
+ *
1494
+ * Register it in the app's console kernel:
1495
+ *
1496
+ * ```ts
1497
+ * // src/console.ts
1498
+ * import { AttachmentsPruneCommand } from '@guren/core'
1499
+ * kernel.register(AttachmentsPruneCommand)
1500
+ * ```
1501
+ *
1502
+ * Orphan rows are detected by resolving each `attachableType` through
1503
+ * `Model.morphMap` and querying for the records — set
1504
+ * `Model.morphMap = { Post, User, ... }` for every model that declares
1505
+ * attachments, or their rows are reported as unverifiable and left alone.
1506
+ */
1507
+ var AttachmentsPruneCommand = class extends Command {
1508
+ static signature = "attachments:prune {--objects : Also delete attachments/ storage prefixes that no row references} {--dry-run : Report what would be removed without deleting}";
1509
+ static description = "Remove attachment rows whose owning record no longer exists";
1510
+ async handle() {
1511
+ const engine = resolveAttachmentEngine("attachments:prune");
1512
+ const dryRun = this.hasOption("dry-run");
1513
+ const objects = this.hasOption("objects");
1514
+ const report = await engine.pruneOrphans({
1515
+ objects,
1516
+ dryRun
1517
+ });
1518
+ const verb = dryRun ? "would be removed" : "removed";
1519
+ this.info(`Scanned ${report.scannedRows} attachment row(s).`);
1520
+ if (report.orphanRows.length === 0) this.info("No orphaned rows.");
1521
+ else {
1522
+ this.info(`${report.orphanRows.length} orphaned row(s) ${verb}:`);
1523
+ for (const row of report.orphanRows) this.line(` ${row.id} (${row.attachableType}#${row.attachableId})`);
1524
+ }
1525
+ for (const skipped of report.skippedTypes) this.warn(`Skipped '${skipped.type}': ${skipped.reason}`);
1526
+ if (objects) {
1527
+ if (report.orphanObjectPrefixes.length === 0) this.info("No orphaned storage prefixes.");
1528
+ else {
1529
+ this.info(`${report.orphanObjectPrefixes.length} orphaned storage prefix(es) ${verb}:`);
1530
+ for (const orphan of report.orphanObjectPrefixes) this.line(` ${orphan.disk}: ${orphan.prefix}`);
1531
+ }
1532
+ for (const skipped of report.skippedDisks) this.warn(`Skipped disk '${skipped.disk}': ${skipped.reason}`);
1533
+ }
1534
+ if (dryRun) this.info("Dry run: nothing was deleted.");
1535
+ else this.success("Prune complete.");
1536
+ }
1537
+ };
1538
+ //#endregion
1539
+ //#region src/attachments/declaration.ts
1540
+ function buildSpec(kind, options) {
1541
+ const hasVariants = options.variants !== void 0 && Object.keys(options.variants).length > 0;
1542
+ if (options.image === "forbid" && hasVariants) throw new Error("Attachment collections with variants cannot set image: 'forbid' — variant generation requires decodable image input.");
1543
+ const image = options.image ?? (hasVariants ? "require" : void 0);
1544
+ const spec = { kind };
1545
+ if (image !== void 0) spec.image = image;
1546
+ if (options.accepts !== void 0) spec.accepts = options.accepts;
1547
+ if (options.variants !== void 0) spec.variants = options.variants;
1548
+ return spec;
1549
+ }
1550
+ /**
1551
+ * Declare a single-attachment collection (`attach` replaces the previous
1552
+ * attachment, purging its row and objects).
1553
+ *
1554
+ * @example
1555
+ * export class Post extends Attachable(defineModel(posts), {
1556
+ * cover: hasOneAttached({
1557
+ * image: 'require',
1558
+ * variants: { thumb: { width: 320 }, og: { width: 1200 } },
1559
+ * }),
1560
+ * draftPdf: hasOneAttached(), // opaque bytes; width/height/placeholder null
1561
+ * }) {}
1562
+ */
1563
+ function hasOneAttached(options = {}) {
1564
+ return buildSpec("one", options);
1565
+ }
1566
+ /**
1567
+ * Declare a multi-attachment collection (`attach` appends).
1568
+ *
1569
+ * @example
1570
+ * export class Post extends Attachable(defineModel(posts), {
1571
+ * images: hasManyAttached({ image: 'require' }),
1572
+ * }) {}
1573
+ */
1574
+ function hasManyAttached(options = {}) {
1575
+ return buildSpec("many", options);
1576
+ }
1577
+ //#endregion
1578
+ export { Attachable, AttachmentsPruneCommand, DatabaseApiTokenStore, DatabaseOAuthStateStore, DatabaseSessionStore, DrizzleAdapter, GenerateVariantsJob, MassAssignmentException, Model, ModelNotFoundException, QueryBuilder, SoftDeletes, configureAttachments, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, hasManyAttached, hasOneAttached, runSeeders };