@opensaas/stack-core 0.25.0 → 0.27.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 (85) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +88 -12
  3. package/CLAUDE.md +50 -0
  4. package/dist/access/access-filter.d.ts +17 -0
  5. package/dist/access/access-filter.d.ts.map +1 -1
  6. package/dist/access/access-filter.js +39 -0
  7. package/dist/access/access-filter.js.map +1 -1
  8. package/dist/access/field-visibility.js.map +1 -1
  9. package/dist/access/index.d.ts +1 -1
  10. package/dist/access/index.d.ts.map +1 -1
  11. package/dist/access/index.js +1 -1
  12. package/dist/access/index.js.map +1 -1
  13. package/dist/access/multi-column-read-write.test.js.map +1 -1
  14. package/dist/config/label.d.ts +22 -0
  15. package/dist/config/label.d.ts.map +1 -0
  16. package/dist/config/label.js +48 -0
  17. package/dist/config/label.js.map +1 -0
  18. package/dist/config/plugin-engine.js.map +1 -1
  19. package/dist/config/types.d.ts +19 -5
  20. package/dist/config/types.d.ts.map +1 -1
  21. package/dist/context/apply-defaults.d.ts +36 -0
  22. package/dist/context/apply-defaults.d.ts.map +1 -0
  23. package/dist/context/apply-defaults.js +70 -0
  24. package/dist/context/apply-defaults.js.map +1 -0
  25. package/dist/context/hook-pipeline.d.ts.map +1 -1
  26. package/dist/context/hook-pipeline.js +10 -0
  27. package/dist/context/hook-pipeline.js.map +1 -1
  28. package/dist/context/index.d.ts +67 -17
  29. package/dist/context/index.d.ts.map +1 -1
  30. package/dist/context/index.js +71 -14
  31. package/dist/context/index.js.map +1 -1
  32. package/dist/context/nested-operations.d.ts.map +1 -1
  33. package/dist/context/nested-operations.js +6 -0
  34. package/dist/context/nested-operations.js.map +1 -1
  35. package/dist/context/transaction-boundary.d.ts.map +1 -1
  36. package/dist/context/write-pipeline.d.ts.map +1 -1
  37. package/dist/context/write-pipeline.js.map +1 -1
  38. package/dist/fields/calendar-day.test.js +133 -7
  39. package/dist/fields/calendar-day.test.js.map +1 -1
  40. package/dist/fields/format-prisma-default.js.map +1 -1
  41. package/dist/fields/index.d.ts +7 -3
  42. package/dist/fields/index.d.ts.map +1 -1
  43. package/dist/fields/index.js +37 -8
  44. package/dist/fields/index.js.map +1 -1
  45. package/dist/hooks/index.d.ts.map +1 -1
  46. package/dist/hooks/index.js.map +1 -1
  47. package/dist/index.d.ts +4 -0
  48. package/dist/index.d.ts.map +1 -1
  49. package/dist/index.js +8 -0
  50. package/dist/index.js.map +1 -1
  51. package/dist/query/index.d.ts.map +1 -1
  52. package/dist/query/relationship-options.d.ts +26 -0
  53. package/dist/query/relationship-options.d.ts.map +1 -0
  54. package/dist/query/relationship-options.js +43 -0
  55. package/dist/query/relationship-options.js.map +1 -0
  56. package/dist/query/relationship-options.test.d.ts +2 -0
  57. package/dist/query/relationship-options.test.d.ts.map +1 -0
  58. package/dist/query/relationship-options.test.js +121 -0
  59. package/dist/query/relationship-options.test.js.map +1 -0
  60. package/dist/utils/password.d.ts.map +1 -1
  61. package/dist/utils/password.js.map +1 -1
  62. package/dist/validation/schema.js.map +1 -1
  63. package/package.json +6 -5
  64. package/src/access/access-filter.ts +54 -0
  65. package/src/access/index.ts +5 -1
  66. package/src/config/label.ts +58 -0
  67. package/src/config/types.ts +20 -13
  68. package/src/context/apply-defaults.ts +79 -0
  69. package/src/context/hook-pipeline.ts +11 -0
  70. package/src/context/index.ts +173 -31
  71. package/src/context/nested-operations.ts +7 -0
  72. package/src/context/write-pipeline.ts +1 -2
  73. package/src/fields/calendar-day.test.ts +158 -7
  74. package/src/fields/index.ts +39 -11
  75. package/src/hooks/index.ts +1 -2
  76. package/src/index.ts +16 -0
  77. package/src/query/relationship-options.test.ts +157 -0
  78. package/src/query/relationship-options.ts +70 -0
  79. package/tests/apply-defaults.test.ts +119 -0
  80. package/tests/context.test.ts +220 -0
  81. package/tests/default-value-create.test.ts +299 -0
  82. package/tests/interactive-transaction.test.ts +444 -0
  83. package/tests/label.test.ts +135 -0
  84. package/tests/sudo.test.ts +7 -3
  85. package/tsconfig.tsbuildinfo +1 -1
