@guren/core 1.17.0 → 1.18.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,4 +1,4 @@
1
- import { ApiToken, ApiTokenStore, Command, Controller, Job, OAuthStatePayload, OAuthStateStore, Router, SessionConfig, SessionData, SessionManager, SessionStore, StorageManager } from "@guren/server";
1
+ import { ApiToken, ApiTokenStore, Command, Container, Controller, Job, OAuthStatePayload, OAuthStateStore, QueueManager, Router, SessionConfig, SessionData, SessionManager, SessionStore, StorageManager } from "@guren/server";
2
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
3
  export * from "@guren/server";
4
4
  //#region src/api-token-store.d.ts
@@ -337,6 +337,12 @@ interface AttachOptions {
337
337
  */
338
338
  queued?: boolean;
339
339
  }
340
+ declare module '@guren/server' {
341
+ interface ServiceBindings {
342
+ /** Bound by `AttachmentEngine.bindTo()` (RFC 0023 §4); absent until then. The runtime spelling lives in `ATTACHMENTS_BINDING` — rename here and there together. */
343
+ attachments: AttachmentEngine;
344
+ }
345
+ }
340
346
  interface ConfigureAttachmentsOptions {
341
347
  /**
342
348
  * The app's Drizzle `attachments` table. Column property names must match the
@@ -345,8 +351,12 @@ interface ConfigureAttachmentsOptions {
345
351
  * `variants` (JSON-capable), `placeholder`, `createdAt`, `updatedAt`.
346
352
  */
347
353
  table: unknown;
348
- /** The app's StorageManager, resolved lazily (e.g. `() => container.make('storage')`). */
349
- storage: () => StorageManager;
354
+ /**
355
+ * The app's StorageManager, resolved lazily: `(container) => container.make('storage')`.
356
+ * The container is the one `bindTo()` was given, else the default
357
+ * application's (RFC 0023 §4).
358
+ */
359
+ storage: (container: Container) => StorageManager;
350
360
  /** Default disk name for new attachments. */
351
361
  disk: string;
352
362
  /**
@@ -382,10 +392,9 @@ interface ConfigureAttachmentsOptions {
382
392
  processor?: ImageProcessor | null;
383
393
  /**
384
394
  * The app's QueueManager, resolved lazily; enables `attach(..., { queued })`.
385
- * Materializing its default driver installs that driver process-wide, so pass
386
- * the same manager the rest of the app dispatches through — a second one would
387
- * redirect every later `Job.dispatch()`. Without this option, `queued: true`
388
- * falls back to the globally configured driver.
395
+ * Variant generation is dispatched through it, so the job lands on its driver
396
+ * whatever else the process has resolved. Without this option, the default
397
+ * application's queue carries the job.
389
398
  */
390
399
  queue?: () => unknown;
391
400
  /**
@@ -484,6 +493,138 @@ interface PruneReport {
484
493
  reason: string;
485
494
  }>;
486
495
  }
496
+ /** What `configureAttachments({ queue })` must resolve to: the `QueueManager` surface the engine dispatches through. */
497
+ type QueueDispatcher = Pick<QueueManager, 'driver' | 'dispatch'>;
498
+ /** Installed by `configureAttachments()`; `queue` is the engine's own manager when it has one. */
499
+ type JobDispatcher = (payload: GenerateVariantsPayload, queue: QueueDispatcher | undefined) => Promise<unknown>;
500
+ declare class AttachmentEngine {
501
+ readonly model: typeof Model$1;
502
+ private readonly storageFactory;
503
+ private container?;
504
+ private readonly defaultDisk;
505
+ private readonly diskDelivery;
506
+ private readonly delivery;
507
+ private deliveryKeys;
508
+ private readonly maxPixels;
509
+ private readonly maxImageBytes;
510
+ private readonly processor;
511
+ private readonly urlExpiresIn;
512
+ private readonly queue?;
513
+ private dispatchJob;
514
+ constructor(options: ConfigureAttachmentsOptions);
515
+ /**
516
+ * Bind this engine on `container` as `attachments` *and* resolve its storage
517
+ * there. One call rather than two: an app that bound the instance alone would
518
+ * still read storage from whichever app is the default (RFC 0023 §4).
519
+ */
520
+ bindTo(container: Container): void;
521
+ /** Wired by `configureAttachments()`, so this module never imports the job. */
522
+ setJobDispatcher(dispatch: JobDispatcher): void;
523
+ private storage;
524
+ attach(model: typeof Model$1, declaration: AttachmentsDeclaration, recordId: string | number, collection: string, source: AttachmentSource, options?: AttachOptions): Promise<AttachmentRecord>;
525
+ detach(model: typeof Model$1, declaration: AttachmentsDeclaration, recordId: string | number, collection: string, attachmentId?: string): Promise<void>;
526
+ withAttachments(model: typeof Model$1, declaration: AttachmentsDeclaration, records: readonly PlainObject$1[], names: readonly string[]): Promise<PlainObject$1[]>;
527
+ attachmentUrl(model: typeof Model$1, declaration: AttachmentsDeclaration, recordOrId: PlainObject$1 | string | number, collection: string, options?: AttachmentUrlOptions & {
528
+ variant?: string;
529
+ }): Promise<string | null>;
530
+ purgeAttachments(model: typeof Model$1, recordId: string | number): Promise<void>;
531
+ private specFor;
532
+ /**
533
+ * The three-gate image pipeline (RFC 0013 §6): encoded-byte cap, header
534
+ * dimensions, full decode. The first two plus the HEIC signature rejection are
535
+ * pure JS; only the full decode needs a processor.
536
+ */
537
+ private inspectImage;
538
+ /**
539
+ * Seed one entry per *declared* variant, generating inline where a processor
540
+ * exists. Recording declared names is what lets `attachmentUrl()` tell "not
541
+ * yet generated" from "never declared" after a reload.
542
+ */
543
+ private buildVariants;
544
+ /**
545
+ * Worker-side completion of a deferred attach: the skipped full decode, any
546
+ * opted-in HEIC conversion, the declared variants, and settling every
547
+ * `pending` record. A row or object purged meanwhile is nothing to do.
548
+ */
549
+ generateVariants(payload: GenerateVariantsPayload): Promise<void>;
550
+ /** `GenerateVariantsJob.failed()`: settle `pending` records after the last retry. */
551
+ markDeferredFailed(attachmentId: string): Promise<void>;
552
+ /**
553
+ * Flip every `pending` variant to a terminal status. Works on a *fresh* read
554
+ * of the row: under at-least-once delivery a duplicate execution holding a
555
+ * stale copy would clobber variants a completed run already marked `ready`.
556
+ */
557
+ private settleDeferred;
558
+ /**
559
+ * The manager `configureAttachments({ queue })` resolves, validated, or
560
+ * undefined without the option (the default application's queue then
561
+ * carries the job). Dispatching through the manager itself keeps the job on
562
+ * this engine's driver whatever another manager in the process resolved.
563
+ */
564
+ private queueManager;
565
+ private dispatchGeneration;
566
+ /**
567
+ * The single indexed query behind `withAttachments()`. Empty `records` or
568
+ * `names` short-circuits: either would send an empty `IN ()` to the adapter.
569
+ */
570
+ private rowsForPage;
571
+ private rowsFor;
572
+ /**
573
+ * Objects first, rows after (RFC 0013 §8): a crash between the two leaves a
574
+ * row pointing at nothing, which the next `url()` surfaces loudly. The reverse
575
+ * leaves orphaned objects only a bucket audit finds.
576
+ */
577
+ private purgeRows;
578
+ /**
579
+ * The sweeper behind `attachments:prune` (RFC 0013 §8): no DB cascade exists
580
+ * for a polymorphic pair. Rows are removed only on *positive* evidence the
581
+ * record is gone; anything unverifiable is reported and left alone.
582
+ */
583
+ pruneOrphans(options?: PruneOptions): Promise<PruneReport>;
584
+ /** With `--objects`: storage prefixes under `attachments/` that no surviving row references. */
585
+ private pruneOrphanObjects;
586
+ private visibilityOf;
587
+ private serveModeFor;
588
+ /** Whether URL minting for this disk goes through the delivery route (`serve: 'direct'` opts out). */
589
+ private routeEnabledFor;
590
+ /** The normalized delivery route config, for `resolveDeliveryRoute()`. */
591
+ get deliveryRoute(): {
592
+ prefix: string;
593
+ routeName: string;
594
+ } | null;
595
+ private deliveryKeyring;
596
+ /**
597
+ * The one URL policy (RFC 0015 §7): public disks stay on `disk.url()`; private
598
+ * disks get signed route URLs when `delivery` is configured and the disk did
599
+ * not opt out with `serve: 'direct'`, else v1's `temporaryUrl()`.
600
+ */
601
+ private usesDeliveryRoute;
602
+ /**
603
+ * The one variant-resolution rule (RFC 0013 §7 / RFC 0015 §1), shared by URL
604
+ * minting, resource payloads, and the delivery route. A `ready` entry resolves
605
+ * to the variant's key and *format-derived* MIME type — variants are
606
+ * transcoded, and serving them under the original's type with `nosniff` would
607
+ * be self-sabotage. Anything else falls back to the original.
608
+ */
609
+ private resolveVariantTarget;
610
+ private urlForRow;
611
+ /**
612
+ * Path-relative: the `Host` header never participates in URL construction (RFC
613
+ * 0015 T6). The variant rides as a signed query parameter resolved at *serve*
614
+ * time, so the same URL starts serving it once generation completes.
615
+ */
616
+ private signDeliveryUrl;
617
+ /**
618
+ * Serve one delivery-route request (RFC 0015 §1). Every failure is the same
619
+ * 404: invalid signature, expired URL, and unknown id stay indistinguishable.
620
+ * Takes the raw `Request` so each parameter is re-read from the *same*
621
+ * `URLSearchParams` parse the signature canonicalizes with; a route decoder
622
+ * disagrees on malformed percent-encoding, a signed-URL rewrite primitive.
623
+ */
624
+ handleDeliveryRequest(request: Request): Promise<Response>;
625
+ private toData;
626
+ private toRecord;
627
+ }
487
628
  //#endregion
488
629
  //#region src/attachments/Attachable.d.ts
489
630
  /** A record id accepted by the attachment statics (int and uuid/text PKs). */
@@ -577,13 +718,19 @@ interface ConfiguredAttachments {
577
718
  * attachment vocabulary.
578
719
  */
579
720
  Attachment: typeof Model$1;
721
+ /**
722
+ * The engine this call built. Hand it to the app's container from a service
723
+ * provider (`engine.bindTo(this.container)`): this function runs at module
724
+ * scope, where no `Application` exists yet (RFC 0023 §4).
725
+ */
726
+ engine: AttachmentEngine;
580
727
  }
581
728
  /**
582
729
  * Wire the attachments layer, once per app: the app owns the table, the
583
730
  * framework returns the model. `Attachable` statics resolve this lazily and
584
731
  * throw a clear error when it was never called.
585
732
  * @example
586
- * export const { Attachment } = configureAttachments({ table: attachments, storage: () => container.make('storage'), disk: 'media' })
733
+ * export const { Attachment, engine } = configureAttachments({ table: attachments, storage: (container) => container.make('storage'), disk: 'media' })
587
734
  */
588
735
  declare function configureAttachments(options: ConfigureAttachmentsOptions): ConfiguredAttachments;
589
736
  //#endregion
@@ -632,9 +779,11 @@ declare class AttachmentsPruneCommand extends Command {
632
779
  declare class GenerateVariantsJob extends Job<GenerateVariantsPayload> {
633
780
  /** Pinned: queued messages must survive identifier mangling and renames. */
634
781
  static jobName: string;
782
+ /** The app whose queue the worker drains, which a worker serving two is not free to guess. */
783
+ private engine;
635
784
  handle(payload: GenerateVariantsPayload): Promise<void>;
636
785
  /** After the last retry, stop `pending` variants looking in-flight forever. */
637
786
  failed(payload: GenerateVariantsPayload, _error: Error): Promise<void>;
638
787
  }
639
788
  //#endregion
640
- export { ATTACHMENT_OBJECT_PREFIX, type AccessorDefinitions, type AccessorFn, type AttachOptions, Attachable, type AttachableRecordId, type AttachableStatic, type AttachedCollectionOptions, type AttachmentCollectionSpec, type AttachmentData, AttachmentDeliveryController, type AttachmentRecord, type AttachmentSource, type AttachmentUrlOptions, 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, DEFAULT_DELIVERY_ROUTE_NAME, DatabaseApiTokenStore, type DatabaseApiTokenStoreOptions, DatabaseOAuthStateStore, type DatabaseSessionDriverOptions, DatabaseSessionStore, type DatabaseSessionStoreOptions, type DeliveryOptions, type DeliveryServeMode, type DiskDeliveryConfig, 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, SessionsPruneCommand, 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, createSessionManager, createSqliteDatabase, defineModel, defineSeeder, hasManyAttached, hasOneAttached, registerAttachmentRoutes, registerDatabaseSessionDriver, runSeeders };
789
+ export { ATTACHMENT_OBJECT_PREFIX, type AccessorDefinitions, type AccessorFn, type AttachOptions, Attachable, type AttachableRecordId, type AttachableStatic, type AttachedCollectionOptions, type AttachmentCollectionSpec, type AttachmentData, AttachmentDeliveryController, type AttachmentEngine, type AttachmentRecord, type AttachmentSource, type AttachmentUrlOptions, 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, DEFAULT_DELIVERY_ROUTE_NAME, DatabaseApiTokenStore, type DatabaseApiTokenStoreOptions, DatabaseOAuthStateStore, type DatabaseSessionDriverOptions, DatabaseSessionStore, type DatabaseSessionStoreOptions, type DeliveryOptions, type DeliveryServeMode, type DiskDeliveryConfig, 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, SessionsPruneCommand, 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, createSessionManager, createSqliteDatabase, defineModel, defineSeeder, hasManyAttached, hasOneAttached, registerAttachmentRoutes, registerDatabaseSessionDriver, runSeeders };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { Command, Controller, HttpException, Job, SessionManager, ValidationException, deriveAppKeyring, getAppKeyringFromEnv, getQueueDriver, registerJob, setQueueDriver, signUrl, verifySignedUrl } from "@guren/server";
1
+ import { Command, Controller, HttpException, Job, SessionManager, ValidationException, ambientBinding, ambientContainer, deriveAppKeyring, getAppKeyringFromEnv, registerJob, resolveQueueDriver, signUrl, tryGetRequestContainer, verifySignedUrl } from "@guren/server";
2
2
  import { DrizzleAdapter, MassAssignmentException, Model, Model as Model$1, ModelNotFoundException, QueryBuilder, SoftDeletes, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, runSeeders } from "@guren/orm";
3
3
  import { isExpired, toDate, toOptionalExpiry } from "@guren/server/support/expiry";
4
4
  import { createHash } from "node:crypto";
@@ -595,6 +595,14 @@ function ulid(now = Date.now()) {
595
595
  * copy there would stop matching when this moves and report an exposed app safe.
596
596
  */
597
597
  const ATTACHMENT_OBJECT_PREFIX = "attachments";
598
+ /**
599
+ * The key the engine binds under, and the one every consumer holding a
600
+ * container reads before falling back (RFC 0023 §4). Its own constant because
601
+ * the word means three unrelated things here (this key, the object-key prefix
602
+ * above, the route's URL prefix), and because `Container.instance()` is
603
+ * unkeyed: a typo would compile and read back as an absent binding.
604
+ */
605
+ const ATTACHMENTS_BINDING = "attachments";
598
606
  const DEFAULT_DELIVERY_ROUTE_NAME = "attachments.show";
599
607
  /**
600
608
  * The inner (presigned) TTL behind a redirect. Fixed, not derived from
@@ -650,9 +658,25 @@ const VARIANT_EXTENSION = {
650
658
  webp: "webp",
651
659
  avif: "avif"
652
660
  };
661
+ /**
662
+ * What a storage factory receives when no Application exists at all: a
663
+ * factory that ignores its argument (`() => storage`) keeps working, and one
664
+ * that reads it gets the error `getContainer()` would have thrown.
665
+ */
666
+ function unavailableContainer() {
667
+ const unavailable = () => {
668
+ throw new Error("Container not initialized. Construct the app with createApp(), or bind the engine on one from a provider (attachmentEngine.bindTo(this.container)).");
669
+ };
670
+ return {
671
+ make: unavailable,
672
+ makeOptional: unavailable,
673
+ has: unavailable
674
+ };
675
+ }
653
676
  var AttachmentEngine = class {
654
677
  model;
655
- storage;
678
+ storageFactory;
679
+ container;
656
680
  defaultDisk;
657
681
  diskDelivery;
658
682
  delivery;
@@ -669,7 +693,7 @@ var AttachmentEngine = class {
669
693
  static table = table;
670
694
  };
671
695
  this.model.morphTo("attachable", "attachable");
672
- this.storage = options.storage;
696
+ this.storageFactory = options.storage;
673
697
  this.defaultDisk = options.disk;
674
698
  this.diskDelivery = normalizeDiskDelivery(options.disks ?? {});
675
699
  this.delivery = options.delivery ? {
@@ -682,15 +706,27 @@ var AttachmentEngine = class {
682
706
  this.urlExpiresIn = options.urlExpiresIn ?? DEFAULT_URL_EXPIRES_IN;
683
707
  this.queue = options.queue;
684
708
  }
709
+ /**
710
+ * Bind this engine on `container` as `attachments` *and* resolve its storage
711
+ * there. One call rather than two: an app that bound the instance alone would
712
+ * still read storage from whichever app is the default (RFC 0023 §4).
713
+ */
714
+ bindTo(container) {
715
+ this.container = container;
716
+ container.instance(ATTACHMENTS_BINDING, this);
717
+ }
685
718
  /** Wired by `configureAttachments()`, so this module never imports the job. */
686
719
  setJobDispatcher(dispatch) {
687
720
  this.dispatchJob = dispatch;
688
721
  }
722
+ storage() {
723
+ return this.storageFactory(this.container ?? ambientContainer() ?? unavailableContainer());
724
+ }
689
725
  async attach(model, declaration, recordId, collection, source, options = {}) {
690
726
  const spec = this.specFor(model, declaration, collection);
691
727
  const normalized = await normalizeSource(source, options.name);
692
728
  const queued = options.queued === true;
693
- if (queued) this.ensureQueueDispatchable();
729
+ if (queued) this.queueManager();
694
730
  const inspection = await this.inspectImage(spec, collection, normalized, queued);
695
731
  const id = ulid();
696
732
  const name = inspection.name;
@@ -1024,22 +1060,23 @@ var AttachmentEngine = class {
1024
1060
  await this.model.forceUpdate({ id: row.id }, updates);
1025
1061
  }
1026
1062
  /**
1027
- * The configured QueueManager's default driver, or with no `queue` option
1028
- * whatever driver the app has already booted globally.
1063
+ * The manager `configureAttachments({ queue })` resolves, validated, or
1064
+ * undefined without the option (the default application's queue then
1065
+ * carries the job). Dispatching through the manager itself keeps the job on
1066
+ * this engine's driver whatever another manager in the process resolved.
1029
1067
  */
1030
- ensureQueueDispatchable() {
1068
+ queueManager() {
1031
1069
  if (!this.dispatchJob) throw new Error("Attachments queue dispatch is not wired. Call configureAttachments() before attaching.");
1032
1070
  if (this.queue) {
1033
1071
  const manager = this.queue();
1034
- if (typeof manager?.driver !== "function") throw new Error("configureAttachments({ queue }) must resolve to a QueueManager (an object with a driver() method).");
1035
- setQueueDriver(manager.driver());
1036
- return;
1072
+ if (typeof manager?.driver !== "function" || typeof manager.dispatch !== "function") throw new Error("configureAttachments({ queue }) must resolve to a QueueManager (an object with driver() and dispatch() methods).");
1073
+ return manager;
1037
1074
  }
1038
- if (!getQueueDriver()) throw new Error("attach() with queued: true requires a queue. Pass configureAttachments({ queue: () => queueManager }) or boot the app's queue before attaching.");
1075
+ if (!resolveQueueDriver()) throw new Error("attach() with queued: true requires a queue. Pass configureAttachments({ queue: () => queueManager }) or boot the app's queue before attaching.");
1039
1076
  }
1040
1077
  async dispatchGeneration(payload) {
1041
- this.ensureQueueDispatchable();
1042
- await this.dispatchJob(payload);
1078
+ const queue = this.queueManager();
1079
+ await this.dispatchJob(payload, queue);
1043
1080
  }
1044
1081
  /**
1045
1082
  * The single indexed query behind `withAttachments()`. Empty `records` or
@@ -1369,7 +1406,12 @@ var AttachmentEngine = class {
1369
1406
  }
1370
1407
  };
1371
1408
  let activeEngine = null;
1372
- /** Install the engine `configureAttachments()` built. Last call wins; `null` unconfigures (tests). */
1409
+ /**
1410
+ * Install the engine `configureAttachments()` built. Last call wins; `null`
1411
+ * unconfigures (tests). Neither this nor its getter is exported from
1412
+ * `@guren/core`, so RFC 0023's deprecation window does not reach them: they go
1413
+ * with the slot in Part 3.
1414
+ */
1373
1415
  function setActiveAttachmentEngine(engine) {
1374
1416
  activeEngine = engine;
1375
1417
  }
@@ -1385,8 +1427,9 @@ function resolveDeliveryRoute() {
1385
1427
  };
1386
1428
  }
1387
1429
  function resolveAttachmentEngine(caller) {
1388
- 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.`);
1389
- return activeEngine;
1430
+ const engine = ambientBinding("attachments") ?? activeEngine;
1431
+ if (!engine) 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.`);
1432
+ return engine;
1390
1433
  }
1391
1434
  async function normalizeSource(source, nameOverride) {
1392
1435
  if (source instanceof Uint8Array) return {
@@ -1563,13 +1606,17 @@ function Attachable(Base, declaration) {
1563
1606
  var GenerateVariantsJob = class extends Job {
1564
1607
  /** Pinned: queued messages must survive identifier mangling and renames. */
1565
1608
  static jobName = "GenerateVariantsJob";
1609
+ /** The app whose queue the worker drains, which a worker serving two is not free to guess. */
1610
+ engine() {
1611
+ return this.makeOptional("attachments") ?? resolveAttachmentEngine("GenerateVariantsJob");
1612
+ }
1566
1613
  async handle(payload) {
1567
- await resolveAttachmentEngine("GenerateVariantsJob").generateVariants(payload);
1614
+ await this.engine().generateVariants(payload);
1568
1615
  }
1569
1616
  /** After the last retry, stop `pending` variants looking in-flight forever. */
1570
1617
  async failed(payload, _error) {
1571
1618
  try {
1572
- await resolveAttachmentEngine("GenerateVariantsJob").markDeferredFailed(payload.attachmentId);
1619
+ await this.engine().markDeferredFailed(payload.attachmentId);
1573
1620
  } catch {}
1574
1621
  }
1575
1622
  };
@@ -1580,14 +1627,17 @@ var GenerateVariantsJob = class extends Job {
1580
1627
  * framework returns the model. `Attachable` statics resolve this lazily and
1581
1628
  * throw a clear error when it was never called.
1582
1629
  * @example
1583
- * export const { Attachment } = configureAttachments({ table: attachments, storage: () => container.make('storage'), disk: 'media' })
1630
+ * export const { Attachment, engine } = configureAttachments({ table: attachments, storage: (container) => container.make('storage'), disk: 'media' })
1584
1631
  */
1585
1632
  function configureAttachments(options) {
1586
1633
  const engine = new AttachmentEngine(options);
1587
- engine.setJobDispatcher((payload) => GenerateVariantsJob.dispatch(payload));
1634
+ engine.setJobDispatcher((payload, queue) => queue ? queue.dispatch(GenerateVariantsJob, payload) : GenerateVariantsJob.dispatch(payload));
1588
1635
  registerJob(GenerateVariantsJob);
1589
1636
  setActiveAttachmentEngine(engine);
1590
- return { Attachment: engine.model };
1637
+ return {
1638
+ Attachment: engine.model,
1639
+ engine
1640
+ };
1591
1641
  }
1592
1642
  //#endregion
1593
1643
  //#region src/attachments/delivery.ts
@@ -1600,7 +1650,7 @@ function configureAttachments(options) {
1600
1650
  */
1601
1651
  var AttachmentDeliveryController = class extends Controller {
1602
1652
  async show() {
1603
- return resolveAttachmentEngine("The attachments delivery route").handleDeliveryRequest(this.ctx.req.raw);
1653
+ return (tryGetRequestContainer(this.ctx)?.makeOptional("attachments") ?? resolveAttachmentEngine("The attachments delivery route")).handleDeliveryRequest(this.ctx.req.raw);
1604
1654
  }
1605
1655
  };
1606
1656
  /**
@@ -1627,7 +1677,7 @@ var AttachmentsPruneCommand = class extends Command {
1627
1677
  static signature = "attachments:prune {--objects : Also delete attachments/ storage prefixes that no row references} {--dry-run : Report what would be removed without deleting}";
1628
1678
  static description = "Remove attachment rows whose owning record no longer exists";
1629
1679
  async handle() {
1630
- const engine = resolveAttachmentEngine("attachments:prune");
1680
+ const engine = this.resolveOptional("attachments") ?? resolveAttachmentEngine("attachments:prune");
1631
1681
  const dryRun = this.hasOption("dry-run");
1632
1682
  const objects = this.hasOption("objects");
1633
1683
  const report = await engine.pruneOrphans({
package/dist/redis.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { Redis, RedisApiTokenStore, RedisApiTokenStoreOptions, RedisClientOptions, RedisEmailVerificationStore, RedisEmailVerificationStoreOptions, RedisOAuthStateStore, RedisOAuthStateStoreOptions, RedisOptions, RedisPasswordResetStore, RedisPasswordResetStoreOptions, RedisRateLimitStore, RedisRateLimitStoreOptions, RedisSessionStore, RedisSessionStoreOptions, RedisSlidingWindowRateLimitStore, createRedisClient } from "@guren/server/redis";
2
- export { Redis, RedisApiTokenStore, type RedisApiTokenStoreOptions, type RedisClientOptions, RedisEmailVerificationStore, type RedisEmailVerificationStoreOptions, RedisOAuthStateStore, type RedisOAuthStateStoreOptions, type RedisOptions, RedisPasswordResetStore, type RedisPasswordResetStoreOptions, RedisRateLimitStore, type RedisRateLimitStoreOptions, RedisSessionStore, type RedisSessionStoreOptions, RedisSlidingWindowRateLimitStore, createRedisClient };
1
+ import { Redis, RedisApiTokenStore, RedisApiTokenStoreOptions, RedisClientOptions, RedisEmailVerificationStore, RedisEmailVerificationStoreOptions, RedisOAuthStateStore, RedisOAuthStateStoreOptions, RedisOptions, RedisPasswordResetStore, RedisPasswordResetStoreOptions, RedisRateLimitStore, RedisRateLimitStoreOptions, RedisSchedulerLock, RedisSchedulerLockOptions, RedisSessionStore, RedisSessionStoreOptions, RedisSlidingWindowRateLimitStore, createRedisClient } from "@guren/server/redis";
2
+ export { Redis, RedisApiTokenStore, type RedisApiTokenStoreOptions, type RedisClientOptions, RedisEmailVerificationStore, type RedisEmailVerificationStoreOptions, RedisOAuthStateStore, type RedisOAuthStateStoreOptions, type RedisOptions, RedisPasswordResetStore, type RedisPasswordResetStoreOptions, RedisRateLimitStore, type RedisRateLimitStoreOptions, RedisSchedulerLock, type RedisSchedulerLockOptions, RedisSessionStore, type RedisSessionStoreOptions, RedisSlidingWindowRateLimitStore, createRedisClient };
package/dist/redis.js CHANGED
@@ -1,2 +1,2 @@
1
- import { Redis, RedisApiTokenStore, RedisEmailVerificationStore, RedisOAuthStateStore, RedisPasswordResetStore, RedisRateLimitStore, RedisSessionStore, RedisSlidingWindowRateLimitStore, createRedisClient } from "@guren/server/redis";
2
- export { Redis, RedisApiTokenStore, RedisEmailVerificationStore, RedisOAuthStateStore, RedisPasswordResetStore, RedisRateLimitStore, RedisSessionStore, RedisSlidingWindowRateLimitStore, createRedisClient };
1
+ import { Redis, RedisApiTokenStore, RedisEmailVerificationStore, RedisOAuthStateStore, RedisPasswordResetStore, RedisRateLimitStore, RedisSchedulerLock, RedisSessionStore, RedisSlidingWindowRateLimitStore, createRedisClient } from "@guren/server/redis";
2
+ export { Redis, RedisApiTokenStore, RedisEmailVerificationStore, RedisOAuthStateStore, RedisPasswordResetStore, RedisRateLimitStore, RedisSchedulerLock, RedisSessionStore, RedisSlidingWindowRateLimitStore, createRedisClient };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/core",
3
- "version": "1.17.0",
3
+ "version": "1.18.0",
4
4
  "type": "module",
5
5
  "sideEffects": [
6
6
  "./src/bin.ts",
@@ -88,9 +88,9 @@
88
88
  "typecheck": "tsc --noEmit"
89
89
  },
90
90
  "dependencies": {
91
- "@guren/cli": "^2.21.0",
92
- "@guren/orm": "^2.8.0",
93
- "@guren/server": "^2.22.0"
91
+ "@guren/cli": "^2.22.0",
92
+ "@guren/orm": "^2.9.0",
93
+ "@guren/server": "^2.23.0"
94
94
  },
95
95
  "devDependencies": {
96
96
  "@types/node": "^20.14.10",