@opensaas/stack-core 0.20.1 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +334 -0
  3. package/CLAUDE.md +29 -11
  4. package/dist/access/access-filter.d.ts +29 -0
  5. package/dist/access/access-filter.d.ts.map +1 -0
  6. package/dist/access/access-filter.js +68 -0
  7. package/dist/access/access-filter.js.map +1 -0
  8. package/dist/access/engine.d.ts +15 -48
  9. package/dist/access/engine.d.ts.map +1 -1
  10. package/dist/access/engine.js +14 -280
  11. package/dist/access/engine.js.map +1 -1
  12. package/dist/access/field-access.d.ts +44 -0
  13. package/dist/access/field-access.d.ts.map +1 -0
  14. package/dist/access/field-access.js +123 -0
  15. package/dist/access/field-access.js.map +1 -0
  16. package/dist/access/field-access.test.d.ts +2 -0
  17. package/dist/access/field-access.test.d.ts.map +1 -0
  18. package/dist/access/{engine.test.js → field-access.test.js} +2 -2
  19. package/dist/access/field-access.test.js.map +1 -0
  20. package/dist/access/field-visibility.d.ts +13 -0
  21. package/dist/access/field-visibility.d.ts.map +1 -0
  22. package/dist/access/field-visibility.js +178 -0
  23. package/dist/access/field-visibility.js.map +1 -0
  24. package/dist/access/index.d.ts +4 -1
  25. package/dist/access/index.d.ts.map +1 -1
  26. package/dist/access/index.js +8 -1
  27. package/dist/access/index.js.map +1 -1
  28. package/dist/access/multi-column-read-write.test.d.ts +2 -0
  29. package/dist/access/multi-column-read-write.test.d.ts.map +1 -0
  30. package/dist/access/multi-column-read-write.test.js +149 -0
  31. package/dist/access/multi-column-read-write.test.js.map +1 -0
  32. package/dist/config/index.d.ts +1 -1
  33. package/dist/config/index.d.ts.map +1 -1
  34. package/dist/config/types.d.ts +334 -5
  35. package/dist/config/types.d.ts.map +1 -1
  36. package/dist/context/hook-pipeline.d.ts +49 -0
  37. package/dist/context/hook-pipeline.d.ts.map +1 -0
  38. package/dist/context/hook-pipeline.js +75 -0
  39. package/dist/context/hook-pipeline.js.map +1 -0
  40. package/dist/context/index.d.ts.map +1 -1
  41. package/dist/context/index.js +30 -462
  42. package/dist/context/index.js.map +1 -1
  43. package/dist/context/nested-operations.d.ts.map +1 -1
  44. package/dist/context/nested-operations.js +72 -68
  45. package/dist/context/nested-operations.js.map +1 -1
  46. package/dist/context/write-pipeline.d.ts +158 -0
  47. package/dist/context/write-pipeline.d.ts.map +1 -0
  48. package/dist/context/write-pipeline.js +306 -0
  49. package/dist/context/write-pipeline.js.map +1 -0
  50. package/dist/extend.d.ts +3 -0
  51. package/dist/extend.d.ts.map +1 -0
  52. package/dist/extend.js +10 -0
  53. package/dist/extend.js.map +1 -0
  54. package/dist/fields/format-prisma-default.d.ts +35 -0
  55. package/dist/fields/format-prisma-default.d.ts.map +1 -0
  56. package/dist/fields/format-prisma-default.js +52 -0
  57. package/dist/fields/format-prisma-default.js.map +1 -0
  58. package/dist/fields/format-prisma-default.test.d.ts +2 -0
  59. package/dist/fields/format-prisma-default.test.d.ts.map +1 -0
  60. package/dist/fields/format-prisma-default.test.js +54 -0
  61. package/dist/fields/format-prisma-default.test.js.map +1 -0
  62. package/dist/fields/index.d.ts +1 -0
  63. package/dist/fields/index.d.ts.map +1 -1
  64. package/dist/fields/index.js +267 -18
  65. package/dist/fields/index.js.map +1 -1
  66. package/dist/fields/select.test.js +85 -0
  67. package/dist/fields/select.test.js.map +1 -1
  68. package/dist/fields/text-keystone-compat.test.d.ts +2 -0
  69. package/dist/fields/text-keystone-compat.test.d.ts.map +1 -0
  70. package/dist/fields/text-keystone-compat.test.js +93 -0
  71. package/dist/fields/text-keystone-compat.test.js.map +1 -0
  72. package/dist/hooks/index.d.ts +20 -0
  73. package/dist/hooks/index.d.ts.map +1 -1
  74. package/dist/hooks/index.js +246 -0
  75. package/dist/hooks/index.js.map +1 -1
  76. package/dist/index.d.ts +6 -8
  77. package/dist/index.d.ts.map +1 -1
  78. package/dist/index.js +25 -9
  79. package/dist/index.js.map +1 -1
  80. package/dist/index.test.d.ts +2 -0
  81. package/dist/index.test.d.ts.map +1 -0
  82. package/dist/index.test.js +33 -0
  83. package/dist/index.test.js.map +1 -0
  84. package/dist/internal.d.ts +8 -0
  85. package/dist/internal.d.ts.map +1 -0
  86. package/dist/internal.js +16 -0
  87. package/dist/internal.js.map +1 -0
  88. package/dist/mcp/handler.js +0 -1
  89. package/dist/mcp/handler.js.map +1 -1
  90. package/dist/validation/field-config.d.ts +55 -0
  91. package/dist/validation/field-config.d.ts.map +1 -0
  92. package/dist/validation/field-config.js +100 -0
  93. package/dist/validation/field-config.js.map +1 -0
  94. package/dist/validation/field-config.test.d.ts +2 -0
  95. package/dist/validation/field-config.test.d.ts.map +1 -0
  96. package/dist/validation/field-config.test.js +159 -0
  97. package/dist/validation/field-config.test.js.map +1 -0
  98. package/package.json +11 -3
  99. package/src/access/access-filter.ts +97 -0
  100. package/src/access/engine.ts +13 -396
  101. package/src/access/{engine.test.ts → field-access.test.ts} +1 -1
  102. package/src/access/field-access.ts +159 -0
  103. package/src/access/field-visibility.ts +269 -0
  104. package/src/access/index.ts +7 -4
  105. package/src/access/multi-column-read-write.test.ts +255 -0
  106. package/src/config/index.ts +3 -0
  107. package/src/config/types.ts +342 -4
  108. package/src/context/hook-pipeline.ts +160 -0
  109. package/src/context/index.ts +29 -667
  110. package/src/context/nested-operations.ts +142 -111
  111. package/src/context/write-pipeline.ts +543 -0
  112. package/src/extend.ts +19 -0
  113. package/src/fields/format-prisma-default.test.ts +64 -0
  114. package/src/fields/format-prisma-default.ts +67 -0
  115. package/src/fields/index.ts +375 -20
  116. package/src/fields/select.test.ts +99 -0
  117. package/src/fields/text-keystone-compat.test.ts +126 -0
  118. package/src/hooks/index.ts +270 -0
  119. package/src/index.test.ts +50 -0
  120. package/src/index.ts +35 -82
  121. package/src/internal.ts +49 -0
  122. package/src/mcp/handler.ts +0 -2
  123. package/src/validation/field-config.test.ts +199 -0
  124. package/src/validation/field-config.ts +145 -0
  125. package/tests/access-relationships.test.ts +4 -4
  126. package/tests/access.test.ts +1 -1
  127. package/tests/field-hooks.test.ts +410 -0
  128. package/tests/field-types.test.ts +1 -1
  129. package/tests/hook-pipeline.test.ts +233 -0
  130. package/tests/nested-operation-registry.test.ts +206 -0
  131. package/tests/write-pipeline.test.ts +588 -0
  132. package/tsconfig.tsbuildinfo +1 -1
  133. package/vitest.config.ts +43 -1
  134. package/dist/access/engine.test.d.ts +0 -2
  135. package/dist/access/engine.test.d.ts.map +0 -1
  136. package/dist/access/engine.test.js.map +0 -1
