plantr 2.1.0 → 2.3.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/src/expect.ts ADDED
@@ -0,0 +1,502 @@
1
+ import assert, { AssertionError } from 'node:assert/strict'
2
+ import { createRequire } from 'node:module'
3
+ import { inspectValue } from './formatting.js'
4
+
5
+ /** Constructor type accepted by `toThrow(...)` */
6
+ // biome-ignore lint/suspicious/noExplicitAny: matches Error constructors with arbitrary parameters
7
+ export type ErrorConstructor = abstract new (...args: any[]) => unknown
8
+
9
+ /** Any callable assertion function accepted by `createSeederInstance({ expect })` */
10
+ // biome-ignore lint/complexity/noBannedTypes: using Function preserves generic inference for callable expect implementations (bun:test, vitest, jest, custom)
11
+ export type AnyExpectFn = Function
12
+
13
+ /**
14
+ * Portable assertion matchers supported across Bun (`bun:test`) and Node.js (built-in fallback).
15
+ * Compatible with `bun:test`, Vitest, and Jest `expect` implementations.
16
+ */
17
+ export interface ExpectMatchers<T = unknown> {
18
+ readonly not: ExpectMatchers<unknown>
19
+ toBe<E = T>(expected: E): void
20
+ toEqual<E = T>(expected: E): void
21
+ toStrictEqual<E = T>(expected: E): void
22
+ toBeDefined(): void
23
+ toBeUndefined(): void
24
+ toBeNull(): void
25
+ toBeTruthy(): void
26
+ toBeFalsy(): void
27
+ toContain(expected: unknown): void
28
+ toHaveLength(length: number): void
29
+ toMatch(expected: string | RegExp): void
30
+ toBeGreaterThan(expected: number | bigint): void
31
+ toBeGreaterThanOrEqual(expected: number | bigint): void
32
+ toBeLessThan(expected: number | bigint): void
33
+ toBeLessThanOrEqual(expected: number | bigint): void
34
+ toThrow(expected?: string | RegExp | Error | ErrorConstructor): void
35
+ }
36
+
37
+ /** Portable `expect` function signature available in `BaseSeederContext` */
38
+ export type ExpectFn = <T = unknown>(actual: T, message?: string) => ExpectMatchers<T>
39
+
40
+ function isPlainObject(value: object): value is Record<string | symbol, unknown> {
41
+ const proto = Object.getPrototypeOf(value)
42
+ return proto === Object.prototype || proto === null
43
+ }
44
+
45
+ /**
46
+ * Normalize values for `toEqual` semantics:
47
+ * - Strip `undefined`-valued properties on plain objects (`{ a: 1, b: undefined }` equals `{ a: 1 }`)
48
+ * - Treat sparse array holes as `undefined` (`[, 1]` equals `[undefined, 1]`)
49
+ * - Preserve cycles, `Date`, `RegExp`, `Map`, `Set`, typed arrays, and class instances
50
+ */
51
+ function normalizeForEqual(value: unknown, seen = new WeakMap<object, unknown>()): unknown {
52
+ if (value === null || typeof value !== 'object') return value
53
+ if (seen.has(value)) return seen.get(value)
54
+
55
+ if (Array.isArray(value)) {
56
+ const normalized: unknown[] = new Array(value.length)
57
+ seen.set(value, normalized)
58
+ for (let i = 0; i < value.length; i++) {
59
+ normalized[i] = normalizeForEqual(value[i], seen)
60
+ }
61
+ return normalized
62
+ }
63
+
64
+ if (isPlainObject(value)) {
65
+ const normalized: Record<string | symbol, unknown> =
66
+ Object.getPrototypeOf(value) === null ? Object.create(null) : {}
67
+ seen.set(value, normalized)
68
+ for (const key of Reflect.ownKeys(value)) {
69
+ const desc = Object.getOwnPropertyDescriptor(value, key)
70
+ if (!desc?.enumerable) continue
71
+ const entryValue = value[key]
72
+ if (entryValue !== undefined) {
73
+ normalized[key] = normalizeForEqual(entryValue, seen)
74
+ }
75
+ }
76
+ return normalized
77
+ }
78
+
79
+ return value
80
+ }
81
+
82
+ function sameValueZero(a: unknown, b: unknown): boolean {
83
+ return a === b || (Number.isNaN(a) && Number.isNaN(b))
84
+ }
85
+
86
+ function containsValue(actual: unknown, expected: unknown): boolean {
87
+ if (typeof actual === 'string') {
88
+ return typeof expected === 'string' && actual.includes(expected)
89
+ }
90
+ if (Array.isArray(actual)) {
91
+ return actual.includes(expected)
92
+ }
93
+ if (actual instanceof Set) {
94
+ return actual.has(expected)
95
+ }
96
+ if (
97
+ actual !== null &&
98
+ actual !== undefined &&
99
+ typeof (actual as Iterable<unknown>)[Symbol.iterator] === 'function'
100
+ ) {
101
+ for (const item of actual as Iterable<unknown>) {
102
+ if (sameValueZero(item, expected)) return true
103
+ }
104
+ }
105
+ return false
106
+ }
107
+
108
+ function matchesThrown(
109
+ thrown: unknown,
110
+ expected: string | RegExp | Error | ErrorConstructor,
111
+ ): boolean {
112
+ if (typeof expected === 'string') {
113
+ const errorMessage = thrown instanceof Error ? thrown.message : String(thrown)
114
+ return errorMessage.includes(expected)
115
+ }
116
+ if (expected instanceof RegExp) {
117
+ const errorMessage = thrown instanceof Error ? thrown.message : String(thrown)
118
+ const re =
119
+ expected.global || expected.sticky ? new RegExp(expected.source, expected.flags) : expected
120
+ return re.test(errorMessage)
121
+ }
122
+ if (expected instanceof Error) {
123
+ if (!(thrown instanceof Error)) return false
124
+ if (expected.constructor !== Error && !(thrown instanceof expected.constructor)) return false
125
+ return thrown.message === expected.message
126
+ }
127
+ if (typeof expected === 'function') {
128
+ return thrown instanceof expected
129
+ }
130
+ return false
131
+ }
132
+
133
+ function failAssertion(
134
+ defaultMessage: string,
135
+ actual: unknown,
136
+ expected: unknown,
137
+ operator: string,
138
+ customMessage?: string,
139
+ ): never {
140
+ throw new AssertionError({
141
+ message: customMessage ?? defaultMessage,
142
+ actual,
143
+ expected,
144
+ operator,
145
+ })
146
+ }
147
+
148
+ function createMatchers<T>(
149
+ actual: T,
150
+ message: string | undefined,
151
+ negated: boolean,
152
+ ): ExpectMatchers<T> {
153
+ const checkComparison = (
154
+ expected: number | bigint,
155
+ operator: '>' | '>=' | '<' | '<=',
156
+ label: string,
157
+ compare: (a: number | bigint, b: number | bigint) => boolean,
158
+ ) => {
159
+ if (typeof actual !== 'number' && typeof actual !== 'bigint') {
160
+ failAssertion(
161
+ `Expected a number or bigint, received ${typeof actual} (${inspectValue(actual)})`,
162
+ actual,
163
+ expected,
164
+ operator,
165
+ message,
166
+ )
167
+ }
168
+ const passed = compare(actual, expected)
169
+ if (negated ? passed : !passed) {
170
+ failAssertion(
171
+ `Expected ${inspectValue(actual)} ${negated ? 'not ' : ''}${label} ${inspectValue(expected)}`,
172
+ actual,
173
+ expected,
174
+ negated ? `not ${operator}` : operator,
175
+ message,
176
+ )
177
+ }
178
+ }
179
+
180
+ return {
181
+ get not(): ExpectMatchers<unknown> {
182
+ return createMatchers(actual as unknown, message, !negated)
183
+ },
184
+
185
+ toBe<E = T>(expected: E): void {
186
+ if (negated) {
187
+ assert.notStrictEqual(actual, expected, message)
188
+ } else {
189
+ assert.strictEqual(actual, expected, message)
190
+ }
191
+ },
192
+
193
+ toEqual<E = T>(expected: E): void {
194
+ const normActual = normalizeForEqual(actual)
195
+ const normExpected = normalizeForEqual(expected)
196
+ if (negated) {
197
+ try {
198
+ assert.notDeepStrictEqual(normActual, normExpected, message)
199
+ } catch (err) {
200
+ if (err instanceof AssertionError) {
201
+ failAssertion(err.message, actual, expected, 'not toEqual', message)
202
+ }
203
+ throw err
204
+ }
205
+ } else {
206
+ try {
207
+ assert.deepStrictEqual(normActual, normExpected, message)
208
+ } catch (err) {
209
+ if (err instanceof AssertionError) {
210
+ failAssertion(err.message, actual, expected, 'toEqual', message)
211
+ }
212
+ throw err
213
+ }
214
+ }
215
+ },
216
+
217
+ toStrictEqual<E = T>(expected: E): void {
218
+ if (negated) {
219
+ assert.notDeepStrictEqual(actual, expected, message)
220
+ } else {
221
+ assert.deepStrictEqual(actual, expected, message)
222
+ }
223
+ },
224
+
225
+ toBeDefined(): void {
226
+ const isDefined = actual !== undefined
227
+ if (negated ? isDefined : !isDefined) {
228
+ failAssertion(
229
+ negated
230
+ ? `Expected ${inspectValue(actual)} to be undefined`
231
+ : 'Expected value to be defined, received undefined',
232
+ actual,
233
+ undefined,
234
+ negated ? 'not toBeDefined' : 'toBeDefined',
235
+ message,
236
+ )
237
+ }
238
+ },
239
+
240
+ toBeUndefined(): void {
241
+ if (negated) {
242
+ assert.notStrictEqual(actual, undefined, message)
243
+ } else {
244
+ assert.strictEqual(actual, undefined, message)
245
+ }
246
+ },
247
+
248
+ toBeNull(): void {
249
+ if (negated) {
250
+ assert.notStrictEqual(actual, null, message)
251
+ } else {
252
+ assert.strictEqual(actual, null, message)
253
+ }
254
+ },
255
+
256
+ toBeTruthy(): void {
257
+ const isTruthy = Boolean(actual)
258
+ if (negated ? isTruthy : !isTruthy) {
259
+ failAssertion(
260
+ `Expected ${inspectValue(actual)} ${negated ? 'not ' : ''}to be truthy`,
261
+ actual,
262
+ !negated,
263
+ negated ? 'not toBeTruthy' : 'toBeTruthy',
264
+ message,
265
+ )
266
+ }
267
+ },
268
+
269
+ toBeFalsy(): void {
270
+ const isFalsy = !actual
271
+ if (negated ? isFalsy : !isFalsy) {
272
+ failAssertion(
273
+ `Expected ${inspectValue(actual)} ${negated ? 'not ' : ''}to be falsy`,
274
+ actual,
275
+ negated,
276
+ negated ? 'not toBeFalsy' : 'toBeFalsy',
277
+ message,
278
+ )
279
+ }
280
+ },
281
+
282
+ toContain(expected: unknown): void {
283
+ const passed = containsValue(actual, expected)
284
+ if (negated ? passed : !passed) {
285
+ failAssertion(
286
+ `Expected ${inspectValue(actual)} ${negated ? 'not ' : ''}to contain ${inspectValue(expected)}`,
287
+ actual,
288
+ expected,
289
+ negated ? 'not toContain' : 'toContain',
290
+ message,
291
+ )
292
+ }
293
+ },
294
+
295
+ toHaveLength(length: number): void {
296
+ const actualLength =
297
+ actual !== null && actual !== undefined
298
+ ? (actual as Record<string, unknown>).length
299
+ : undefined
300
+ if (typeof actualLength !== 'number') {
301
+ failAssertion(
302
+ `Expected ${inspectValue(actual)} to have a numeric length property`,
303
+ actual,
304
+ length,
305
+ 'toHaveLength',
306
+ message,
307
+ )
308
+ }
309
+ if (negated) {
310
+ if (actualLength === length) {
311
+ failAssertion(
312
+ `Expected ${inspectValue(actual)} not to have length ${length}`,
313
+ actualLength,
314
+ length,
315
+ 'not toHaveLength',
316
+ message,
317
+ )
318
+ }
319
+ } else {
320
+ assert.strictEqual(
321
+ actualLength,
322
+ length,
323
+ message ??
324
+ `Expected ${inspectValue(actual)} to have length ${length}, received ${actualLength}`,
325
+ )
326
+ }
327
+ },
328
+
329
+ toMatch(expected: string | RegExp): void {
330
+ if (typeof actual !== 'string') {
331
+ failAssertion(
332
+ `Expected a string for toMatch, received ${typeof actual} (${inspectValue(actual)})`,
333
+ actual,
334
+ expected,
335
+ 'toMatch',
336
+ message,
337
+ )
338
+ }
339
+ const passed =
340
+ expected instanceof RegExp
341
+ ? (expected.global || expected.sticky
342
+ ? new RegExp(expected.source, expected.flags)
343
+ : expected
344
+ ).test(actual)
345
+ : actual.includes(expected)
346
+ if (negated ? passed : !passed) {
347
+ failAssertion(
348
+ `Expected ${inspectValue(actual)} ${negated ? 'not ' : ''}to match ${inspectValue(expected)}`,
349
+ actual,
350
+ expected,
351
+ negated ? 'not toMatch' : 'toMatch',
352
+ message,
353
+ )
354
+ }
355
+ },
356
+
357
+ toBeGreaterThan(expected: number | bigint): void {
358
+ checkComparison(expected, '>', 'to be greater than', (a, b) => a > b)
359
+ },
360
+
361
+ toBeGreaterThanOrEqual(expected: number | bigint): void {
362
+ checkComparison(expected, '>=', 'to be greater than or equal to', (a, b) => a >= b)
363
+ },
364
+
365
+ toBeLessThan(expected: number | bigint): void {
366
+ checkComparison(expected, '<', 'to be less than', (a, b) => a < b)
367
+ },
368
+
369
+ toBeLessThanOrEqual(expected: number | bigint): void {
370
+ checkComparison(expected, '<=', 'to be less than or equal to', (a, b) => a <= b)
371
+ },
372
+
373
+ toThrow(expected?: string | RegExp | Error | ErrorConstructor): void {
374
+ if (typeof actual !== 'function') {
375
+ failAssertion(
376
+ `Expected a function for toThrow, received ${typeof actual} (${inspectValue(actual)})`,
377
+ actual,
378
+ expected,
379
+ 'toThrow',
380
+ message,
381
+ )
382
+ }
383
+ let threw = false
384
+ let thrown: unknown
385
+ try {
386
+ ;(actual as () => unknown)()
387
+ } catch (err) {
388
+ threw = true
389
+ thrown = err
390
+ }
391
+
392
+ if (!threw) {
393
+ if (!negated) {
394
+ failAssertion(
395
+ expected === undefined
396
+ ? 'Expected function to throw'
397
+ : `Expected function to throw ${inspectValue(expected)}, but it did not throw`,
398
+ undefined,
399
+ expected,
400
+ 'toThrow',
401
+ message,
402
+ )
403
+ }
404
+ return
405
+ }
406
+
407
+ if (expected === undefined) {
408
+ if (negated) {
409
+ failAssertion(
410
+ `Expected function not to throw, but it threw ${inspectValue(thrown)}`,
411
+ thrown,
412
+ undefined,
413
+ 'not toThrow',
414
+ message,
415
+ )
416
+ }
417
+ return
418
+ }
419
+
420
+ const matched = matchesThrown(thrown, expected)
421
+ if (negated ? matched : !matched) {
422
+ failAssertion(
423
+ negated
424
+ ? `Expected function not to throw matching ${inspectValue(expected)}, but it threw ${inspectValue(thrown)}`
425
+ : `Expected function to throw matching ${inspectValue(expected)}, but it threw ${inspectValue(thrown)}`,
426
+ thrown,
427
+ expected,
428
+ negated ? 'not toThrow' : 'toThrow',
429
+ message,
430
+ )
431
+ }
432
+ },
433
+ }
434
+ }
435
+
436
+ /**
437
+ * Create a zero-dependency `expect` implementation backed by `node:assert/strict`.
438
+ * Used automatically on Node.js when no custom `expect` is passed to `createSeederInstance`.
439
+ */
440
+ export function createNodeExpect(): ExpectFn {
441
+ return <T = unknown>(actual: T, message?: string): ExpectMatchers<T> =>
442
+ createMatchers(actual, message, false)
443
+ }
444
+
445
+ let cachedDefaultExpect: ExpectFn | undefined
446
+
447
+ function loadBunExpect(): ExpectFn | undefined {
448
+ if (typeof (globalThis as { Bun?: unknown }).Bun === 'undefined') return undefined
449
+ try {
450
+ const req = createRequire(import.meta.url)
451
+ // Dynamic specifier prevents bundlers and Node static analysis from resolving 'bun:test'
452
+ const specifier = ['bun', 'test'].join(':')
453
+ const mod = req(specifier) as { expect?: ExpectFn }
454
+ if (typeof mod.expect === 'function') return mod.expect
455
+ } catch {
456
+ // Fall back to the Node implementation if bun:test cannot be loaded
457
+ }
458
+ return undefined
459
+ }
460
+
461
+ /**
462
+ * Synchronously resolve the default `expect` function for the active runtime:
463
+ * `bun:test`'s `expect` on Bun, or the built-in `node:assert/strict` implementation on Node.js.
464
+ */
465
+ export function getDefaultExpect(): ExpectFn {
466
+ if (!cachedDefaultExpect) {
467
+ cachedDefaultExpect = loadBunExpect() ?? createNodeExpect()
468
+ }
469
+ return cachedDefaultExpect
470
+ }
471
+
472
+ /**
473
+ * Runtime-safe `expect` export: lazily delegates to `bun:test`'s `expect` on Bun
474
+ * and the built-in `node:assert/strict` fallback on Node.js.
475
+ */
476
+ const expectTarget = (() => {
477
+ throw new Error('unreachable')
478
+ }) as unknown as ExpectFn
479
+
480
+ export const expect: ExpectFn = new Proxy(expectTarget, {
481
+ apply(_target, thisArg, args) {
482
+ return Reflect.apply(getDefaultExpect(), thisArg, args)
483
+ },
484
+ get(_target, prop) {
485
+ const impl = getDefaultExpect()
486
+ const value = Reflect.get(impl, prop, impl)
487
+ return typeof value === 'function' ? value.bind(impl) : value
488
+ },
489
+ has(_target, prop) {
490
+ return Reflect.has(getDefaultExpect(), prop)
491
+ },
492
+ ownKeys() {
493
+ return Reflect.ownKeys(getDefaultExpect())
494
+ },
495
+ getOwnPropertyDescriptor(_target, prop) {
496
+ const desc = Reflect.getOwnPropertyDescriptor(getDefaultExpect(), prop)
497
+ return desc ? { ...desc, configurable: true } : undefined
498
+ },
499
+ getPrototypeOf() {
500
+ return Reflect.getPrototypeOf(getDefaultExpect())
501
+ },
502
+ })
package/src/formatting.ts CHANGED
@@ -1,5 +1,33 @@
1
+ import { inspect as nodeInspect } from 'node:util'
2
+ import { isSeedUsageError } from './errors.js'
1
3
  import type { SeederResult } from './types.js'