@@ -1,7 +1,9 @@
1
- import { describe, it, expect, expectTypeOf } from 'vitest'
1
+ import { describe, it, expect, expectTypeOf, vi } from 'vitest'
2
2
  import { calendarDay } from './index.js'
3
3
  import { generateZodSchema, validateWithZod } from '../validation/schema.js'
4
+ import { getContext } from '../context/index.js'
4
5
  import type { FieldConfig } from '../config/types.js'
6
+ import type { OpenSaasConfig } from '../config/types.js'
5
7
 
6
8
  /**
7
9
  * calendarDay is a YYYY-MM-DD string end-to-end (Keystone's CalendarDay
@@ -54,7 +56,7 @@ describe('calendarDay field (YYYY-MM-DD string end-to-end)', () => {
54
56
  })
55
57
  })
56
58
 
57
- describe('write validation (string-only)', () => {
59
+ describe('write validation (YYYY-MM-DD string, or a Date post-resolveInput)', () => {
58
60
  const fields: Record<string, FieldConfig> = {
59
61
  startsOn: calendarDay({ validation: { isRequired: true } }),
60
62
  }
@@ -73,15 +75,18 @@ describe('calendarDay field (YYYY-MM-DD string end-to-end)', () => {
73
75
  }
74
76
  })
75
77
 
76
- it('rejects a Date instance at runtime (not a string)', () => {
77
- // A typed caller cannot reach here (input type is `string`), but the
78
- // validator is string-only as a runtime backstop.
78
+ it('accepts a Date instance (the shape resolveInput produces from a valid string)', () => {
79
+ // The write pipeline runs field `resolveInput` BEFORE this schema, and
80
+ // calendarDay's resolveInput turns a valid YYYY-MM-DD string into a UTC
81
+ // Date (see #621) so Prisma's `@db.Date` write validator accepts it. So
82
+ // by the time this schema runs, a successful write reaches it as a
83
+ // Date, not the original string — the schema must accept both shapes.
79
84
  const result = validateWithZod(
80
- { startsOn: new Date('2025-01-15') } as unknown as Record<string, unknown>,
85
+ { startsOn: new Date('2025-01-15T00:00:00.000Z') } as unknown as Record<string, unknown>,
81
86
  fields,
82
87
  'create',
83
88
  )
84
- expect(result.success).toBe(false)
89
+ expect(result.success).toBe(true)
85
90
  })
86
91
 
87
92
  it('zod schema for the field validates the YYYY-MM-DD shape', () => {
@@ -91,6 +96,62 @@ describe('calendarDay field (YYYY-MM-DD string end-to-end)', () => {
91
96
  })
92
97
  })
93
98
 
99
+ describe('write transform (resolveInput coerces YYYY-MM-DD string to a UTC Date, #621)', () => {
100
+ // The write pipeline calls fieldConfig.hooks.resolveInput({ resolvedData,
101
+ // fieldKey, ... }) BEFORE zod validation runs. We exercise that hook
102
+ // directly with the value shapes a caller (or an upstream list-level
103
+ // resolveInput) can produce.
104
+ function writeValue(value: unknown): unknown {
105
+ const field = calendarDay()
106
+ const hook = field.hooks?.resolveInput
107
+ if (!hook) throw new Error('calendarDay must define a resolveInput hook')
108
+ return (
109
+ hook as unknown as (args: {
110
+ resolvedData: Record<string, unknown>
111
+ fieldKey: string
112
+ }) => unknown
113
+ )({ resolvedData: { startsOn: value }, fieldKey: 'startsOn' })
114
+ }
115
+
116
+ it('converts a YYYY-MM-DD string to a UTC-midnight Date', () => {
117
+ const result = writeValue('2025-01-15') as Date
118
+ expect(result).toBeInstanceOf(Date)
119
+ expect(result.toISOString()).toBe('2025-01-15T00:00:00.000Z')
120
+ })
121
+
122
+ it('passes an already-Date value through unchanged', () => {
123
+ const date = new Date('2025-06-01T00:00:00.000Z')
124
+ expect(writeValue(date)).toBe(date)
125
+ })
126
+
127
+ it('passes null/undefined through unchanged (so isRequired can still reject a missing value)', () => {
128
+ expect(writeValue(null)).toBeNull()
129
+ expect(writeValue(undefined)).toBeUndefined()
130
+ })
131
+
132
+ it('leaves a malformed string untouched so zod still rejects it with a clear message', () => {
133
+ expect(writeValue('15/01/2025')).toBe('15/01/2025')
134
+ })
135
+
136
+ it('reads resolvedData[fieldKey], not inputData — survives a list-level resolveInput default', () => {
137
+ // A list-level resolveInput can inject a default for an omitted key
138
+ // into resolvedData before field resolveInput runs. Reading
139
+ // resolvedData (not the original inputData) here means that injected
140
+ // default is what gets coerced, instead of being read as `undefined`
141
+ // and overwriting the injected default with null.
142
+ const field = calendarDay()
143
+ const hook = field.hooks?.resolveInput as unknown as (args: {
144
+ resolvedData: Record<string, unknown>
145
+ fieldKey: string
146
+ }) => unknown
147
+ const result = hook({
148
+ resolvedData: { startsOn: '2025-03-20' }, // injected by a list-level hook
149
+ fieldKey: 'startsOn',
150
+ }) as Date
151
+ expect(result.toISOString()).toBe('2025-03-20T00:00:00.000Z')
152
+ })
153
+ })
154
+
94
155
  describe('read transform (resolveOutput returns a YYYY-MM-DD string)', () => {
95
156
  // The read pipeline calls fieldConfig.hooks.resolveOutput({ value, ... }).
96
157
  // We exercise that hook directly with the value shapes Prisma can return.
@@ -137,4 +198,94 @@ describe('calendarDay field (YYYY-MM-DD string end-to-end)', () => {
137
198
  expect(hook({ value: '2025-01-15' })).toBe('custom:2025-01-15')
138
199
  })
139
200
  })
201
+
202
+ describe('end-to-end via context.db.*.create/update (#621 repro)', () => {
203
+ // Prisma 7's client validator rejects a bare YYYY-MM-DD string for a
204
+ // `@db.Date` column. Assert the value actually forwarded to the Prisma
205
+ // client is a Date, not the string the caller passed in.
206
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock Prisma client
207
+ let mockPrisma: any
208
+
209
+ function buildConfig(): OpenSaasConfig {
210
+ mockPrisma = {
211
+ event: {
212
+ findFirst: vi.fn(),
213
+ findUnique: vi.fn(),
214
+ findMany: vi.fn(),
215
+ create: vi.fn(),
216
+ update: vi.fn(),
217
+ delete: vi.fn(),
218
+ count: vi.fn(),
219
+ },
220
+ }
221
+ return {
222
+ db: {
223
+ provider: 'postgresql',
224
+ prismaClientConstructor: (PrismaClient) => new PrismaClient(),
225
+ },
226
+ lists: {
227
+ Event: {
228
+ fields: {
229
+ startsOn: calendarDay({ validation: { isRequired: true } }),
230
+ },
231
+ access: {
232
+ operation: {
233
+ query: () => true,
234
+ create: () => true,
235
+ update: () => true,
236
+ delete: () => true,
237
+ },
238
+ },
239
+ },
240
+ },
241
+ }
242
+ }
243
+
244
+ it('create: a YYYY-MM-DD string reaches Prisma as a UTC-midnight Date', async () => {
245
+ const config = buildConfig()
246
+ mockPrisma.event.create.mockResolvedValue({
247
+ id: '1',
248
+ startsOn: new Date('2025-01-15T00:00:00.000Z'),
249
+ })
250
+ const context = await getContext(config, mockPrisma, null)
251
+
252
+ await context.db.event.create({ data: { startsOn: '2025-01-15' } })
253
+
254
+ expect(mockPrisma.event.create).toHaveBeenCalledTimes(1)
255
+ const callArgs = mockPrisma.event.create.mock.calls[0][0]
256
+ expect(callArgs.data.startsOn).toBeInstanceOf(Date)
257
+ expect((callArgs.data.startsOn as Date).toISOString()).toBe('2025-01-15T00:00:00.000Z')
258
+ })
259
+
260
+ it('update: a YYYY-MM-DD string reaches Prisma as a UTC-midnight Date', async () => {
261
+ const config = buildConfig()
262
+ const existing = { id: '1', startsOn: new Date('2025-01-15T00:00:00.000Z') }
263
+ mockPrisma.event.findUnique.mockResolvedValue(existing)
264
+ mockPrisma.event.update.mockResolvedValue({
265
+ ...existing,
266
+ startsOn: new Date('2025-02-20T00:00:00.000Z'),
267
+ })
268
+ const context = await getContext(config, mockPrisma, null)
269
+
270
+ await context.db.event.update({ where: { id: '1' }, data: { startsOn: '2025-02-20' } })
271
+
272
+ expect(mockPrisma.event.update).toHaveBeenCalledTimes(1)
273
+ const callArgs = mockPrisma.event.update.mock.calls[0][0]
274
+ expect(callArgs.data.startsOn).toBeInstanceOf(Date)
275
+ expect((callArgs.data.startsOn as Date).toISOString()).toBe('2025-02-20T00:00:00.000Z')
276
+ })
277
+
278
+ it('the read result is still normalised back to a YYYY-MM-DD string', async () => {
279
+ const config = buildConfig()
280
+ mockPrisma.event.create.mockResolvedValue({
281
+ id: '1',
282
+ startsOn: new Date('2025-01-15T00:00:00.000Z'),
283
+ })
284
+ const context = await getContext(config, mockPrisma, null)
285
+
286
+ const result = await context.db.event.create({ data: { startsOn: '2025-01-15' } })
287
+
288
+ expect(result?.startsOn).toBe('2025-01-15')
289
+ })
290
+ })
140
291
  })
@@ -523,9 +523,13 @@ export function timestamp<
523
523
  * - Stores date values only (no time component)
524
524
  * - PostgreSQL/MySQL: Uses native DATE type via @db.Date
525
525
  * - SQLite: Uses String representation
526
- * - **Writes:** accept only a `YYYY-MM-DD` string; a malformed string or a
527
- * `Date` is rejected at runtime by validation (a `ValidationError`). Genuine
528
- * compile-time rejection at the `context.db` call site is tracked in #599.
526
+ * - **Writes:** pass a `YYYY-MM-DD` string (the declared type). A
527
+ * `resolveInput` hook converts a valid string to a UTC-midnight `Date`
528
+ * before validation, since Prisma 7's client validator rejects a bare date
529
+ * string for a `@db.Date` column (#621); a `Date` is also accepted
530
+ * directly. A malformed string is rejected at runtime by validation (a
531
+ * `ValidationError`). Genuine compile-time rejection of a `Date` at the
532
+ * `context.db` call site is tracked in #599.
529
533
  * - **Reads:** always return a `YYYY-MM-DD` string. Even though the underlying
530
534
  * `@db.Date` column hands Prisma a `Date`, a `resolveOutput` transform
531
535
  * normalises it back to a `YYYY-MM-DD` string so the runtime value matches
@@ -573,6 +577,17 @@ export function calendarDay<
573
577
  return {
574
578
  type: 'calendarDay',
575
579
  ...options,
580
+ // Writes: the write pipeline runs field resolveInput BEFORE zod
581
+ // validation (Hook Pipeline: field resolveInput → built-in field rules),
582
+ // so this is the only point a YYYY-MM-DD string can be turned into
583
+ // something Prisma's `@db.Date` write validator accepts — Prisma 7
584
+ // rejects a bare date string there (#621). Convert a valid string to a
585
+ // UTC-midnight Date; leave anything else (a Date already, null/undefined,
586
+ // or a malformed string) untouched so the zod schema below still rejects
587
+ // malformed input with a clear message. Reads resolvedData[fieldKey]
588
+ // (not raw inputData) so a list-level resolveInput that injects a default
589
+ // for an omitted key is still coerced instead of being overwritten.
590
+ //
576
591
  // Reads: the underlying @db.Date column hands Prisma a Date (or a TEXT
577
592
  // string under the SQLite fallback). Normalise to a YYYY-MM-DD string so the
578
593
  // runtime value matches the declared `string` type. UTC components are used
@@ -580,6 +595,15 @@ export function calendarDay<
580
595
  // Cast hooks to any since field builders are generic and can't know the
581
596
  // specific TFieldKey (same pattern as password()).
582
597
  hooks: {
598
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Field builder hooks must be generic
599
+ resolveInput: ({ resolvedData, fieldKey }: { resolvedData: any; fieldKey: string }) => {
600
+ const value = resolvedData?.[fieldKey]
601
+ if (value == null || value instanceof Date) return value
602
+ if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value)) {
603
+ return new Date(`${value}T00:00:00.000Z`)
604
+ }
605
+ return value
606
+ },
583
607
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Field builder hooks must be generic
584
608
  resolveOutput: ({ value }: { value: any }) => formatCalendarDay(value),
585
609
  // Merge with user-provided hooks if any
@@ -590,15 +614,19 @@ export function calendarDay<
590
614
  const validation = options?.validation
591
615
  const isRequired = validation?.isRequired
592
616
 
593
- // Accept ISO8601 date strings (YYYY-MM-DD)
594
- const baseSchema = z.string({
595
- message: `${formatFieldName(fieldName)} must be a valid date in ISO8601 format (YYYY-MM-DD)`,
596
- })
617
+ // Accept ISO8601 date strings (YYYY-MM-DD) in the shape a caller passes,
618
+ // or a `Date` — the shape resolveInput above turns a valid string into
619
+ // before this schema runs. Malformed strings fall through resolveInput
620
+ // untouched and still fail the regex here with a clear message.
621
+ const stringSchema = z
622
+ .string({
623
+ message: `${formatFieldName(fieldName)} must be a valid date in ISO8601 format (YYYY-MM-DD)`,
624
+ })
625
+ .regex(/^\d{4}-\d{2}-\d{2}$/, {
626
+ message: `${formatFieldName(fieldName)} must be in YYYY-MM-DD format`,
627
+ })
597
628
 
598
- // Validate ISO8601 date format (YYYY-MM-DD)
599
- const dateSchema = baseSchema.regex(/^\d{4}-\d{2}-\d{2}$/, {
600
- message: `${formatFieldName(fieldName)} must be in YYYY-MM-DD format`,
601
- })
629
+ const dateSchema = z.union([stringSchema, z.date()])
602
630
 
603
631
  if (isRequired && operation === 'create') {
604
632
  return dateSchema
@@ -386,8 +386,7 @@ export async function executeFieldBeforeTransactionHooks(
386
386
  * so hooks can compensate.
387
387
  */