@@ -462,12 +462,16 @@ export type BaseFieldConfig<TTypeInfo extends TypeInfo> = {
462
462
  * @param fieldName - The name of the field (for generating modifiers)
463
463
  * @param provider - Optional database provider ('sqlite', 'postgresql', 'mysql', etc.)
464
464
  * @param listName - Optional list name (used for generating enum type names)
465
+ * @param keystoneCompat - Whether Keystone-compat mode is enabled (db.keystoneCompat).
466
+ * When true, non-null text columns without an explicit defaultValue emit
467
+ * `@default("")` to match Keystone 6's implicit empty-string text default.
465
468
  * @returns Prisma type string, optional modifiers, and optional enum values
466
469
  */
467
470
  getPrismaType?: (
468
471
  fieldName: string,
469
472
  provider?: string,
470
473
  listName?: string,
474
+ keystoneCompat?: boolean,
471
475
  ) => {
472
476
  type: string
473
477
  modifiers?: string
@@ -506,6 +510,72 @@ export type BaseFieldConfig<TTypeInfo extends TypeInfo> = {
506
510
  */
507
511
  typeOnly?: boolean
508
512
  }>
513
+ /**
514
+ * Multi-column Prisma emission.
515
+ *
516
+ * Most scalar fields back a single Prisma column via {@link getPrismaType}.
517
+ * A field that maps onto SEVERAL physical columns (e.g. the storage
518
+ * `image()`/`file()` fields in multi-column / Keystone-parity mode — see
519
+ * ADR-0006) implements this instead: it returns one descriptor per column,
520
+ * each becoming its own line in the generated model. When present, the
521
+ * generator emits these lines and skips the single-column `getPrismaType`
522
+ * path. The field itself owns the column layout — the generator stays a
523
+ * neutral coordinator (no field-type switches), mirroring how relationship
524
+ * fields emit FK + relation lines through `getPrismaRelation`.
525
+ *
526
+ * @param fieldName - The field's config key (used to derive default column names)
527
+ * @returns One descriptor per physical column, or `undefined` to fall back to
528
+ * the single-column `getPrismaType` path.
529
+ */
530
+ getPrismaColumns?: (fieldName: string) => MultiColumnPrismaResult[] | undefined
531
+ /**
532
+ * The physical Prisma column names this field owns when it spans multiple
533
+ * columns (see {@link getPrismaColumns}). The read path uses this to strip the
534
+ * raw per-part columns from query results so only the assembled logical value
535
+ * (produced by {@link assembleColumns}) is exposed.
536
+ *
537
+ * @param fieldName - The field's config key
538
+ */
539
+ getColumnNames?: (fieldName: string) => string[]
540
+ /**
541
+ * Assemble the field's logical value from a database row's per-part columns
542
+ * (the read direction of a multi-column field). Pure transform — called by the
543
+ * read pipeline before field visibility. Receives the full row so it can read
544
+ * its sibling columns by name.
545
+ *
546
+ * @param fieldName - The field's config key
547
+ * @param row - The raw database row (contains the per-part columns)
548
+ */
549
+ assembleColumns?: (fieldName: string, row: Record<string, unknown>) => unknown
550
+ /**
551
+ * Split the field's logical value into per-part columns for writing (the write
552
+ * direction of a multi-column field). Pure transform — called by the write
553
+ * pipeline after `resolveInput`; the returned record is merged into the write
554
+ * payload in place of the single field key.
555
+ *
556
+ * @param fieldName - The field's config key
557
+ * @param value - The resolved logical value (metadata, or `null` to clear)
558
+ */
559
+ splitColumns?: (fieldName: string, value: unknown) => Record<string, unknown>
560
+ }
561
+
562
+ /**
563
+ * A single physical column contributed by a multi-column field
564
+ * (see {@link BaseFieldConfig.getPrismaColumns}).
565
+ */
566
+ export type MultiColumnPrismaResult = {
567
+ /** The Prisma model field name (the property the column is declared as). */
568
+ name: string
569
+ /** The Prisma scalar type, e.g. `'String'` or `'Int'`. */
570
+ type: string
571
+ /**
572
+ * Field modifiers, e.g. `'?'` for nullable. A leading `'?'` attaches to the
573
+ * type; anything after it is treated as trailing attributes (matching the
574
+ * single-column `getPrismaType` modifier convention).
575
+ */
576
+ modifiers?: string
577
+ /** Physical column name for the `@map` attribute, when it differs from `name`. */
578
+ map?: string
509
579
  }
510
580
 
511
581
  export type TextField<TTypeInfo extends TypeInfo = TypeInfo> = BaseFieldConfig<TTypeInfo> & {
@@ -587,6 +657,46 @@ export type SelectField<TTypeInfo extends TypeInfo = TypeInfo> = BaseFieldConfig
587
657
  */
588
658
  type?: 'string' | 'enum'
589
659
  map?: string
660
+ /**
661
+ * Force the generated column to be nullable (`?`) even when a `defaultValue`
662
+ * is present. By default a select with a `defaultValue` generates NOT NULL;
663
+ * set this to `true` for an explicit opt-in to a nullable column with a
664
+ * default (e.g. `String? @default("X")` or `<Enum>? @default(X)`), so that
665
+ * a live column containing NULLs migrates without a NOT NULL failure.
666
+ *
667
+ * @default undefined (NOT NULL when a default is present — unchanged behaviour)
668
+ *
669
+ * @example
670
+ * ```typescript
671
+ * // Optional select with a default, but keep the column nullable
672
+ * status: select({
673
+ * options: [{ label: 'Draft', value: 'draft' }],
674
+ * defaultValue: 'draft',
675
+ * db: { isNullable: true },
676
+ * })
677
+ * // Generates: String? @default("draft")
678
+ * ```
679
+ */
680
+ isNullable?: boolean
681
+ /**
682
+ * Override the generated Prisma enum type name for native-enum selects
683
+ * (only applies when `type: 'enum'`). By default the enum is named
684
+ * `<List><Field>` (e.g. `AccountNoteStatus`); set this to match a live DB
685
+ * enum type whose name differs (e.g. Keystone's `…Type` suffix).
686
+ *
687
+ * The custom name is applied to both the generated `enum` block and every
688
+ * reference to it in the owning model.
689
+ *
690
+ * @example
691
+ * ```typescript
692
+ * status: select({
693
+ * options: [{ label: 'Open', value: 'open' }],
694
+ * db: { type: 'enum', enumName: 'AccountNoteStatusType' },
695
+ * })
696
+ * // Generates: enum AccountNoteStatusType { ... } and the column references it
697
+ * ```
698
+ */
699
+ enumName?: string
590
700
  }
591
701
  validation?: {
592
702
  isRequired?: boolean
@@ -723,8 +833,57 @@ export type RelationshipField<TTypeInfo extends TypeInfo = TypeInfo> =
723
833
  ui?: {
724
834
  displayMode?: 'select' | 'cards'
725
835
  }
836
+ /**
837
+ * Get the complete Prisma schema contribution for this relationship field.
838
+ *
839
+ * Relationships are special: unlike scalar fields (which return a single
840
+ * type via `getPrismaType`), a relationship can contribute a foreign key
841
+ * line, a relation line on the owning model, and a synthetic back-relation
842
+ * line on the target model. This method encapsulates all of that logic so
843
+ * the generator can remain a neutral coordinator.
844
+ *
845
+ * @param fieldName - The name of this relationship field
846
+ * @param allFields - All fields on the list this relationship belongs to
847
+ * @param listKey - The name of the list this relationship belongs to
848
+ * @param config - The full OpenSaas config (used to resolve the target list/field)
849
+ */
850
+ getPrismaRelation?: (
851
+ fieldName: string,
852
+ allFields: Record<string, FieldConfig>,
853
+ listKey: string,
854
+ config: OpenSaasConfig,
855
+ ) => PrismaRelationResult
726
856
  }
727
857
 
858
+ /**
859
+ * The complete Prisma schema contribution of a relationship field.
860
+ */
861
+ export type PrismaRelationResult = {
862
+ /**
863
+ * Lines to add to the owning model.
864
+ * For an FK-owning single relationship this is `[fkLine, relationLine]`;
865
+ * for the many side or the non-FK side it is `[relationLine]`.
866
+ */
867
+ modelLines: string[]
868
+ /**
869
+ * Foreign key index to add to the owning model, if this side owns an
870
+ * indexed foreign key.
871
+ */
872
+ foreignKeyIndex?: {
873
+ foreignKeyField: string
874
+ indexType: boolean | 'unique'
875
+ }
876
+ /**
877
+ * Synthetic back-relation field to add to the target model. Only present
878
+ * for list-only refs (e.g., `ref: 'Category'`), where the target model
879
+ * needs an opposite relation field for Prisma to validate the relation.
880
+ */
881
+ backRelation?: {
882
+ targetList: string
883
+ line: string
884
+ }
885
+ }
886
+
728
887
  export type JsonField<TTypeInfo extends TypeInfo = TypeInfo> = BaseFieldConfig<TTypeInfo> & {
729
888
  type: 'json'
730
889
  validation?: {
@@ -1150,6 +1309,65 @@ export type ListConfig<TTypeInfo extends TypeInfo> = {
1150
1309
  operation?: OperationAccess<TTypeInfo['item']>
1151
1310
  }
1152
1311
  hooks?: Hooks<TTypeInfo['item'], TTypeInfo['inputs']['create'], TTypeInfo['inputs']['update']>
1312
+ /**
1313
+ * Database configuration for this list (model level)
1314
+ */
1315
+ db?: {
1316
+ /**
1317
+ * Custom database table name.
1318
+ * Adds a `@@map` attribute to the generated Prisma model.
1319
+ *
1320
+ * Useful when the Prisma model name (the list key) must differ from the
1321
+ * physical table name — e.g. adopting an existing better-auth installation
1322
+ * whose tables were created under a different name.
1323
+ *
1324
+ * @example
1325
+ * ```typescript
1326
+ * AuthUser: list({ fields: { ... }, db: { map: 'user' } })
1327
+ * // Generates: model AuthUser { ... @@map("user") }
1328
+ * ```
1329
+ */
1330
+ map?: string
1331
+ /**
1332
+ * Database schema for this model (Postgres multi-schema).
1333
+ * Adds a `@@schema` attribute to the generated Prisma model.
1334
+ *
1335
+ * Requires the schema to be listed in the datasource `schemas` array (see
1336
+ * {@link DatabaseConfig.schemas}) and the `multiSchema` preview feature,
1337
+ * both of which the generator emits automatically when `db.schemas` is set.
1338
+ *
1339
+ * Useful when adopting an existing installation whose tables live in a
1340
+ * non-`public` schema — e.g. a separate-schema better-auth layout.
1341
+ *
1342
+ * @example
1343
+ * ```typescript
1344
+ * AuthUser: list({ fields: { ... }, db: { schema: 'auth' } })
1345
+ * // Generates: model AuthUser { ... @@schema("auth") }
1346
+ * ```
1347
+ */
1348
+ schema?: string
1349
+ /**
1350
+ * Per-list override for auto-injected `createdAt`/`updatedAt` timestamp columns.
1351
+ *
1352
+ * Takes precedence over the global `db.timestamps` setting:
1353
+ * - `true` forces auto-timestamps on for this list, even when the global default is off.
1354
+ * - `false` forces them off for this list, even when enabled globally.
1355
+ * - `undefined` (the default) falls back to the global `db.timestamps` setting.
1356
+ *
1357
+ * When timestamps resolve to on but the list already declares its own `createdAt`/
1358
+ * `updatedAt` field, the auto column is skipped for the declared field(s) so Prisma
1359
+ * never sees a duplicate (`P1012`).
1360
+ *
1361
+ * @example Opt a single list out of timestamps even when enabled globally
1362
+ * ```typescript
1363
+ * Production: list({
1364
+ * fields: { name: text() },
1365
+ * db: { timestamps: false },
1366
+ * })
1367
+ * ```
1368
+ */
1369
+ timestamps?: boolean
1370
+ }
1153
1371
  /**
1154
1372
  * MCP server configuration for this list
1155
1373
  */
@@ -1221,12 +1439,10 @@ export type DatabaseConfig = {
1221
1439
  *
1222
1440
  * @example SQLite with better-sqlite3
1223
1441
  * ```typescript
1224
- * import { PrismaBetterSQLite3 } from '@prisma/adapter-better-sqlite3'
1225
- * import Database from 'better-sqlite3'
1442
+ * import { PrismaBetterSqlite3 } from '@prisma/adapter-better-sqlite3'
1226
1443
  *
1227
1444
  * prismaClientConstructor: (PrismaClient) => {
1228
- * const db = new Database(process.env.DATABASE_URL || './dev.db')
1229
- * const adapter = new PrismaBetterSQLite3(db)
1445
+ * const adapter = new PrismaBetterSqlite3({ url: process.env.DATABASE_URL || 'file:./dev.db' })
1230
1446
  * return new PrismaClient({ adapter })
1231
1447
  * }
1232
1448
  * ```
@@ -1284,6 +1500,86 @@ export type DatabaseConfig = {
1284
1500
  * ```
1285
1501
  */
1286
1502
  joinTableNaming?: 'prisma' | 'keystone'
1503
+ /**
1504
+ * Postgres multi-schema support.
1505
+ *
1506
+ * When set, the generator enables Prisma's `multiSchema` preview feature and
1507
+ * emits the `schemas = [...]` array on the datasource block. Combine with a
1508
+ * per-list `db.schema` (see {@link ListConfig}) to place models in a specific
1509
+ * schema via `@@schema(...)`.
1510
+ *
1511
+ * Only applies to the `postgresql` provider. When unset, the generated schema
1512
+ * is unchanged (single `public` schema, no `@@schema` attributes).
1513
+ *
1514
+ * @example Separate `auth` schema alongside the default `public`
1515
+ * ```typescript
1516
+ * db: {
1517
+ * provider: 'postgresql',
1518
+ * schemas: ['public', 'auth'],
1519
+ * // ...
1520
+ * }
1521
+ * ```
1522
+ */
1523
+ schemas?: string[]
1524
+ /**
1525
+ * Auto-inject `createdAt`/`updatedAt` timestamp columns into every generated model.
1526
+ *
1527
+ * Default: `false`. The generator does NOT add timestamps automatically — a list
1528
+ * opts in either by declaring the fields itself or by enabling this flag. This matches
1529
+ * Keystone 6, which never adds timestamps automatically, and keeps Keystone → stack
1530
+ * migrations non-destructive (Schema parity). See ADR-0004.
1531
+ *
1532
+ * When `true`, every list receives:
1533
+ * ```prisma
1534
+ * createdAt DateTime @default(now())
1535
+ * updatedAt DateTime @default(now()) @updatedAt
1536
+ * ```
1537
+ *
1538
+ * A per-list `db.timestamps` override takes precedence over this global setting. When
1539
+ * timestamps are enabled but a list already declares its own `createdAt`/`updatedAt`
1540
+ * field, the auto column is skipped for the declared field(s) so Prisma never sees a
1541
+ * duplicate (`P1012`).
1542
+ *
1543
+ * @default false
1544
+ *
1545
+ * @example Re-enable auto-timestamps globally
1546
+ * ```typescript
1547
+ * db: {
1548
+ * provider: 'postgresql',
1549
+ * timestamps: true,
1550
+ * // ... rest of config
1551
+ * }
1552
+ * ```
1553
+ */
1554
+ timestamps?: boolean
1555
+ /**
1556
+ * Opt into Keystone-compat mode for generated schema defaults.
1557
+ *
1558
+ * Keystone 6 gives every non-null text column an implicit empty-string
1559
+ * default. With `keystoneCompat: true`, the generator mirrors that: any
1560
+ * non-null `text()` column that has no explicit `defaultValue` emits
1561
+ * `@default("")`, so a migrating project reaches Schema parity without
1562
+ * hand-setting `defaultValue: ''` on dozens of columns.
1563
+ *
1564
+ * Stays opt-in (default `false`) because a greenfield project would not want
1565
+ * implicit empty-string text defaults cluttering its schema. The flag never
1566
+ * affects nullable text, fields with an explicit `defaultValue`, or any
1567
+ * non-text field — an explicit `text({ defaultValue: 'x' })` always wins.
1568
+ *
1569
+ * @default false
1570
+ *
1571
+ * @example Reach Schema parity when migrating from Keystone
1572
+ * ```typescript
1573
+ * db: {
1574
+ * provider: 'postgresql',
1575
+ * keystoneCompat: true, // non-null text without a default → @default("")
1576
+ * // ... rest of config
1577
+ * }
1578
+ * ```
1579
+ *
1580
+ * @see ADR-0004 (Keystone-compatible generator defaults)
1581
+ */
1582
+ keystoneCompat?: boolean
1287
1583
  /**
1288
1584
  * Optional function to extend or modify the generated Prisma schema
1289
1585
  * Receives the generated schema as a string and should return the modified schema
@@ -1774,6 +2070,34 @@ export type Plugin = {
1774
2070
  * Main configuration type
1775
2071
  * Using interface instead of type to allow module augmentation
1776
2072
  */
2073
+ /**
2074
+ * Configurable generator output locations.
2075
+ *
2076
+ * Lets a project relocate the generated Prisma schema and the `.opensaas`
2077
+ * bundle directory. Paths are interpreted relative to the project root.
2078
+ *
2079
+ * @example
2080
+ * ```typescript
2081
+ * output: {
2082
+ * prismaSchema: 'prisma-opensaas/schema.prisma',
2083
+ * opensaasDir: '.opensaas',
2084
+ * }
2085
+ * ```
2086
+ */
2087
+ export interface OutputConfig {
2088
+ /**
2089
+ * Path to the generated Prisma schema file.
2090
+ * @default "prisma/schema.prisma"
2091
+ */
2092
+ prismaSchema?: string
2093
+ /**
2094
+ * Directory for the generated `.opensaas` bundle (types, lists, context,
2095
+ * plugin-types, prisma-extensions, and the patched Prisma client).
2096
+ * @default ".opensaas"
2097
+ */
2098
+ opensaasDir?: string
2099
+ }
2100
+
1777
2101
  export interface OpenSaasConfig {
1778
2102
  db: DatabaseConfig
1779
2103
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Config must accept any list configuration
@@ -1794,6 +2118,20 @@ export interface OpenSaasConfig {
1794
2118
  * @default ".opensaas"
1795
2119
  */
1796
2120
  opensaasPath?: string
2121
+ /**
2122
+ * Relocate the generator's output so `opensaas generate` can coexist with an
2123
+ * existing `prisma/` directory (e.g. during a Keystone → stack migration).
2124
+ *
2125
+ * Both fields are resolved relative to the project root (the directory the
2126
+ * CLI runs in). When omitted, defaults are unchanged: the schema is written to
2127
+ * `prisma/schema.prisma` and the `.opensaas` bundle to `.opensaas/`.
2128
+ *
2129
+ * The generated files' cross-references follow these locations — `context.ts`
2130
+ * imports the generated types/lists from the resolved `.opensaas` dir, and the
2131
+ * top-level `prisma.config.ts` points at the configured schema path so the
2132
+ * `prisma` CLI keeps working.
2133
+ */
2134
+ output?: OutputConfig
1797
2135
  /**
1798
2136
  * Plugins to extend the stack
1799
2137
  * Executed in array order (or dependency order if dependencies specified)
@@ -0,0 +1,160 @@
1
+ import type { ListConfig } from '../config/types.js'
2
+ import type { AccessContext } from '../access/types.js'
3
+ import {
4
+ executeResolveInput,
5
+ executeValidate,
6
+ executeFieldResolveInputHooks,
7
+ executeFieldValidateHooks,
8
+ validateFieldRules,
9
+ ValidationError,
10
+ } from '../hooks/index.js'
11
+
12
+ /**
13
+ * Hook Pipeline — the single module that runs the transform+validate span of a
14
+ * write: list `resolveInput` → field `resolveInput` → list `validate` → field
15
+ * `validate` → built-in field rules (`validateFieldRules`). It owns the order of
16
+ * these phases and the threading of `resolvedData` through them, in one place.
17
+ *
18
+ * It is THE place where input is shaped and validated; it throws
19
+ * {@link ValidationError} on failure exactly as before (validate hooks via
20
+ * `addValidationError`, then `validateFieldRules`) — validation is never silent.
21
+ *
22
+ * Side-effect hooks (`beforeOperation`/`afterOperation`), operation-level access,
23
+ * writable-field filtering, nested operations, persistence and Field Visibility
24
+ * are deliberately OUT of this span — they stay in the Write Pipeline. See the
25
+ * "Hook Pipeline" and "Write Pipeline" glossary terms in CONTEXT.md.
26
+ */
27
+
28
+ /**
29
+ * Arguments for one transform+validate span. Only the create/update operations
30
+ * run this span (delete skips the input-shaping phases entirely).
31
+ */
32
+ export interface HookPipelineArgs {
33
+ operation: 'create' | 'update'
34
+ listName: string
35
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
36
+ listConfig: ListConfig<any>
37
+ /** The original input data for the write. */
38
+ inputData: Record<string, unknown>
39
+ /** The existing row for update; `undefined` for create. */
40
+ item: Record<string, unknown> | undefined
41
+ context: AccessContext
42
+ }
43
+
44
+ /**
45
+ * Result of a transform+validate span: the fully-resolved write data after the
46
+ * resolveInput hooks have run and all validation has passed.
47
+ */
48
+ export interface HookPipelineResult {
49
+ resolvedData: Record<string, unknown>
50
+ }
51
+
52
+ /**
53
+ * The transform+validate span, owning order + `resolvedData` threading.
54
+ */
55
+ export interface HookPipeline {
56
+ run(args: HookPipelineArgs): Promise<HookPipelineResult>
57
+ }
58
+
59
+ /**
60
+ * Run the transform+validate span once.
61
+ *
62
+ * Phase order (owned here, in one place):
63
+ * list `resolveInput`
64
+ * → field `resolveInput`
65
+ * → list `validate`
66
+ * → field `validate`
67
+ * → built-in field rules (`validateFieldRules`)
68
+ *
69
+ * Contract preserved exactly:
70
+ * - `resolvedData` starts as `inputData` and is threaded through each phase;
71
+ * - validate hooks report failures via `addValidationError` → THROW
72
+ * `ValidationError` (never silent);
73
+ * - built-in field rule failures THROW `ValidationError`;
74
+ * - on success returns the transformed `resolvedData`.
75
+ */
76
+ async function runHookPipeline(args: HookPipelineArgs): Promise<HookPipelineResult> {
77
+ const { operation, listName, listConfig, inputData, item, context } = args
78
+
79
+ // ── Phase 1: list-level resolveInput ──────────────────────────────────────
80
+ let resolvedData = await executeResolveInput(
81
+ listConfig.hooks,
82
+ operation === 'create'
83
+ ? {
84
+ listKey: listName,
85
+ operation: 'create',
86
+ inputData,
87
+ resolvedData: inputData,
88
+ item: undefined,
89
+ context,
90
+ }
91
+ : {
92
+ listKey: listName,
93
+ operation: 'update',
94
+ inputData,
95
+ resolvedData: inputData,
96
+ item,
97
+ context,
98
+ },
99
+ )
100
+
101
+ // ── Phase 1.5: field-level resolveInput (e.g. hash passwords) ──────────────
102
+ resolvedData = await executeFieldResolveInputHooks(
103
+ inputData,
104
+ resolvedData,
105
+ listConfig.fields,
106
+ operation,
107
+ context,
108
+ listName,
109
+ item,
110
+ )
111
+
112
+ // ── Phase 2: list-level validate ──────────────────────────────────────────
113
+ await executeValidate(
114
+ listConfig.hooks,
115
+ operation === 'create'
116
+ ? {
117
+ listKey: listName,
118
+ operation: 'create',
119
+ inputData,
120
+ resolvedData,
121
+ item: undefined,
122
+ context,
123
+ }
124
+ : {
125
+ listKey: listName,
126
+ operation: 'update',
127
+ inputData,
128
+ resolvedData,
129
+ item,
130
+ context,
131
+ },
132
+ )
133
+
134
+ // ── Phase 2.5: field-level validate ───────────────────────────────────────
135
+ await executeFieldValidateHooks(
136
+ inputData,
137
+ resolvedData,
138
+ listConfig.fields,
139
+ operation,
140
+ context,
141
+ listName,
142
+ item,
143
+ )
144
+
145
+ // ── Phase 3: built-in field rules (isRequired, length, etc.) ──────────────
146
+ // Validation failures THROW (validation is not silent).
147
+ const validation = validateFieldRules(resolvedData, listConfig.fields, operation)
148
+ if (validation.errors.length > 0) {
149
+ throw new ValidationError(validation.errors, validation.fieldErrors)
150
+ }
151
+
152
+ return { resolvedData }
153
+ }
154
+
155
+ /**
156
+ * The default Hook Pipeline instance used by the Write Pipeline.
157
+ */
158
+ export const hookPipeline: HookPipeline = {
159
+ run: runHookPipeline,
160
+ }