2
4
 
5
+ type BunInspectGlobal = {
6
+ Bun?: {
7
+ inspect?: (value: unknown, options?: { colors?: boolean }) => string
8
+ }
9
+ }
10
+
11
+ /**
12
+ * Runtime-safe value inspection: uses `Bun.inspect` on Bun and falls back to
13
+ * `node:util`'s `inspect` on Node.js.
14
+ */
15
+ export function inspectValue(value: unknown, options?: { colors?: boolean }): string {
16
+ const bunInspect = (globalThis as BunInspectGlobal).Bun?.inspect
17
+ if (typeof bunInspect === 'function') {
18
+ return options ? bunInspect(value, options) : bunInspect(value)
19
+ }
20
+ return nodeInspect(value, { colors: options?.colors ?? false })
21
+ }
22
+
23
+ /**
24
+ * An error as the person running the seed should see it: a usage error by its message
25
+ * alone, anything else in full (message, stack, `cause` and extra fields).
26
+ */
27
+ export function formatError(error: unknown, options?: { colors?: boolean }): string {
28
+ return isSeedUsageError(error) ? error.message : inspectValue(error, options)
29
+ }
30
+
3
31
  /**
4
32
  * ANSI color codes for terminal output
5
33
  */
@@ -125,7 +153,8 @@ const escapeAnnotation = (text: string) =>
125
153
 