388
388
  export type TransactionOutcome =
389
- | { status: 'committed'; item: Record<string, unknown> }
390
- | { status: 'rolled-back'; error: unknown }
389
+ { status: 'committed'; item: Record<string, unknown> } | { status: 'rolled-back'; error: unknown }
391
390
 
392
391
  /**
393
392
  * Execute field-level afterTransaction hooks (#590 / ADR-0010).
package/src/index.ts CHANGED
@@ -34,10 +34,20 @@ export type {
34
34
 
35
35
  // Context factory
36
36
  export { getContext } from './context/index.js'
37
+ export type {
38
+ StackContext,
39
+ TransactionOptions,
40
+ TransactionIsolationLevel,
41
+ } from './context/index.js'
37
42
 
38
43
  // Naming utilities (documented public helpers; used for URLs and db keys)
39
44
  export { getDbKey, getUrlKey, getListKeyFromUrl } from './lib/case-utils.js'
40
45
 
46
+ // Label seam — resolves the field that represents a row as a single label
47
+ // (projection) and reads it off a row (render). Used by the admin UI for
48
+ // relationship cells, dropdown options, and page headings.
49
+ export { getLabelFieldName, getItemLabel } from './config/label.js'
50
+
41
51
  // Validation error surfaced by write operations
42
52
  export { ValidationError } from './hooks/index.js'
43
53
 
@@ -56,3 +66,9 @@ export type { FieldConfigValidationError } from './validation/field-config.js'
56
66
  // root surface — those live on '@opensaas/stack-core/internal'.
57
67
  export { defineFragment, runQuery, runQueryOne } from './query/index.js'
58
68
  export type { ResultOf, RelationSelector, QueryArgs } from './query/index.js'
69
+
70
+ // Relationship-options read primitive — bounded, projected fetch for
71
+ // relationship editors. Backs the `relationshipOptions` context.serverAction
72
+ // op; also callable directly wherever a full context is already in hand.
73
+ export { getRelationshipOptions } from './query/relationship-options.js'
74
+ export type { RelationshipOption, RelationshipOptionsArgs } from './query/relationship-options.js'
@@ -0,0 +1,157 @@
1
+ import { describe, it, expect, vi } from 'vitest'
2
+ import { getRelationshipOptions } from './relationship-options.js'
3
+ import type { QueryRunnerContext } from './index.js'
4
+ import type { OpenSaasConfig } from '../config/types.js'
5
+
6
+ function makeDelegate(rows: Array<Record<string, unknown>>) {
7
+ return {
8
+ findMany: vi.fn(async (_args?: unknown) => rows),
9
+ findFirst: vi.fn(async (_args?: unknown) => rows[0] ?? null),
10
+ }
11
+ }
12
+
13
+ function makeContext(
14
+ delegates: Record<string, ReturnType<typeof makeDelegate>>,
15
+ ): QueryRunnerContext {
16
+ return { db: delegates }
17
+ }
18
+
19
+ const authors = [
20
+ { id: 'a1', name: 'Ada Lovelace' },
21
+ { id: 'a2', name: 'Alan Turing' },
22
+ { id: 'a3', name: 'Grace Hopper' },
23
+ ]
24
+
25
+ function makeConfig(): OpenSaasConfig {
26
+ return {
27
+ db: { provider: 'sqlite', url: 'file:./test.db' },
28
+ lists: {
29
+ Author: {
30
+ fields: {
31
+ name: { type: 'text' },
32
+ },
33
+ access: { operation: { query: () => true } },
34
+ },
35
+ NumericLabel: {
36
+ fields: {
37
+ rank: { type: 'integer' },
38
+ },
39
+ ui: { labelField: 'rank' },
40
+ access: { operation: { query: () => true } },
41
+ },
42
+ },
43
+ } as unknown as OpenSaasConfig
44
+ }
45
+
46
+ describe('getRelationshipOptions', () => {
47
+ it('returns { id, label }[] via a scalar-only fragment with no nested include', async () => {
48
+ const delegate = makeDelegate(authors)
49
+ const context = makeContext({ author: delegate })
50
+ const config = makeConfig()
51
+
52
+ const result = await getRelationshipOptions(context, config, 'Author', {})
53
+
54
+ expect(result).toEqual([
55
+ { id: 'a1', label: 'Ada Lovelace' },
56
+ { id: 'a2', label: 'Alan Turing' },
57
+ { id: 'a3', label: 'Grace Hopper' },
58
+ ])
59
+
60
+ const call = delegate.findMany.mock.calls[0][0] as Record<string, unknown>
61
+ expect(call.include).toBeUndefined()
62
+ })
63
+
64
+ it('bounds the result by take', async () => {
65
+ const delegate = makeDelegate(authors.slice(0, 2))
66
+ const context = makeContext({ author: delegate })
67
+ const config = makeConfig()
68
+
69
+ await getRelationshipOptions(context, config, 'Author', { take: 2 })
70
+
71
+ expect(delegate.findMany).toHaveBeenCalledWith(expect.objectContaining({ take: 2 }))
72
+ })
73
+
74
+ it('orders by the label field ascending and filters via contains on a text label field', async () => {
75
+ const delegate = makeDelegate([authors[0]])
76
+ const context = makeContext({ author: delegate })
77
+ const config = makeConfig()
78
+
79
+ await getRelationshipOptions(context, config, 'Author', { search: 'Ada' })
80
+
81
+ expect(delegate.findMany).toHaveBeenCalledWith(
82
+ expect.objectContaining({
83
+ where: { name: { contains: 'Ada' } },
84
+ orderBy: { name: 'asc' },
85
+ }),
86
+ )
87
+ })
88
+
89
+ it('does not filter (first-N) when the label field is not a text field', async () => {
90
+ const rows = [{ id: 'n1', rank: 1 }]
91
+ const delegate = makeDelegate(rows)
92
+ const context = makeContext({ numericLabel: delegate })
93
+ const config = makeConfig()
94
+
95
+ await getRelationshipOptions(context, config, 'NumericLabel', { search: '1' })
96
+
97
+ const call = delegate.findMany.mock.calls[0][0] as Record<string, unknown>
98
+ expect(call.where).toBeUndefined()
99
+ expect(call.orderBy).toEqual({ rank: 'asc' })
100
+ })
101
+
102
+ it('unions currently-selected ids even when beyond take / not matching search', async () => {
103
+ // The bounded/search-scoped query only returns a1 (mimicking take:1 + search).
104
+ const primaryDelegate = makeDelegate([authors[0]])
105
+ const context = makeContext({ author: primaryDelegate })
106
+ const config = makeConfig()
107
+
108
+ // The selected-ids query (a separate findMany call) resolves a3, which fell
109
+ // outside the primary window.
110
+ primaryDelegate.findMany.mockImplementationOnce(async () => [authors[0]])
111
+ primaryDelegate.findMany.mockImplementationOnce(async () => [authors[2]])
112
+
113
+ const result = await getRelationshipOptions(context, config, 'Author', {
114
+ take: 1,
115
+ selectedIds: ['a3'],
116
+ })
117
+
118
+ expect(result).toEqual([
119
+ { id: 'a1', label: 'Ada Lovelace' },
120
+ { id: 'a3', label: 'Grace Hopper' },
121
+ ])
122
+
123
+ const selectedCall = primaryDelegate.findMany.mock.calls[1][0] as Record<string, unknown>
124
+ expect(selectedCall.where).toEqual({ id: { in: ['a3'] } })
125
+ })
126
+
127
+ it('does not re-query when the selected id is already within the primary window', async () => {
128
+ const delegate = makeDelegate([authors[0]])
129
+ const context = makeContext({ author: delegate })
130
+ const config = makeConfig()
131
+
132
+ await getRelationshipOptions(context, config, 'Author', { selectedIds: ['a1'] })
133
+
134
+ expect(delegate.findMany).toHaveBeenCalledTimes(1)
135
+ })
136
+
137
+ it('returns [] when the related list query access is denied (findMany returns [])', async () => {
138
+ const delegate = makeDelegate([])
139
+ const context = makeContext({ author: delegate })
140
+ const config = makeConfig()
141
+
142
+ const result = await getRelationshipOptions(context, config, 'Author', {
143
+ selectedIds: ['a1'],
144
+ })
145
+
146
+ expect(result).toEqual([])
147
+ })
148
+
149
+ it('returns [] when the related list does not exist in config', async () => {
150
+ const context = makeContext({})
151
+ const config = makeConfig()
152
+
153
+ const result = await getRelationshipOptions(context, config, 'Missing', {})
154
+
155
+ expect(result).toEqual([])
156
+ })
157
+ })
@@ -0,0 +1,70 @@
1
+ import type { OpenSaasConfig } from '../config/types.js'
2
+ import { getLabelFieldName, getItemLabel } from '../config/label.js'
3
+ import { defineFragment, runQuery, type QueryRunnerContext } from './index.js'
4
+
5
+ const DEFAULT_TAKE = 50
6
+
7
+ export interface RelationshipOption {
8
+ id: string
9
+ label: string
10
+ }
11
+
12
+ export interface RelationshipOptionsArgs {
13
+ /** Filters the label field via `contains` when it is a text field. */
14
+ search?: string
15
+ /** Bounds the primary (search-scoped) window. @default 50 */
16
+ take?: number
17
+ /** Always unioned into the result, even outside the search/take window. */
18
+ selectedIds?: string[]
19
+ }
20
+
21
+ /**
22
+ * Bounded, projected fetch of `{ id, label }` options for a relationship
23
+ * editor — the read primitive behind the `relationshipOptions` serverAction
24
+ * op. Selects only `id` and the resolved label field (via
25
+ * {@link getLabelFieldName}), so the fragment carries no relation keys and
26
+ * `buildIncludeWithAccessControl`'s depth-5 auto-include never runs.
27
+ *
28
+ * Operation-level `query` access on `relatedListKey` still applies — a denied
29
+ * list resolves to `[]` (via the underlying access-controlled `findMany`).
30
+ */
31
+ export async function getRelationshipOptions(
32
+ context: QueryRunnerContext,
33
+ config: OpenSaasConfig,
34
+ relatedListKey: string,
35
+ args: RelationshipOptionsArgs = {},
36
+ ): Promise<RelationshipOption[]> {
37
+ const relatedListConfig = config.lists[relatedListKey]
38
+ if (!relatedListConfig) return []
39
+
40
+ const labelField = getLabelFieldName(relatedListConfig)
41
+ const fragment = defineFragment<Record<string, unknown>>()({
42
+ id: true,
43
+ [labelField]: true,
44
+ })
45
+
46
+ const { search, take = DEFAULT_TAKE, selectedIds = [] } = args
47
+ const labelFieldConfig = relatedListConfig.fields[labelField] as { type?: string } | undefined
48
+ const where =
49
+ search && labelFieldConfig?.type === 'text' ? { [labelField]: { contains: search } } : undefined
50
+
51
+ const primary = await runQuery(context, relatedListKey, fragment, {
52
+ where,
53
+ orderBy: { [labelField]: 'asc' },
54
+ take,
55
+ })
56
+
57
+ const seenIds = new Set(primary.map((item) => (item as { id: string }).id))
58
+ const missingSelectedIds = selectedIds.filter((id) => !seenIds.has(id))
59
+
60
+ const selected = missingSelectedIds.length
61
+ ? await runQuery(context, relatedListKey, fragment, {
62
+ where: { id: { in: missingSelectedIds } },
63
+ })
64
+ : []
65
+
66
+ return [...primary, ...selected].map((item) => ({
67
+ id: (item as { id: string }).id,
68
+ label: getItemLabel(relatedListConfig, item as Record<string, unknown>),
69
+ }))
70
+ }
@@ -0,0 +1,119 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import { applyCreateDefaults } from '../src/context/apply-defaults.js'
3
+ import { text, integer, checkbox, timestamp, virtual, relationship } from '../src/fields/index.js'
4
+ import type { FieldConfig } from '../src/config/types.js'
5
+
6
+ /**
7
+ * Direct unit tests for `applyCreateDefaults` (#615). These exercise every guard
8
+ * rail of the real helper — virtual / system / relationship skips, the
9
+ * no-`defaultValue` skip, explicit-value and explicit-`null` preservation, the
10
+ * timestamp `{ kind: 'now' }` sentinel skip, and concrete `Date` injection — so
11
+ * the resolve-then-validate helper is fully covered without mocking its logic.
12
+ */
13
+
14
+ function fields(config: Record<string, FieldConfig>): Record<string, FieldConfig> {
15
+ return config
16
+ }
17
+
18
+ describe('applyCreateDefaults', () => {
19
+ it('injects a declared defaultValue into an omitted field', () => {
20
+ const resolved = applyCreateDefaults(
21
+ {},
22
+ fields({
23
+ label: text({ defaultValue: 'PLACEHOLDER' }),
24
+ count: integer({ defaultValue: 7 }),
25
+ active: checkbox({ defaultValue: true }),
26
+ }),
27
+ )
28
+
29
+ expect(resolved).toEqual({ label: 'PLACEHOLDER', count: 7, active: true })
30
+ })
31
+
32
+ it('leaves a field with NO defaultValue untouched (key stays absent)', () => {
33
+ const resolved = applyCreateDefaults({}, fields({ label: text() }))
34
+
35
+ expect('label' in resolved).toBe(false)
36
+ })
37
+
38
+ it('preserves an explicitly-provided value over the default', () => {
39
+ const resolved = applyCreateDefaults(
40
+ { count: 99 },
41
+ fields({ count: integer({ defaultValue: 7 }) }),
42
+ )
43
+
44
+ expect(resolved.count).toBe(99)
45
+ })
46
+
47
+ it('preserves an explicit null and does not overwrite it with the default', () => {
48
+ const resolved = applyCreateDefaults(
49
+ { note: null },
50
+ fields({ note: text({ defaultValue: 'DEFAULT_NOTE' }) }),
51
+ )
52
+
53
+ expect(resolved.note).toBeNull()
54
+ })
55
+
56
+ it('skips virtual fields (no scalar default to inject)', () => {
57
+ const resolved = applyCreateDefaults(
58
+ {},
59
+ fields({
60
+ // A virtual field cannot carry a stored default; it must be skipped.
61
+ computed: virtual({
62
+ type: 'string',
63
+ hooks: { resolveOutput: () => 'x' },
64
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
65
+ }) as any,
66
+ }),
67
+ )
68
+
69
+ expect('computed' in resolved).toBe(false)
70
+ })
71
+
72
+ it('skips system fields (id/createdAt/updatedAt)', () => {
73
+ const resolved = applyCreateDefaults(
74
+ {},
75
+ fields({
76
+ id: text({ defaultValue: 'SHOULD_NOT_INJECT' }),
77
+ createdAt: timestamp({ defaultValue: new Date('2020-01-01T00:00:00Z') }),
78
+ updatedAt: timestamp({ defaultValue: new Date('2020-01-01T00:00:00Z') }),
79
+ }),
80
+ )
81
+
82
+ expect(resolved).toEqual({})
83
+ })
84
+
85
+ it('skips relationship fields (they carry connect/create payloads, not literals)', () => {
86
+ const resolved = applyCreateDefaults(
87
+ {},
88
+ fields({
89
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
90
+ owner: relationship({ ref: 'User' }) as any,
91
+ }),
92
+ )
93
+
94
+ expect('owner' in resolved).toBe(false)
95
+ })
96
+
97
+ it("does NOT inject the timestamp { kind: 'now' } sentinel (left for the DB @default(now()))", () => {
98
+ const resolved = applyCreateDefaults(
99
+ {},
100
+ fields({ when: timestamp({ defaultValue: { kind: 'now' } }) }),
101
+ )
102
+
103
+ expect('when' in resolved).toBe(false)
104
+ })
105
+
106
+ it('DOES inject a concrete Date default (a real literal, unlike the now sentinel)', () => {
107
+ const date = new Date('2021-06-15T12:00:00Z')
108
+ const resolved = applyCreateDefaults({}, fields({ when: timestamp({ defaultValue: date }) }))
109
+
110
+ expect(resolved.when).toBe(date)
111
+ })
112
+
113
+ it('returns the same resolvedData object it was given (mutation contract)', () => {
114
+ const input: Record<string, unknown> = {}
115
+ const result = applyCreateDefaults(input, fields({ label: text({ defaultValue: 'x' }) }))
116
+
117
+ expect(result).toBe(input)
118
+ })
119
+ })