126
154
  /**
127
155
  * Print error details for failed seeders: the failing step, the full error (message,
128
- * stack, cause and own fields via Bun.inspect) and a hint when cached steps ran first.
156
+ * stack, cause and own fields via Bun.inspect on Bun or util.inspect on Node.js) and
157
+ * a hint when cached steps ran first.
129
158
  * Under GitHub Actions, also prints one `::error` annotation per failed seeder.
130
159
  */
131
160
  export function printErrors(results: readonly SeederResult[]): void {
@@ -134,7 +163,7 @@ export function printErrors(results: readonly SeederResult[]): void {
134
163
  for (const result of failed) {
135
164
  const where = result.failedStep ? ` in step "${result.failedStep}"` : ''
136
165
  console.log(colorize(`❌ Seeder "${result.name}" failed${where}:`, 'red'))
137
- const details = Bun.inspect(result.error, { colors: supportsColor() })
166
+ const details = formatError(result.error, { colors: supportsColor() })
138
167
  for (const line of details.split('\n')) console.log(` ${line}`)
139
168
  if (result.cachedSteps.length > 0) {
140
169
  console.log(
@@ -154,6 +183,28 @@ export function printErrors(results: readonly SeederResult[]): void {
154
183
  }
155
184
  }
156
185
 
186
+ /**
187
+ * Print errors thrown while cleaning up (cache flush, onAfterAll, teardown, deferred
188
+ * cleanups) that are not rethrown, so a second failure is never silently lost.
189
+ */
190
+ export function printCleanupErrors(errors: readonly unknown[]): void {
191
+ for (const error of errors) {
192
+ console.error(colorize('Cleanup after the run also failed:', 'red'))
193
+ for (const line of formatError(error, { colors: supportsColor() }).split('\n')) {
194
+ console.error(` ${line}`)
195
+ }
196
+ }
197
+ }
198
+
199
+ /**
200
+ * Print that `onFresh` is about to run, before the seeders
201
+ */
202
+ export function printFreshReset(seeders: readonly string[], all: boolean): void {
203
+ const which = all ? 'every seeder runs fresh' : `fresh: ${seeders.join(', ')}`
204
+ console.log(colorize(`↺ onFresh (${which})`, 'yellow'))
205
+ console.log('')
206
+ }
207
+
157
208
  /**
158
209
  * Print seeder header before execution
159
210
  */
@@ -0,0 +1,48 @@
1
+ import type { MaybePromise } from './types.js'
2
+
3
+ /**
4
+ * Run `fn` over `items` with at most `limit` calls in flight, and resolve to the results
5
+ * in the order of `items`, whatever order the calls finish in.
6
+ *
7
+ * Fails fast: after the first call throws or rejects, no further item starts. It waits for
8
+ * the calls already in flight to settle, so nothing still runs once it rejects (with the
9
+ * first error; later errors are dropped).
10
+ *
11
+ * @param limit - A positive integer, or `Infinity` for no limit
12
+ * @throws {RangeError} When `limit` is not a positive integer or `Infinity`
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * const products = await mapWithLimit(bodies, 8, (body) => api.post('/products', body))
17
+ * ```
18
+ */
19
+ export async function mapWithLimit<Item, Result>(
20
+ items: Iterable<Item>,
21
+ limit: number,
22
+ fn: (item: Item, index: number) => MaybePromise<Result>,
23
+ ): Promise<Result[]> {
24
+ if (Number.isNaN(limit) || limit < 1 || (Number.isFinite(limit) && !Number.isInteger(limit))) {
25
+ throw new RangeError(
26
+ `Invalid limit (${String(limit)}): expected a positive integer or Infinity`,
27
+ )
28
+ }
29
+ const list = Array.from(items)
30
+ const results = new Array<Result>(list.length)
31
+ let next = 0
32
+ let failure: { error: unknown } | undefined
33
+
34
+ const worker = async () => {
35
+ while (!failure && next < list.length) {
36
+ const index = next++
37
+ try {
38
+ results[index] = await fn(list[index] as Item, index)
39
+ } catch (error) {
40
+ failure ??= { error }
41
+ }
42
+ }
43
+ }
44
+ await Promise.all(Array.from({ length: Math.min(limit, list.length) }, worker))
45
+
46
+ if (failure) throw failure.error
47
+ return results
48
+ }