@lunora/seed 1.0.0-alpha.7 → 1.0.0-alpha.71
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/LICENSE.md +6 -0
- package/dist/index.d.mts +28 -28
- package/dist/index.d.ts +28 -28
- package/dist/index.mjs +1 -2
- package/dist/packem_shared/createSeedClient-Ew_Dt82y.mjs +1 -0
- package/dist/packem_shared/plan-DRy9bg5D.mjs +1 -0
- package/dist/packem_shared/plan.d-CDkBhI-1.d.mts +88 -0
- package/dist/packem_shared/plan.d-CDkBhI-1.d.ts +88 -0
- package/dist/packem_shared/seedPlan-3bhwPxyX.mjs +1 -0
- package/dist/testing.d.mts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.mjs +1 -53
- package/package.json +5 -4
- package/dist/packem_shared/createSeedClient-CI9LRLTi.mjs +0 -92
- package/dist/packem_shared/plan-DirmkctQ.mjs +0 -497
- package/dist/packem_shared/plan.d-BQ6LiWIk.d.mts +0 -78
- package/dist/packem_shared/plan.d-BQ6LiWIk.d.ts +0 -78
- package/dist/packem_shared/seedPlan-CDSmSgjY.mjs +0 -1
package/LICENSE.md
CHANGED
|
@@ -103,3 +103,9 @@ Unless required by applicable law or agreed to in writing, software distributed
|
|
|
103
103
|
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
|
104
104
|
CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
|
105
105
|
specific language governing permissions and limitations under the License.
|
|
106
|
+
|
|
107
|
+
<!-- DEPENDENCIES -->
|
|
108
|
+
<!-- /DEPENDENCIES -->
|
|
109
|
+
|
|
110
|
+
<!-- TYPE_DEPENDENCIES -->
|
|
111
|
+
<!-- /TYPE_DEPENDENCIES -->
|
package/dist/index.d.mts
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
import { Schema } from '@lunora/server';
|
|
2
|
-
import { O as OverrideContext } from "./packem_shared/plan.d-
|
|
3
|
-
export { type S as SeedCounts, type a as SeedOptions, type b as SeedOverrides, type T as TablePlan, s as seedPlan } from "./packem_shared/plan.d-
|
|
2
|
+
import { O as OverrideContext } from "./packem_shared/plan.d-CDkBhI-1.mjs";
|
|
3
|
+
export { type S as SeedCounts, type a as SeedOptions, type b as SeedOverrides, type T as TablePlan, s as seedPlan } from "./packem_shared/plan.d-CDkBhI-1.mjs";
|
|
4
4
|
/**
|
|
5
|
-
* A typed, schema-aware seed client — the ergonomic DX layer over {@link seedPlan}.
|
|
6
|
-
*
|
|
7
|
-
* Where `seedPlan` generates every table at once, the client lets you author one
|
|
8
|
-
* table at a time, with autocomplete on each table's columns and live foreign-key
|
|
9
|
-
* connection to whatever was seeded earlier this run. Pass your generated
|
|
10
|
-
* `InsertModel` type as the type argument — or let `lunora/_generated/seed.ts`
|
|
11
|
-
* do that for you — for full type inference on each table's columns.
|
|
12
|
-
*
|
|
13
|
-
* The client is deterministic (same `seed` ⇒ same rows and ids) and pure unless a
|
|
14
|
-
* `persist` hook is supplied, in which case each generated batch is also written
|
|
15
|
-
* through it (the test harness, an admin import, …). Because every row carries an
|
|
16
|
-
* explicit `_id`, the returned ids are known whether or not anything is persisted.
|
|
17
|
-
*/
|
|
5
|
+
* A typed, schema-aware seed client — the ergonomic DX layer over {@link seedPlan}.
|
|
6
|
+
*
|
|
7
|
+
* Where `seedPlan` generates every table at once, the client lets you author one
|
|
8
|
+
* table at a time, with autocomplete on each table's columns and live foreign-key
|
|
9
|
+
* connection to whatever was seeded earlier this run. Pass your generated
|
|
10
|
+
* `InsertModel` type as the type argument — or let `lunora/_generated/seed.ts`
|
|
11
|
+
* do that for you — for full type inference on each table's columns.
|
|
12
|
+
*
|
|
13
|
+
* The client is deterministic (same `seed` ⇒ same rows and ids) and pure unless a
|
|
14
|
+
* `persist` hook is supplied, in which case each generated batch is also written
|
|
15
|
+
* through it (the test harness, an admin import, …). Because every row carries an
|
|
16
|
+
* explicit `_id`, the returned ids are known whether or not anything is persisted.
|
|
17
|
+
*/
|
|
18
18
|
/** Picks a concrete count: a fixed number, or a deterministic value within `[min, max]`. */
|
|
19
19
|
type CountHelper = (countOrRange: number | readonly [number, number]) => number;
|
|
20
20
|
/** The per-call population spec: a count, an inclusive range, explicit partial rows, or a count callback. */
|
|
@@ -23,10 +23,10 @@ type SeedSpec<Row> = number | ReadonlyArray<Partial<Row>> | readonly [number, nu
|
|
|
23
23
|
type FieldOverride<Value> = ((context: OverrideContext) => Value) | Value;
|
|
24
24
|
/** Options for a single table call. `overrides` win over any explicit partial rows. */
|
|
25
25
|
interface SeedCallOptions<Row> {
|
|
26
|
-
overrides?: { [K in keyof Row]?: FieldOverride<Row[K]
|
|
26
|
+
overrides?: { [K in keyof Row]?: FieldOverride<Row[K]>; };
|
|
27
27
|
}
|
|
28
28
|
/** The id columns the client emits, keyed by table — the result of a single table call. */
|
|
29
|
-
type SeedCallResult<InsertModel, Table extends keyof InsertModel> = { [K in Table]: string[] };
|
|
29
|
+
type SeedCallResult<InsertModel, Table extends keyof InsertModel> = { [K in Table]: string[]; };
|
|
30
30
|
/** The seeder function exposed for one table. */
|
|
31
31
|
type TableSeeder<InsertModel, Table extends keyof InsertModel> = (spec?: SeedSpec<InsertModel[Table]>, options?: SeedCallOptions<InsertModel[Table]>) => Promise<SeedCallResult<InsertModel, Table>>;
|
|
32
32
|
/** The `$`-prefixed run state shared by every client. */
|
|
@@ -39,7 +39,7 @@ interface SeedClientState {
|
|
|
39
39
|
readonly $store: Readonly<Record<string, ReadonlyArray<Record<string, unknown>>>>;
|
|
40
40
|
}
|
|
41
41
|
/** The per-table seeder methods plus the `$`-prefixed run state. */
|
|
42
|
-
type SeedClient<InsertModel> = SeedClientState & { [Table in keyof InsertModel]: TableSeeder<InsertModel, Table
|
|
42
|
+
type SeedClient<InsertModel> = SeedClientState & { [Table in keyof InsertModel]: TableSeeder<InsertModel, Table>; };
|
|
43
43
|
/** Options for {@link createSeedClient}. */
|
|
44
44
|
interface SeedClientOptions {
|
|
45
45
|
/** Default row count when a table call passes no spec (default `10`). */
|
|
@@ -50,15 +50,15 @@ interface SeedClientOptions {
|
|
|
50
50
|
seed?: number;
|
|
51
51
|
}
|
|
52
52
|
/**
|
|
53
|
-
* Create a typed seed client for `schema`. Each table is a method; call it with a
|
|
54
|
-
* count, a range, or explicit partial rows, and its foreign keys connect to rows
|
|
55
|
-
* seeded earlier this run. State accumulates on `$store`/`$ids` and clears with
|
|
56
|
-
* `$reset()`.
|
|
57
|
-
* @example
|
|
58
|
-
* const seed = createSeedClient<InsertModel>(schema, { seed: 1 });
|
|
59
|
-
* const { users } = await seed.users(5);
|
|
60
|
-
* const { posts } = await seed.posts((x) => x([10, 20]));
|
|
61
|
-
* // posts.authorId values are drawn from `users`.
|
|
62
|
-
*/
|
|
53
|
+
* Create a typed seed client for `schema`. Each table is a method; call it with a
|
|
54
|
+
* count, a range, or explicit partial rows, and its foreign keys connect to rows
|
|
55
|
+
* seeded earlier this run. State accumulates on `$store`/`$ids` and clears with
|
|
56
|
+
* `$reset()`.
|
|
57
|
+
* @example
|
|
58
|
+
* const seed = createSeedClient<InsertModel>(schema, { seed: 1 });
|
|
59
|
+
* const { users } = await seed.users(5);
|
|
60
|
+
* const { posts } = await seed.posts((x) => x([10, 20]));
|
|
61
|
+
* // posts.authorId values are drawn from `users`.
|
|
62
|
+
*/
|
|
63
63
|
declare const createSeedClient: <InsertModel = Record<string, Record<string, unknown>>>(schema: Schema, options?: SeedClientOptions) => SeedClient<InsertModel>;
|
|
64
64
|
export { type CountHelper, type OverrideContext, type SeedCallOptions, type SeedCallResult, type SeedClient, type SeedClientOptions, type SeedSpec, createSeedClient };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
import { Schema } from '@lunora/server';
|
|
2
|
-
import { O as OverrideContext } from "./packem_shared/plan.d-
|
|
3
|
-
export { type S as SeedCounts, type a as SeedOptions, type b as SeedOverrides, type T as TablePlan, s as seedPlan } from "./packem_shared/plan.d-
|
|
2
|
+
import { O as OverrideContext } from "./packem_shared/plan.d-CDkBhI-1.js";
|
|
3
|
+
export { type S as SeedCounts, type a as SeedOptions, type b as SeedOverrides, type T as TablePlan, s as seedPlan } from "./packem_shared/plan.d-CDkBhI-1.js";
|
|
4
4
|
/**
|
|
5
|
-
* A typed, schema-aware seed client — the ergonomic DX layer over {@link seedPlan}.
|
|
6
|
-
*
|
|
7
|
-
* Where `seedPlan` generates every table at once, the client lets you author one
|
|
8
|
-
* table at a time, with autocomplete on each table's columns and live foreign-key
|
|
9
|
-
* connection to whatever was seeded earlier this run. Pass your generated
|
|
10
|
-
* `InsertModel` type as the type argument — or let `lunora/_generated/seed.ts`
|
|
11
|
-
* do that for you — for full type inference on each table's columns.
|
|
12
|
-
*
|
|
13
|
-
* The client is deterministic (same `seed` ⇒ same rows and ids) and pure unless a
|
|
14
|
-
* `persist` hook is supplied, in which case each generated batch is also written
|
|
15
|
-
* through it (the test harness, an admin import, …). Because every row carries an
|
|
16
|
-
* explicit `_id`, the returned ids are known whether or not anything is persisted.
|
|
17
|
-
*/
|
|
5
|
+
* A typed, schema-aware seed client — the ergonomic DX layer over {@link seedPlan}.
|
|
6
|
+
*
|
|
7
|
+
* Where `seedPlan` generates every table at once, the client lets you author one
|
|
8
|
+
* table at a time, with autocomplete on each table's columns and live foreign-key
|
|
9
|
+
* connection to whatever was seeded earlier this run. Pass your generated
|
|
10
|
+
* `InsertModel` type as the type argument — or let `lunora/_generated/seed.ts`
|
|
11
|
+
* do that for you — for full type inference on each table's columns.
|
|
12
|
+
*
|
|
13
|
+
* The client is deterministic (same `seed` ⇒ same rows and ids) and pure unless a
|
|
14
|
+
* `persist` hook is supplied, in which case each generated batch is also written
|
|
15
|
+
* through it (the test harness, an admin import, …). Because every row carries an
|
|
16
|
+
* explicit `_id`, the returned ids are known whether or not anything is persisted.
|
|
17
|
+
*/
|
|
18
18
|
/** Picks a concrete count: a fixed number, or a deterministic value within `[min, max]`. */
|
|
19
19
|
type CountHelper = (countOrRange: number | readonly [number, number]) => number;
|
|
20
20
|
/** The per-call population spec: a count, an inclusive range, explicit partial rows, or a count callback. */
|
|
@@ -23,10 +23,10 @@ type SeedSpec<Row> = number | ReadonlyArray<Partial<Row>> | readonly [number, nu
|
|
|
23
23
|
type FieldOverride<Value> = ((context: OverrideContext) => Value) | Value;
|
|
24
24
|
/** Options for a single table call. `overrides` win over any explicit partial rows. */
|
|
25
25
|
interface SeedCallOptions<Row> {
|
|
26
|
-
overrides?: { [K in keyof Row]?: FieldOverride<Row[K]
|
|
26
|
+
overrides?: { [K in keyof Row]?: FieldOverride<Row[K]>; };
|
|
27
27
|
}
|
|
28
28
|
/** The id columns the client emits, keyed by table — the result of a single table call. */
|
|
29
|
-
type SeedCallResult<InsertModel, Table extends keyof InsertModel> = { [K in Table]: string[] };
|
|
29
|
+
type SeedCallResult<InsertModel, Table extends keyof InsertModel> = { [K in Table]: string[]; };
|
|
30
30
|
/** The seeder function exposed for one table. */
|
|
31
31
|
type TableSeeder<InsertModel, Table extends keyof InsertModel> = (spec?: SeedSpec<InsertModel[Table]>, options?: SeedCallOptions<InsertModel[Table]>) => Promise<SeedCallResult<InsertModel, Table>>;
|
|
32
32
|
/** The `$`-prefixed run state shared by every client. */
|
|
@@ -39,7 +39,7 @@ interface SeedClientState {
|
|
|
39
39
|
readonly $store: Readonly<Record<string, ReadonlyArray<Record<string, unknown>>>>;
|
|
40
40
|
}
|
|
41
41
|
/** The per-table seeder methods plus the `$`-prefixed run state. */
|
|
42
|
-
type SeedClient<InsertModel> = SeedClientState & { [Table in keyof InsertModel]: TableSeeder<InsertModel, Table
|
|
42
|
+
type SeedClient<InsertModel> = SeedClientState & { [Table in keyof InsertModel]: TableSeeder<InsertModel, Table>; };
|
|
43
43
|
/** Options for {@link createSeedClient}. */
|
|
44
44
|
interface SeedClientOptions {
|
|
45
45
|
/** Default row count when a table call passes no spec (default `10`). */
|
|
@@ -50,15 +50,15 @@ interface SeedClientOptions {
|
|
|
50
50
|
seed?: number;
|
|
51
51
|
}
|
|
52
52
|
/**
|
|
53
|
-
* Create a typed seed client for `schema`. Each table is a method; call it with a
|
|
54
|
-
* count, a range, or explicit partial rows, and its foreign keys connect to rows
|
|
55
|
-
* seeded earlier this run. State accumulates on `$store`/`$ids` and clears with
|
|
56
|
-
* `$reset()`.
|
|
57
|
-
* @example
|
|
58
|
-
* const seed = createSeedClient<InsertModel>(schema, { seed: 1 });
|
|
59
|
-
* const { users } = await seed.users(5);
|
|
60
|
-
* const { posts } = await seed.posts((x) => x([10, 20]));
|
|
61
|
-
* // posts.authorId values are drawn from `users`.
|
|
62
|
-
*/
|
|
53
|
+
* Create a typed seed client for `schema`. Each table is a method; call it with a
|
|
54
|
+
* count, a range, or explicit partial rows, and its foreign keys connect to rows
|
|
55
|
+
* seeded earlier this run. State accumulates on `$store`/`$ids` and clears with
|
|
56
|
+
* `$reset()`.
|
|
57
|
+
* @example
|
|
58
|
+
* const seed = createSeedClient<InsertModel>(schema, { seed: 1 });
|
|
59
|
+
* const { users } = await seed.users(5);
|
|
60
|
+
* const { posts } = await seed.posts((x) => x([10, 20]));
|
|
61
|
+
* // posts.authorId values are drawn from `users`.
|
|
62
|
+
*/
|
|
63
63
|
declare const createSeedClient: <InsertModel = Record<string, Record<string, unknown>>>(schema: Schema, options?: SeedClientOptions) => SeedClient<InsertModel>;
|
|
64
64
|
export { type CountHelper, type OverrideContext, type SeedCallOptions, type SeedCallResult, type SeedClient, type SeedClientOptions, type SeedSpec, createSeedClient };
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export { s as seedPlan } from './packem_shared/plan-DirmkctQ.mjs';
|
|
1
|
+
import{createSeedClient as o}from"./packem_shared/createSeedClient-Ew_Dt82y.mjs";import{V as a}from"./packem_shared/plan-DRy9bg5D.mjs";export{o as createSeedClient,a as seedPlan};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{l as k,V as $,w as C}from"./plan-DRy9bg5D.mjs";const S=t=>Array.isArray(t)&&t.length===2&&typeof t[0]=="number"&&typeof t[1]=="number",A=(t,u,l,s)=>{const n=o=>typeof o=="number"?o:C.int([l,u,"count"],{max:o[1],min:o[0]});return t===void 0?{count:s}:typeof t=="number"?{count:t}:typeof t=="function"?{count:t(n)}:S(t)?{count:n(t)}:{count:t.length,partials:t}},M=(t,u,l)=>{const s={};if(t!==void 0){const n=new Set(t.flatMap(o=>Object.keys(o)));for(const o of n)s[o]=c=>t[c.index-l]?.[o]}for(const[n,o]of Object.entries(u??{}))s[n]=o;return s},R=(t,u={})=>{const{defaultCount:l=10,persist:s,seed:n=0}=u,o={},c={},a={},O=async(e,r,d)=>{k(n);const{count:f,partials:y}=A(r,e,n,l),m=a[e]??0,v=$(t,{counts:{[e]:f},existingIds:c,indexOffset:{[e]:m},only:[e],overrides:{[e]:M(y,d?.overrides,m)},seed:n});let h=[];for(const{rows:p,table:i}of v){const g=p.map(x=>x._id);o[i]??=[],o[i].push(...p),c[i]??=[],c[i].push(...g),a[i]=(a[i]??0)+p.length,i===e&&(h=g),s!==void 0&&await s(i,p)}return{[e]:h}};let b=Promise.resolve();const j=(e,r,d)=>{const f=b.then(()=>O(e,r,d));return b=f.then(()=>{},()=>{}),f},w={$ids:c,$reset:()=>{for(const e of Object.keys(o))delete o[e];for(const e of Object.keys(c))delete c[e];for(const e of Object.keys(a))delete a[e]},$store:o};return new Proxy(w,{get(e,r,d){return typeof r=="string"&&!r.startsWith("$")&&Object.hasOwn(t.tables,r)?(f,y)=>j(r,f,y):Reflect.get(e,r,d)}})};export{R as createSeedClient};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as $}from"@lunora/errors";import{faker as m}from"@faker-js/faker";import{optionalInner as C}from"@lunora/values";let x=0;const q=(e,n)=>e<n?-1:e>n?1:0,O=e=>e===void 0?"undefined":typeof e=="bigint"?`${e.toString()}n`:e===null||typeof e!="object"?JSON.stringify(e)??"null":Array.isArray(e)?`[${e.map(n=>O(n)).join(",")}]`:`{${Object.keys(e).toSorted(q).map(n=>`${JSON.stringify(n)}:${O(e[n])}`).join(",")}}`,V=(e,n)=>{let t=3735928559^n,o=1103547991^n;for(let a=0;a<e.length;a+=1){const i=e.codePointAt(a)??0;t=Math.imul(t^i,2654435761),o=Math.imul(o^i,1597334677)}return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(t^t>>>13,3266489909),4294967296*(2097151&o)+(t>>>0)},G="\0",H=e=>{const n=typeof e=="string"?G+e:O(e);return V(n,x)%4294967296},K=e=>{if(typeof e=="number"){x=e>>>0;return}if(typeof e=="string"){x=V(e,0)%4294967296;return}let n=0;for(const t of e)n=Math.imul(n^t,2654435761)>>>0;x=n},d=(e,n)=>(m.seed(H(e)),n()),W=(e,n)=>{if(typeof n=="number")return n;const[t,o]=n;return d(["__count__",e],()=>m.number.int({max:o,min:t}))},X=/[a-z]/,Y=/[A-Z]/,ee=/\d/,u={bool(e){return d(e,()=>m.datatype.boolean())},city(e){return d(e,()=>m.location.city())},country(e){return d(e,()=>m.location.country())},dateString(e,n){const t=n?.min??new Date("1980-01-01T00:00:00.000Z"),o=n?.max??new Date("2020-01-01T00:00:00.000Z");return d(e,()=>m.date.between({from:t,to:o}).toISOString())},email(e){return d(e,()=>m.internet.email().toLowerCase())},firstName(e){return d(e,()=>m.person.firstName())},float(e,n){const{fractionDigits:t=2,max:o=1e3,min:a=0}=n??{};return d(e,()=>m.number.float({fractionDigits:t,max:o,min:a}))},fullName(e){return d(e,()=>m.person.fullName())},int(e,n){const{max:t=1e3,min:o=0}=n??{};return d(e,()=>m.number.int({max:t,min:o}))},lastName(e){return d(e,()=>m.person.lastName())},oneOf(e,n){if(n.length!==0)return d(e,()=>m.helpers.arrayElement(n))},paragraph(e){return d(e,()=>m.lorem.paragraph())},password(e){return d(e,()=>m.internet.password())},phoneNumber(e){return d(e,()=>m.phone.number())},scramble(e,n){const t=new Set(n?.preserve);return Array.from({length:e.length},(o,a)=>{const i=e.charAt(a);return t.has(i)?i:X.test(i)?d([e,a,"l"],()=>m.string.alpha({casing:"lower",length:1})):Y.test(i)?d([e,a,"u"],()=>m.string.alpha({casing:"upper",length:1})):ee.test(i)?d([e,a,"d"],()=>String(m.number.int({max:9,min:0}))):i}).join("")},sentence(e,n){return d(e,()=>m.lorem.sentence(n?{max:n.max??8,min:n.min??3}:void 0))},slug(e){return d(e,()=>m.lorem.slug())},streetAddress(e){return d(e,()=>m.location.streetAddress())},times(e,n,t){const o=W(e,n),a=[];for(let i=0;i<o;i+=1)a.push(t([e,i]));return a},url(e){return d(e,()=>m.internet.url())},username(e){return d(e,()=>m.internet.username())},uuid(e){return d(e,()=>m.string.uuid())},word(e){return d(e,()=>m.lorem.word())}},h=e=>e._meta??{},Z=e=>C(e)??e,z=e=>{const{column:n}=h(e);if(n?.defaultValue!==void 0||n?.defaultFn!==void 0)return!0;const t=C(e);return t===void 0?!1:z(t)},ne=(e,n)=>{const t=Z(n),o=h(t);return{fkTable:t.kind==="id"?o.tableName:void 0,hasServerDefault:z(n),kind:t.kind,name:e,nullable:o.column?.notNull===!1,optional:n.kind==="optional",validator:t}},te=e=>{const{tables:n}=e;return Object.entries(n).map(([t,o])=>({fields:Object.entries(o.shape).map(([a,i])=>ne(a,i)),name:t}))},re=(e,n)=>{const t=new Map(e.map(r=>[r.name,r])),o=r=>{const l=t.get(r);if(l===void 0)return new Set;const f=new Set;for(const g of l.fields)g.fkTable!==void 0&&g.fkTable!==r&&n.has(g.fkTable)&&f.add(g.fkTable);return f},a=[],i=new Set,s=[...n].filter(r=>t.has(r));for(;s.length>0;){const r=s.findIndex(g=>[...o(g)].every(w=>i.has(w))),l=r===-1?0:r,[f]=s.splice(l,1);if(f===void 0)break;a.push(f),i.add(f)}return a},oe=(e,n,t=new Set)=>{const o=new Map(e.map(s=>[s.name,s])),a=new Set(n),i=[...a];for(;i.length>0;){const s=i.pop();if(s===void 0)break;const r=o.get(s);if(r!==void 0&&!t.has(s))for(const l of r.fields)l.fkTable!==void 0&&l.fkTable!==s&&o.has(l.fkTable)&&!a.has(l.fkTable)&&(a.add(l.fkTable),i.push(l.fkTable))}return a},ae=e=>h(e).constraints??{},se=[{generate:e=>u.email(e),keywords:["email"]},{generate:e=>u.firstName(e),keywords:["firstname"]},{generate:e=>u.lastName(e),keywords:["lastname","surname"]},{generate:e=>u.username(e),keywords:["username"]},{generate:e=>u.fullName(e),keywords:["name"]},{generate:e=>u.sentence(e,{max:5,min:2}),keywords:["title"]},{generate:e=>u.url(e),keywords:["url","link","image","avatar"]},{generate:e=>u.phoneNumber(e),keywords:["phone"]},{generate:e=>u.paragraph(e),keywords:["description","bio","body","content","text"]},{generate:e=>u.slug(e),keywords:["slug","key","code"]},{generate:e=>u.city(e),keywords:["city"]},{generate:e=>u.country(e),keywords:["country"]},{generate:e=>u.streetAddress(e),keywords:["address","street"]},{generate:e=>u.password(e),keywords:["password","secret","token"]}],ie=new Set(["at","date","deadline","expires","expiry","since","timestamp","until"]),ue=/([a-z\d])([A-Z])/gu,le=/[\s_-]+/u,me=e=>e.replaceAll(ue,"$1 $2").split(le).filter(n=>n!=="").map(n=>n.toLowerCase()),de=4320*60*60*1e3,ce=e=>{const n=me(e).at(-1);return n!==void 0&&ie.has(n)},fe=(e,n)=>n-u.int(e,{max:de,min:0}),ge=(e,n,t)=>{const o=e.toLowerCase(),a=se.find(f=>f.keywords.some(g=>o.includes(g))),i=a===void 0?u.word(n):a.generate(n),{maxLength:s,minLength:r}=t;if(s!==void 0&&r!==void 0&&r>s)throw new $("INTERNAL",`Seed constraint error for field "${e}": minLength (${String(r)}) > maxLength (${String(s)}). Adjust the schema constraints.`);const l=s!==void 0&&i.length>s?i.slice(0,s):i;return r!==void 0&&l.length<r?l.padEnd(r,l.length>0?l:"x"):l},y=(e,n,t,o)=>{const a=Z(e),i=ae(a);if(i.enum!==void 0&&i.enum.length>0)return u.oneOf(t,i.enum);switch(a.kind){case"any":return u.word(t);case"array":{const s=h(a).inner;return s===void 0?[]:u.times(t,[1,3],r=>y(s,n,r,o))}case"bigint":return u.int(t,{max:1e6,min:0});case"boolean":return u.bool(t);case"bytes":return Array.from({length:8},(s,r)=>u.int([t,r],{max:255,min:0}));case"date":case"timestamp":return new Date(u.dateString(t)).getTime();case"from":throw new $("INTERNAL",`@lunora/seed: column "${n}" is a v.from() validator, whose external Standard Schema the seeder cannot introspect to invent a conforming value. Supply one via \`overrides\` (\`{ <table>: { ${n}: … } }\`), restrict the run with \`only\` so the table is skipped, or give the column a concrete v.* type.`);case"id":return u.uuid(t);case"literal":return h(a).value;case"null":return null;case"number":{const{maximum:s,minimum:r}=i;if(s===void 0&&r===void 0&&ce(n))return fe(t,o);if(s!==void 0&&r!==void 0&&r>s)throw new $("INTERNAL",`Seed constraint error for field "${n}": minimum (${String(r)}) > maximum (${String(s)}). Adjust the schema constraints.`);const l=r??0,f=s??1e3;return!Number.isInteger(l)||!Number.isInteger(f)?u.float(t,{max:f,min:l}):u.int(t,{max:f,min:l})}case"object":{const s=h(a).shape??{};return Object.fromEntries(Object.entries(s).map(([r,l])=>[r,y(l,r,[t,r],o)]))}case"record":{const{keyValidator:s,valueValidator:r}=h(a),l=u.times(t,[1,3],f=>{const g=s===void 0?u.word(["k",f]):String(y(s,n,["k",f],o)),w=r===void 0?u.word(["v",f]):y(r,n,["v",f],o);return[g,w]});return Object.fromEntries(l)}case"storage":return`seed/${u.uuid(t)}`;case"string":return ge(n,t,i);case"union":{const s=h(a).members??[],r=u.oneOf(t,s);return r===void 0?u.word(t):y(r,n,[t,"u"],o)}default:return u.word(t)}},pe=(e,n)=>typeof e=="function"?e(n):e,he=(e,n)=>{if(!e.optional)return e.nullable?null:u.uuid(n)},we=(e,n,t,o,a)=>{const i=e.fkTable,s=i===n?(o.get(n)??[]).slice(0,t):o.get(i)??[],r=a[i]??[];return r.length===0?s:[...s,...r]},R=(e,n,t,o)=>[e,n,t,o],be=(e,n,t,o,a,i,s)=>{if(e.fkTable!==void 0){const r=we(e,n,o,a,i);return r.length===0?he(e,t):u.oneOf(t,r)}if(!e.hasServerDefault)return y(e.validator,e.name,t,s)},Se=(e,n={})=>{const{counts:t={},defaultCount:o=10,existingIds:a={},indexOffset:i={},now:s=Date.now(),only:r,overrides:l={},seed:f=0}=n;K(f);const g=te(e);if(r!==void 0){const c=new Set(g.map(b=>b.name));for(const b of r)if(!c.has(b)){const k=g.map(N=>N.name).join(", ");throw new $("BAD_REQUEST",`unknown table "${b}" in seed \`only\` — schema defines: ${k||"(no tables)"}`)}}const w=new Set(r??g.map(c=>c.name)),F=new Set(Object.keys(a).filter(c=>!w.has(c)&&(a[c]??[]).length>0)),J=new Set([...oe(g,w,F)].filter(c=>w.has(c)||(a[c]??[]).length===0)),P=re(g,J),Q=new Map(g.map(c=>[c.name,c])),j=new Map,L={},M=[];for(const c of P){const b=Q.get(c);if(b===void 0)continue;const k=l[c]??{},N=t[c]??o,U=i[c]??0,_=[];j.set(c,_);const T=[];L[c]=T;for(let S=0;S<N;S+=1){const A=U+S,v={},E=(p,B)=>{if(Object.hasOwn(k,p)){const D=pe(k[p],{field:p,index:A,row:v,store:L,table:c});if(D!==void 0){v[p]=D;return}}const I=B();I!==void 0&&(v[p]=I)};E("_id",()=>u.uuid(R(f,c,A,"_id"))),_.push(v._id);for(const p of b.fields)E(p.name,()=>be(p,c,R(f,c,A,p.name),S,j,a,s));T.push(v)}M.push({rows:T,table:c})}return M};export{te as S,Se as V,K as l,u as w};
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { Schema } from '@lunora/server';
|
|
2
|
+
/**
|
|
3
|
+
* The pure, I/O-free core of seeding. {@link seedPlan} introspects a schema,
|
|
4
|
+
* generates rows table-by-table in foreign-key order, and resolves every
|
|
5
|
+
* `v.id("parent")` column to a real id of an already-generated parent row. The
|
|
6
|
+
* result feeds every adapter (test harness, CLI, studio) — none of them
|
|
7
|
+
* re-implement generation.
|
|
8
|
+
*
|
|
9
|
+
* Determinism: a `seed` value selects the global copycat mapping, and each value
|
|
10
|
+
* is hashed from `[seed, table, index, field]`, so the same `(schema, options)`
|
|
11
|
+
* always yields byte-identical rows.
|
|
12
|
+
*/
|
|
13
|
+
/** A row context handed to an override function. */
|
|
14
|
+
interface OverrideContext {
|
|
15
|
+
field: string;
|
|
16
|
+
/** The row's absolute index (the `indexOffset` base plus its position in this batch). */
|
|
17
|
+
index: number;
|
|
18
|
+
/** The row built so far (system `_id` first, then earlier fields). */
|
|
19
|
+
row: Record<string, unknown>;
|
|
20
|
+
/**
|
|
21
|
+
* A live, read-only view of every table's rows generated so far this run,
|
|
22
|
+
* keyed by table name. Lets an override correlate across tables (e.g. copy a
|
|
23
|
+
* field from the parent row a foreign key points at). Rows for the current
|
|
24
|
+
* table accumulate as they are built, so only earlier rows are visible.
|
|
25
|
+
*/
|
|
26
|
+
store: Readonly<Record<string, ReadonlyArray<Record<string, unknown>>>>;
|
|
27
|
+
table: string;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Per-table, per-field overrides. Each override is a static value or a function
|
|
31
|
+
* of the row context; field `_id` overrides the generated primary key.
|
|
32
|
+
*/
|
|
33
|
+
type SeedOverrides = Record<string, Record<string, unknown>>;
|
|
34
|
+
/** Per-table row counts. */
|
|
35
|
+
type SeedCounts = Record<string, number>;
|
|
36
|
+
interface SeedOptions {
|
|
37
|
+
/** Rows per table; falls back to {@link SeedOptions.defaultCount} when a table is absent. */
|
|
38
|
+
counts?: SeedCounts;
|
|
39
|
+
/** Count used for any selected table not present in `counts` (default `10`). */
|
|
40
|
+
defaultCount?: number;
|
|
41
|
+
/**
|
|
42
|
+
* Ids of rows that already exist in the target store, keyed by table. Foreign
|
|
43
|
+
* keys may resolve to these in addition to freshly-seeded parents, and a
|
|
44
|
+
* parent table fully covered here is not re-seeded when it is only pulled in
|
|
45
|
+
* as an FK dependency (it is when named explicitly in `only`).
|
|
46
|
+
*/
|
|
47
|
+
existingIds?: Readonly<Record<string, ReadonlyArray<string>>>;
|
|
48
|
+
/**
|
|
49
|
+
* Per-table absolute index base for generation. Defaults to `0`. A client
|
|
50
|
+
* seeding the same table across several calls passes the running total so
|
|
51
|
+
* each batch hashes from fresh indices and never collides ids with an
|
|
52
|
+
* earlier batch.
|
|
53
|
+
*/
|
|
54
|
+
indexOffset?: Readonly<Record<string, number>>;
|
|
55
|
+
/**
|
|
56
|
+
* Wall-clock reference for time-valued columns (`createdAt`, `expiresAt`, …),
|
|
57
|
+
* as epoch-ms. Defaults to now.
|
|
58
|
+
*
|
|
59
|
+
* Pin it to make a plan byte-for-byte reproducible: seeding is deterministic
|
|
60
|
+
* in `seed` alone for every other column, and this is the one input that
|
|
61
|
+
* would otherwise drift between runs. A pinned `(seed, now)` pair is what
|
|
62
|
+
* makes a seeded screenshot, test fixture, or bug report replayable.
|
|
63
|
+
*/
|
|
64
|
+
now?: number;
|
|
65
|
+
/**
|
|
66
|
+
* Restrict seeding to these tables. Transitive `v.id(...)` parents are added
|
|
67
|
+
* automatically (unless already covered by `existingIds`) so child foreign
|
|
68
|
+
* keys resolve to real rows. The result is still ordered by FK dependency.
|
|
69
|
+
* Default: all tables.
|
|
70
|
+
*/
|
|
71
|
+
only?: ReadonlyArray<string>;
|
|
72
|
+
/** Static values or functions overriding generated columns. */
|
|
73
|
+
overrides?: SeedOverrides;
|
|
74
|
+
/** Deterministic mapping selector — same seed ⇒ same rows. Default `0`. */
|
|
75
|
+
seed?: number;
|
|
76
|
+
}
|
|
77
|
+
/** One table's generated rows, in insert order. Each row carries an explicit `_id`. */
|
|
78
|
+
interface TablePlan {
|
|
79
|
+
rows: ReadonlyArray<Record<string, unknown>>;
|
|
80
|
+
table: string;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Build a deterministic, FK-consistent set of rows for `schema`.
|
|
84
|
+
* @returns one {@link TablePlan} per seeded table, ordered so a table's FK
|
|
85
|
+
* parents come before it.
|
|
86
|
+
*/
|
|
87
|
+
declare const seedPlan: (schema: Schema, options?: SeedOptions) => ReadonlyArray<TablePlan>;
|
|
88
|
+
export { OverrideContext as O, SeedCounts as S, TablePlan as T, SeedOptions as a, SeedOverrides as b, seedPlan as s };
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { Schema } from '@lunora/server';
|
|
2
|
+
/**
|
|
3
|
+
* The pure, I/O-free core of seeding. {@link seedPlan} introspects a schema,
|
|
4
|
+
* generates rows table-by-table in foreign-key order, and resolves every
|
|
5
|
+
* `v.id("parent")` column to a real id of an already-generated parent row. The
|
|
6
|
+
* result feeds every adapter (test harness, CLI, studio) — none of them
|
|
7
|
+
* re-implement generation.
|
|
8
|
+
*
|
|
9
|
+
* Determinism: a `seed` value selects the global copycat mapping, and each value
|
|
10
|
+
* is hashed from `[seed, table, index, field]`, so the same `(schema, options)`
|
|
11
|
+
* always yields byte-identical rows.
|
|
12
|
+
*/
|
|
13
|
+
/** A row context handed to an override function. */
|
|
14
|
+
interface OverrideContext {
|
|
15
|
+
field: string;
|
|
16
|
+
/** The row's absolute index (the `indexOffset` base plus its position in this batch). */
|
|
17
|
+
index: number;
|
|
18
|
+
/** The row built so far (system `_id` first, then earlier fields). */
|
|
19
|
+
row: Record<string, unknown>;
|
|
20
|
+
/**
|
|
21
|
+
* A live, read-only view of every table's rows generated so far this run,
|
|
22
|
+
* keyed by table name. Lets an override correlate across tables (e.g. copy a
|
|
23
|
+
* field from the parent row a foreign key points at). Rows for the current
|
|
24
|
+
* table accumulate as they are built, so only earlier rows are visible.
|
|
25
|
+
*/
|
|
26
|
+
store: Readonly<Record<string, ReadonlyArray<Record<string, unknown>>>>;
|
|
27
|
+
table: string;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Per-table, per-field overrides. Each override is a static value or a function
|
|
31
|
+
* of the row context; field `_id` overrides the generated primary key.
|
|
32
|
+
*/
|
|
33
|
+
type SeedOverrides = Record<string, Record<string, unknown>>;
|
|
34
|
+
/** Per-table row counts. */
|
|
35
|
+
type SeedCounts = Record<string, number>;
|
|
36
|
+
interface SeedOptions {
|
|
37
|
+
/** Rows per table; falls back to {@link SeedOptions.defaultCount} when a table is absent. */
|
|
38
|
+
counts?: SeedCounts;
|
|
39
|
+
/** Count used for any selected table not present in `counts` (default `10`). */
|
|
40
|
+
defaultCount?: number;
|
|
41
|
+
/**
|
|
42
|
+
* Ids of rows that already exist in the target store, keyed by table. Foreign
|
|
43
|
+
* keys may resolve to these in addition to freshly-seeded parents, and a
|
|
44
|
+
* parent table fully covered here is not re-seeded when it is only pulled in
|
|
45
|
+
* as an FK dependency (it is when named explicitly in `only`).
|
|
46
|
+
*/
|
|
47
|
+
existingIds?: Readonly<Record<string, ReadonlyArray<string>>>;
|
|
48
|
+
/**
|
|
49
|
+
* Per-table absolute index base for generation. Defaults to `0`. A client
|
|
50
|
+
* seeding the same table across several calls passes the running total so
|
|
51
|
+
* each batch hashes from fresh indices and never collides ids with an
|
|
52
|
+
* earlier batch.
|
|
53
|
+
*/
|
|
54
|
+
indexOffset?: Readonly<Record<string, number>>;
|
|
55
|
+
/**
|
|
56
|
+
* Wall-clock reference for time-valued columns (`createdAt`, `expiresAt`, …),
|
|
57
|
+
* as epoch-ms. Defaults to now.
|
|
58
|
+
*
|
|
59
|
+
* Pin it to make a plan byte-for-byte reproducible: seeding is deterministic
|
|
60
|
+
* in `seed` alone for every other column, and this is the one input that
|
|
61
|
+
* would otherwise drift between runs. A pinned `(seed, now)` pair is what
|
|
62
|
+
* makes a seeded screenshot, test fixture, or bug report replayable.
|
|
63
|
+
*/
|
|
64
|
+
now?: number;
|
|
65
|
+
/**
|
|
66
|
+
* Restrict seeding to these tables. Transitive `v.id(...)` parents are added
|
|
67
|
+
* automatically (unless already covered by `existingIds`) so child foreign
|
|
68
|
+
* keys resolve to real rows. The result is still ordered by FK dependency.
|
|
69
|
+
* Default: all tables.
|
|
70
|
+
*/
|
|
71
|
+
only?: ReadonlyArray<string>;
|
|
72
|
+
/** Static values or functions overriding generated columns. */
|
|
73
|
+
overrides?: SeedOverrides;
|
|
74
|
+
/** Deterministic mapping selector — same seed ⇒ same rows. Default `0`. */
|
|
75
|
+
seed?: number;
|
|
76
|
+
}
|
|
77
|
+
/** One table's generated rows, in insert order. Each row carries an explicit `_id`. */
|
|
78
|
+
interface TablePlan {
|
|
79
|
+
rows: ReadonlyArray<Record<string, unknown>>;
|
|
80
|
+
table: string;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Build a deterministic, FK-consistent set of rows for `schema`.
|
|
84
|
+
* @returns one {@link TablePlan} per seeded table, ordered so a table's FK
|
|
85
|
+
* parents come before it.
|
|
86
|
+
*/
|
|
87
|
+
declare const seedPlan: (schema: Schema, options?: SeedOptions) => ReadonlyArray<TablePlan>;
|
|
88
|
+
export { OverrideContext as O, SeedCounts as S, TablePlan as T, SeedOptions as a, SeedOverrides as b, seedPlan as s };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"@lunora/errors";import{V as a}from"./plan-DRy9bg5D.mjs";export{a as seedPlan};
|
package/dist/testing.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Schema } from '@lunora/server';
|
|
2
2
|
import { TestHarness } from '@lunora/testing';
|
|
3
|
-
import { a as SeedOptions } from "./packem_shared/plan.d-
|
|
3
|
+
import { a as SeedOptions } from "./packem_shared/plan.d-CDkBhI-1.mjs";
|
|
4
4
|
declare const seed: (harness: TestHarness, schema: Schema, options?: SeedOptions) => Promise<Record<string, string[]>>;
|
|
5
5
|
export { seed };
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Schema } from '@lunora/server';
|
|
2
2
|
import { TestHarness } from '@lunora/testing';
|
|
3
|
-
import { a as SeedOptions } from "./packem_shared/plan.d-
|
|
3
|
+
import { a as SeedOptions } from "./packem_shared/plan.d-CDkBhI-1.js";
|
|
4
4
|
declare const seed: (harness: TestHarness, schema: Schema, options?: SeedOptions) => Promise<Record<string, string[]>>;
|
|
5
5
|
export { seed };
|
package/dist/testing.mjs
CHANGED
|
@@ -1,53 +1 @@
|
|
|
1
|
-
import { s
|
|
2
|
-
|
|
3
|
-
const reviveRow = (row, bigintFields, bytesFields) => {
|
|
4
|
-
if (bigintFields.size === 0 && bytesFields.size === 0) {
|
|
5
|
-
return row;
|
|
6
|
-
}
|
|
7
|
-
const revived = { ...row };
|
|
8
|
-
for (const field of bigintFields) {
|
|
9
|
-
const value = revived[field];
|
|
10
|
-
if (typeof value === "number") {
|
|
11
|
-
revived[field] = BigInt(value);
|
|
12
|
-
}
|
|
13
|
-
}
|
|
14
|
-
for (const field of bytesFields) {
|
|
15
|
-
const value = revived[field];
|
|
16
|
-
if (Array.isArray(value)) {
|
|
17
|
-
revived[field] = Uint8Array.from(value).buffer;
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
return revived;
|
|
21
|
-
};
|
|
22
|
-
const seed = async (harness, schema, options = {}) => {
|
|
23
|
-
const plan = seedPlan(schema, options);
|
|
24
|
-
const specs = introspectSchema(schema);
|
|
25
|
-
const bigintFieldsByTable = /* @__PURE__ */ new Map();
|
|
26
|
-
const bytesFieldsByTable = /* @__PURE__ */ new Map();
|
|
27
|
-
for (const spec of specs) {
|
|
28
|
-
const bigintFields = new Set(spec.fields.filter((field) => field.kind === "bigint").map((field) => field.name));
|
|
29
|
-
const bytesFields = new Set(spec.fields.filter((field) => field.kind === "bytes").map((field) => field.name));
|
|
30
|
-
if (bigintFields.size > 0) {
|
|
31
|
-
bigintFieldsByTable.set(spec.name, bigintFields);
|
|
32
|
-
}
|
|
33
|
-
if (bytesFields.size > 0) {
|
|
34
|
-
bytesFieldsByTable.set(spec.name, bytesFields);
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
const ids = {};
|
|
38
|
-
await harness.run(async (context) => {
|
|
39
|
-
const insert = context.db.insert;
|
|
40
|
-
for (const { rows, table } of plan) {
|
|
41
|
-
const tableIds = [];
|
|
42
|
-
const bigintFields = bigintFieldsByTable.get(table) ?? /* @__PURE__ */ new Set();
|
|
43
|
-
const bytesFields = bytesFieldsByTable.get(table) ?? /* @__PURE__ */ new Set();
|
|
44
|
-
for (const row of rows) {
|
|
45
|
-
tableIds.push(await insert(table, reviveRow(row, bigintFields, bytesFields), { allowExplicitId: true }));
|
|
46
|
-
}
|
|
47
|
-
ids[table] = tableIds;
|
|
48
|
-
}
|
|
49
|
-
});
|
|
50
|
-
return ids;
|
|
51
|
-
};
|
|
52
|
-
|
|
53
|
-
export { seed };
|
|
1
|
+
import{V as y,S}from"./packem_shared/plan-DRy9bg5D.mjs";const b=(f,r,a)=>{if(r.size===0&&a.size===0)return f;const n={...f};for(const s of r){const e=n[s];typeof e=="number"&&(n[s]=BigInt(e))}for(const s of a){const e=n[s];Array.isArray(e)&&(n[s]=Uint8Array.from(e).buffer)}return n},z=async(f,r,a={})=>{const n=y(r,a),s=S(r),e=new Map,m=new Map;for(const o of s){const i=new Set(o.fields.filter(t=>t.kind==="bigint").map(t=>t.name)),c=new Set(o.fields.filter(t=>t.kind==="bytes").map(t=>t.name));i.size>0&&e.set(o.name,i),c.size>0&&m.set(o.name,c)}const l={};return await f.run(async o=>{const i=o.db.insert;for(const{rows:c,table:t}of n){const p=[],w=e.get(t)??new Set,u=m.get(t)??new Set;for(const d of c)p.push(await i(t,b(d,w,u),{allowExplicitId:!0}));l[t]=p}}),l};export{z as seed};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/seed",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.71",
|
|
4
4
|
"description": "Schema-driven, deterministic database seeding for Lunora: realistic fake data from defineSchema",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -47,11 +47,12 @@
|
|
|
47
47
|
"access": "public"
|
|
48
48
|
},
|
|
49
49
|
"dependencies": {
|
|
50
|
-
"@faker-js/faker": "^10.5.0"
|
|
50
|
+
"@faker-js/faker": "^10.5.0",
|
|
51
|
+
"@lunora/errors": "1.0.0-alpha.21"
|
|
51
52
|
},
|
|
52
53
|
"peerDependencies": {
|
|
53
|
-
"@lunora/server": "1.0.0-alpha.
|
|
54
|
-
"@lunora/values": "1.0.0-alpha.
|
|
54
|
+
"@lunora/server": ">=1.0.0-alpha.24 <2.0.0-0",
|
|
55
|
+
"@lunora/values": ">=1.0.0-alpha.7 <2.0.0-0"
|
|
55
56
|
},
|
|
56
57
|
"engines": {
|
|
57
58
|
"node": "^22.15.0 || >=24.11.0"
|
|
@@ -1,92 +0,0 @@
|
|
|
1
|
-
import { a as setHashKey, s as seedPlan, c as copycat } from './plan-DirmkctQ.mjs';
|
|
2
|
-
|
|
3
|
-
const isRange = (spec) => Array.isArray(spec) && spec.length === 2 && typeof spec[0] === "number" && typeof spec[1] === "number";
|
|
4
|
-
const resolveSpec = (spec, table, seed, defaultCount) => {
|
|
5
|
-
const pick = (countOrRange) => typeof countOrRange === "number" ? countOrRange : copycat.int([seed, table, "count"], { max: countOrRange[1], min: countOrRange[0] });
|
|
6
|
-
if (spec === void 0) {
|
|
7
|
-
return { count: defaultCount };
|
|
8
|
-
}
|
|
9
|
-
if (typeof spec === "number") {
|
|
10
|
-
return { count: spec };
|
|
11
|
-
}
|
|
12
|
-
if (typeof spec === "function") {
|
|
13
|
-
return { count: spec(pick) };
|
|
14
|
-
}
|
|
15
|
-
if (isRange(spec)) {
|
|
16
|
-
return { count: pick(spec) };
|
|
17
|
-
}
|
|
18
|
-
return { count: spec.length, partials: spec };
|
|
19
|
-
};
|
|
20
|
-
const buildOverrides = (partials, fieldOverrides, offset) => {
|
|
21
|
-
const overrides = {};
|
|
22
|
-
if (partials !== void 0) {
|
|
23
|
-
const fields = new Set(partials.flatMap((partial) => Object.keys(partial)));
|
|
24
|
-
for (const field of fields) {
|
|
25
|
-
overrides[field] = (context) => partials[context.index - offset]?.[field];
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
for (const [field, value] of Object.entries(fieldOverrides ?? {})) {
|
|
29
|
-
overrides[field] = value;
|
|
30
|
-
}
|
|
31
|
-
return overrides;
|
|
32
|
-
};
|
|
33
|
-
const createSeedClient = (schema, options = {}) => {
|
|
34
|
-
const { defaultCount = 10, persist, seed = 0 } = options;
|
|
35
|
-
const store = {};
|
|
36
|
-
const idsByTable = {};
|
|
37
|
-
const createdCount = {};
|
|
38
|
-
const seedTable = async (table, spec, callOptions) => {
|
|
39
|
-
setHashKey(seed);
|
|
40
|
-
const { count, partials } = resolveSpec(spec, table, seed, defaultCount);
|
|
41
|
-
const offset = createdCount[table] ?? 0;
|
|
42
|
-
const plan = seedPlan(schema, {
|
|
43
|
-
counts: { [table]: count },
|
|
44
|
-
existingIds: idsByTable,
|
|
45
|
-
indexOffset: { [table]: offset },
|
|
46
|
-
only: [table],
|
|
47
|
-
overrides: { [table]: buildOverrides(partials, callOptions?.overrides, offset) },
|
|
48
|
-
seed
|
|
49
|
-
});
|
|
50
|
-
let created = [];
|
|
51
|
-
for (const { rows, table: planned } of plan) {
|
|
52
|
-
const ids = rows.map((row) => row._id);
|
|
53
|
-
store[planned] ??= [];
|
|
54
|
-
store[planned].push(...rows);
|
|
55
|
-
idsByTable[planned] ??= [];
|
|
56
|
-
idsByTable[planned].push(...ids);
|
|
57
|
-
createdCount[planned] = (createdCount[planned] ?? 0) + rows.length;
|
|
58
|
-
if (planned === table) {
|
|
59
|
-
created = ids;
|
|
60
|
-
}
|
|
61
|
-
if (persist !== void 0) {
|
|
62
|
-
await persist(planned, rows);
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
return { [table]: created };
|
|
66
|
-
};
|
|
67
|
-
const state = {
|
|
68
|
-
$ids: idsByTable,
|
|
69
|
-
$reset: () => {
|
|
70
|
-
for (const key of Object.keys(store)) {
|
|
71
|
-
delete store[key];
|
|
72
|
-
}
|
|
73
|
-
for (const key of Object.keys(idsByTable)) {
|
|
74
|
-
delete idsByTable[key];
|
|
75
|
-
}
|
|
76
|
-
for (const key of Object.keys(createdCount)) {
|
|
77
|
-
delete createdCount[key];
|
|
78
|
-
}
|
|
79
|
-
},
|
|
80
|
-
$store: store
|
|
81
|
-
};
|
|
82
|
-
return /* @__PURE__ */ new Proxy(state, {
|
|
83
|
-
get(target, property, receiver) {
|
|
84
|
-
if (typeof property === "string" && !property.startsWith("$") && Object.hasOwn(schema.tables, property)) {
|
|
85
|
-
return (spec, callOptions) => seedTable(property, spec, callOptions);
|
|
86
|
-
}
|
|
87
|
-
return Reflect.get(target, property, receiver);
|
|
88
|
-
}
|
|
89
|
-
});
|
|
90
|
-
};
|
|
91
|
-
|
|
92
|
-
export { createSeedClient };
|
|
@@ -1,497 +0,0 @@
|
|
|
1
|
-
import { faker } from '@faker-js/faker';
|
|
2
|
-
import { optionalInner } from '@lunora/values';
|
|
3
|
-
|
|
4
|
-
let hashSalt = 0;
|
|
5
|
-
const compareStrings = (a, b) => {
|
|
6
|
-
if (a < b) {
|
|
7
|
-
return -1;
|
|
8
|
-
}
|
|
9
|
-
if (a > b) {
|
|
10
|
-
return 1;
|
|
11
|
-
}
|
|
12
|
-
return 0;
|
|
13
|
-
};
|
|
14
|
-
const stableStringify = (input) => {
|
|
15
|
-
if (input === void 0) {
|
|
16
|
-
return "undefined";
|
|
17
|
-
}
|
|
18
|
-
if (typeof input === "bigint") {
|
|
19
|
-
return `${input.toString()}n`;
|
|
20
|
-
}
|
|
21
|
-
if (input === null || typeof input !== "object") {
|
|
22
|
-
return JSON.stringify(input) ?? "null";
|
|
23
|
-
}
|
|
24
|
-
if (Array.isArray(input)) {
|
|
25
|
-
return `[${input.map((item) => stableStringify(item)).join(",")}]`;
|
|
26
|
-
}
|
|
27
|
-
const entries = Object.keys(input).toSorted(compareStrings).map((key) => `${JSON.stringify(key)}:${stableStringify(input[key])}`);
|
|
28
|
-
return `{${entries.join(",")}}`;
|
|
29
|
-
};
|
|
30
|
-
const cyrb53 = (text, seed) => {
|
|
31
|
-
let h1 = 3735928559 ^ seed;
|
|
32
|
-
let h2 = 1103547991 ^ seed;
|
|
33
|
-
for (let index = 0; index < text.length; index += 1) {
|
|
34
|
-
const ch = text.codePointAt(index) ?? 0;
|
|
35
|
-
h1 = Math.imul(h1 ^ ch, 2654435761);
|
|
36
|
-
h2 = Math.imul(h2 ^ ch, 1597334677);
|
|
37
|
-
}
|
|
38
|
-
h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507);
|
|
39
|
-
h1 ^= Math.imul(h2 ^ h2 >>> 13, 3266489909);
|
|
40
|
-
h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507);
|
|
41
|
-
h2 ^= Math.imul(h1 ^ h1 >>> 13, 3266489909);
|
|
42
|
-
return 4294967296 * (2097151 & h2) + (h1 >>> 0);
|
|
43
|
-
};
|
|
44
|
-
const STRING_DOMAIN_TAG = "\0";
|
|
45
|
-
const hashInput = (input) => {
|
|
46
|
-
const text = typeof input === "string" ? STRING_DOMAIN_TAG + input : stableStringify(input);
|
|
47
|
-
return cyrb53(text, hashSalt) % 4294967296;
|
|
48
|
-
};
|
|
49
|
-
const setHashKey = (key) => {
|
|
50
|
-
if (typeof key === "number") {
|
|
51
|
-
hashSalt = key >>> 0;
|
|
52
|
-
return;
|
|
53
|
-
}
|
|
54
|
-
if (typeof key === "string") {
|
|
55
|
-
hashSalt = cyrb53(key, 0) % 4294967296;
|
|
56
|
-
return;
|
|
57
|
-
}
|
|
58
|
-
let folded = 0;
|
|
59
|
-
for (const word of key) {
|
|
60
|
-
folded = Math.imul(folded ^ word, 2654435761) >>> 0;
|
|
61
|
-
}
|
|
62
|
-
hashSalt = folded;
|
|
63
|
-
};
|
|
64
|
-
|
|
65
|
-
const seeded = (input, produce) => {
|
|
66
|
-
faker.seed(hashInput(input));
|
|
67
|
-
return produce();
|
|
68
|
-
};
|
|
69
|
-
const resolveCount = (input, range) => {
|
|
70
|
-
if (typeof range === "number") {
|
|
71
|
-
return range;
|
|
72
|
-
}
|
|
73
|
-
const [min, max] = range;
|
|
74
|
-
return seeded(["__count__", input], () => faker.number.int({ max, min }));
|
|
75
|
-
};
|
|
76
|
-
const capitalizeWord = (word) => word.length === 0 ? word : word.charAt(0).toUpperCase() + word.slice(1);
|
|
77
|
-
const LOWER_ALPHA = /[a-z]/;
|
|
78
|
-
const UPPER_ALPHA = /[A-Z]/;
|
|
79
|
-
const DIGIT = /\d/;
|
|
80
|
-
const copycat = {
|
|
81
|
-
bool(input) {
|
|
82
|
-
return seeded(input, () => faker.datatype.boolean());
|
|
83
|
-
},
|
|
84
|
-
char(input) {
|
|
85
|
-
return seeded(input, () => faker.string.alpha(1));
|
|
86
|
-
},
|
|
87
|
-
city(input) {
|
|
88
|
-
return seeded(input, () => faker.location.city());
|
|
89
|
-
},
|
|
90
|
-
country(input) {
|
|
91
|
-
return seeded(input, () => faker.location.country());
|
|
92
|
-
},
|
|
93
|
-
countryCode(input) {
|
|
94
|
-
return seeded(input, () => faker.location.countryCode());
|
|
95
|
-
},
|
|
96
|
-
/** ISO-8601 date string between `min`/`max` (default years 1980–2020). */
|
|
97
|
-
dateString(input, options) {
|
|
98
|
-
const min = options?.min ?? /* @__PURE__ */ new Date("1980-01-01T00:00:00.000Z");
|
|
99
|
-
const max = options?.max ?? /* @__PURE__ */ new Date("2020-01-01T00:00:00.000Z");
|
|
100
|
-
return seeded(input, () => faker.date.between({ from: min, to: max }).toISOString());
|
|
101
|
-
},
|
|
102
|
-
digit(input) {
|
|
103
|
-
return seeded(input, () => String(faker.number.int({ max: 9, min: 0 })));
|
|
104
|
-
},
|
|
105
|
-
email(input) {
|
|
106
|
-
return seeded(input, () => faker.internet.email().toLowerCase());
|
|
107
|
-
},
|
|
108
|
-
firstName(input) {
|
|
109
|
-
return seeded(input, () => faker.person.firstName());
|
|
110
|
-
},
|
|
111
|
-
float(input, options) {
|
|
112
|
-
const { fractionDigits = 2, max = 1e3, min = 0 } = options ?? {};
|
|
113
|
-
return seeded(input, () => faker.number.float({ fractionDigits, max, min }));
|
|
114
|
-
},
|
|
115
|
-
fullName(input) {
|
|
116
|
-
return seeded(input, () => faker.person.fullName());
|
|
117
|
-
},
|
|
118
|
-
hex(input) {
|
|
119
|
-
return seeded(input, () => faker.string.hexadecimal({ casing: "lower", length: 1, prefix: "" }));
|
|
120
|
-
},
|
|
121
|
-
int(input, options) {
|
|
122
|
-
const { max = 1e3, min = 0 } = options ?? {};
|
|
123
|
-
return seeded(input, () => faker.number.int({ max, min }));
|
|
124
|
-
},
|
|
125
|
-
ipv4(input) {
|
|
126
|
-
return seeded(input, () => faker.internet.ipv4());
|
|
127
|
-
},
|
|
128
|
-
lastName(input) {
|
|
129
|
-
return seeded(input, () => faker.person.lastName());
|
|
130
|
-
},
|
|
131
|
-
mac(input) {
|
|
132
|
-
return seeded(input, () => faker.internet.mac());
|
|
133
|
-
},
|
|
134
|
-
/** Pick the array element corresponding to `input`. Returns `undefined` for an empty array. */
|
|
135
|
-
oneOf(input, values) {
|
|
136
|
-
if (values.length === 0) {
|
|
137
|
-
return void 0;
|
|
138
|
-
}
|
|
139
|
-
return seeded(input, () => faker.helpers.arrayElement(values));
|
|
140
|
-
},
|
|
141
|
-
paragraph(input) {
|
|
142
|
-
return seeded(input, () => faker.lorem.paragraph());
|
|
143
|
-
},
|
|
144
|
-
password(input) {
|
|
145
|
-
return seeded(input, () => faker.internet.password());
|
|
146
|
-
},
|
|
147
|
-
phoneNumber(input) {
|
|
148
|
-
return seeded(input, () => faker.phone.number());
|
|
149
|
-
},
|
|
150
|
-
/**
|
|
151
|
-
* Scramble a string in place: letters become seeded letters (case
|
|
152
|
-
* preserved), digits become seeded digits, every other character is kept.
|
|
153
|
-
* Length is preserved. Characters listed in `preserve` pass through untouched.
|
|
154
|
-
*/
|
|
155
|
-
scramble(input, options) {
|
|
156
|
-
const preserve = new Set(options?.preserve);
|
|
157
|
-
return Array.from({ length: input.length }, (_unused, index) => {
|
|
158
|
-
const char = input.charAt(index);
|
|
159
|
-
if (preserve.has(char)) {
|
|
160
|
-
return char;
|
|
161
|
-
}
|
|
162
|
-
if (LOWER_ALPHA.test(char)) {
|
|
163
|
-
return seeded([input, index, "l"], () => faker.string.alpha({ casing: "lower", length: 1 }));
|
|
164
|
-
}
|
|
165
|
-
if (UPPER_ALPHA.test(char)) {
|
|
166
|
-
return seeded([input, index, "u"], () => faker.string.alpha({ casing: "upper", length: 1 }));
|
|
167
|
-
}
|
|
168
|
-
if (DIGIT.test(char)) {
|
|
169
|
-
return seeded([input, index, "d"], () => String(faker.number.int({ max: 9, min: 0 })));
|
|
170
|
-
}
|
|
171
|
-
return char;
|
|
172
|
-
}).join("");
|
|
173
|
-
},
|
|
174
|
-
sentence(input, options) {
|
|
175
|
-
return seeded(input, () => faker.lorem.sentence(options ? { max: options.max ?? 8, min: options.min ?? 3 } : void 0));
|
|
176
|
-
},
|
|
177
|
-
slug(input) {
|
|
178
|
-
return seeded(input, () => faker.lorem.slug());
|
|
179
|
-
},
|
|
180
|
-
/** Pick a deterministic subset (size within `range`) of `values`, no repeats. */
|
|
181
|
-
someOf(input, range, values) {
|
|
182
|
-
const count = Math.min(resolveCount(["__some__", input], range), values.length);
|
|
183
|
-
return seeded(input, () => faker.helpers.arrayElements(values, count));
|
|
184
|
-
},
|
|
185
|
-
streetAddress(input) {
|
|
186
|
-
return seeded(input, () => faker.location.streetAddress());
|
|
187
|
-
},
|
|
188
|
-
streetName(input) {
|
|
189
|
-
return seeded(input, () => faker.location.street());
|
|
190
|
-
},
|
|
191
|
-
timezone(input) {
|
|
192
|
-
return seeded(input, () => faker.location.timeZone());
|
|
193
|
-
},
|
|
194
|
-
/**
|
|
195
|
-
* Call `produce` once per element for a deterministic count within `range`,
|
|
196
|
-
* passing each a distinct sub-input so the elements differ but stay stable.
|
|
197
|
-
*/
|
|
198
|
-
times(input, range, produce) {
|
|
199
|
-
const count = resolveCount(input, range);
|
|
200
|
-
const out = [];
|
|
201
|
-
for (let index = 0; index < count; index += 1) {
|
|
202
|
-
out.push(produce([input, index]));
|
|
203
|
-
}
|
|
204
|
-
return out;
|
|
205
|
-
},
|
|
206
|
-
url(input) {
|
|
207
|
-
return seeded(input, () => faker.internet.url());
|
|
208
|
-
},
|
|
209
|
-
username(input) {
|
|
210
|
-
return seeded(input, () => faker.internet.username());
|
|
211
|
-
},
|
|
212
|
-
uuid(input) {
|
|
213
|
-
return seeded(input, () => faker.string.uuid());
|
|
214
|
-
},
|
|
215
|
-
word(input, options) {
|
|
216
|
-
const word = seeded(input, () => faker.lorem.word());
|
|
217
|
-
return options?.capitalize === true ? capitalizeWord(word) : word;
|
|
218
|
-
},
|
|
219
|
-
words(input, options) {
|
|
220
|
-
return seeded(input, () => faker.lorem.words(options ? { max: options.max ?? 5, min: options.min ?? 2 } : void 0));
|
|
221
|
-
}
|
|
222
|
-
};
|
|
223
|
-
|
|
224
|
-
const metaOf = (validator) => validator._meta ?? {};
|
|
225
|
-
const unwrapOptional = (validator) => optionalInner(validator) ?? validator;
|
|
226
|
-
const hasServerDefault = (validator) => {
|
|
227
|
-
const { column } = metaOf(validator);
|
|
228
|
-
if (column?.defaultValue !== void 0 || column?.defaultFn !== void 0) {
|
|
229
|
-
return true;
|
|
230
|
-
}
|
|
231
|
-
const inner = optionalInner(validator);
|
|
232
|
-
return inner === void 0 ? false : hasServerDefault(inner);
|
|
233
|
-
};
|
|
234
|
-
const describeField = (name, validator) => {
|
|
235
|
-
const inner = unwrapOptional(validator);
|
|
236
|
-
const meta = metaOf(inner);
|
|
237
|
-
return {
|
|
238
|
-
fkTable: inner.kind === "id" ? meta.tableName : void 0,
|
|
239
|
-
hasServerDefault: hasServerDefault(validator),
|
|
240
|
-
kind: inner.kind,
|
|
241
|
-
name,
|
|
242
|
-
// `notNull` is tri-state: `true` (default / `.notNull()`), `false`
|
|
243
|
-
// (`.nullable()`), or `undefined` (no column metadata). Only an explicit
|
|
244
|
-
// `false` means the user opted the column into SQL `NULL` — which is what
|
|
245
|
-
// `fkFallback` keys off to emit `null` for an unresolved nullable FK. This
|
|
246
|
-
// mirrors codegen's own `isNullable` (`column?.notNull === false`).
|
|
247
|
-
nullable: meta.column?.notNull === false,
|
|
248
|
-
optional: validator.kind === "optional",
|
|
249
|
-
validator: inner
|
|
250
|
-
};
|
|
251
|
-
};
|
|
252
|
-
const introspectSchema = (schema) => {
|
|
253
|
-
const { tables } = schema;
|
|
254
|
-
return Object.entries(tables).map(([name, table]) => {
|
|
255
|
-
return {
|
|
256
|
-
fields: Object.entries(table.shape).map(([fieldName, validator]) => describeField(fieldName, validator)),
|
|
257
|
-
name
|
|
258
|
-
};
|
|
259
|
-
});
|
|
260
|
-
};
|
|
261
|
-
const orderTables = (specs, selected) => {
|
|
262
|
-
const byName = new Map(specs.map((spec) => [spec.name, spec]));
|
|
263
|
-
const parentsOf = (name) => {
|
|
264
|
-
const spec = byName.get(name);
|
|
265
|
-
if (spec === void 0) {
|
|
266
|
-
return /* @__PURE__ */ new Set();
|
|
267
|
-
}
|
|
268
|
-
const parents = /* @__PURE__ */ new Set();
|
|
269
|
-
for (const field of spec.fields) {
|
|
270
|
-
if (field.fkTable !== void 0 && field.fkTable !== name && selected.has(field.fkTable)) {
|
|
271
|
-
parents.add(field.fkTable);
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
return parents;
|
|
275
|
-
};
|
|
276
|
-
const ordered = [];
|
|
277
|
-
const placed = /* @__PURE__ */ new Set();
|
|
278
|
-
const pending = [...selected].filter((name) => byName.has(name));
|
|
279
|
-
while (pending.length > 0) {
|
|
280
|
-
const readyIndex = pending.findIndex((name2) => [...parentsOf(name2)].every((parent) => placed.has(parent)));
|
|
281
|
-
const index = readyIndex === -1 ? 0 : readyIndex;
|
|
282
|
-
const [name] = pending.splice(index, 1);
|
|
283
|
-
if (name === void 0) {
|
|
284
|
-
break;
|
|
285
|
-
}
|
|
286
|
-
ordered.push(name);
|
|
287
|
-
placed.add(name);
|
|
288
|
-
}
|
|
289
|
-
return ordered;
|
|
290
|
-
};
|
|
291
|
-
const fkParentClosure = (specs, roots) => {
|
|
292
|
-
const byName = new Map(specs.map((spec) => [spec.name, spec]));
|
|
293
|
-
const result = new Set(roots);
|
|
294
|
-
const stack = [...result];
|
|
295
|
-
while (stack.length > 0) {
|
|
296
|
-
const name = stack.pop();
|
|
297
|
-
if (name === void 0) {
|
|
298
|
-
break;
|
|
299
|
-
}
|
|
300
|
-
const spec = byName.get(name);
|
|
301
|
-
if (spec === void 0) {
|
|
302
|
-
continue;
|
|
303
|
-
}
|
|
304
|
-
for (const field of spec.fields) {
|
|
305
|
-
if (field.fkTable !== void 0 && field.fkTable !== name && byName.has(field.fkTable) && !result.has(field.fkTable)) {
|
|
306
|
-
result.add(field.fkTable);
|
|
307
|
-
stack.push(field.fkTable);
|
|
308
|
-
}
|
|
309
|
-
}
|
|
310
|
-
}
|
|
311
|
-
return result;
|
|
312
|
-
};
|
|
313
|
-
|
|
314
|
-
const constraintsOf = (validator) => metaOf(validator).constraints ?? {};
|
|
315
|
-
const STRING_HEURISTICS = [
|
|
316
|
-
{ generate: (input) => copycat.email(input), keywords: ["email"] },
|
|
317
|
-
{ generate: (input) => copycat.firstName(input), keywords: ["firstname"] },
|
|
318
|
-
{ generate: (input) => copycat.lastName(input), keywords: ["lastname", "surname"] },
|
|
319
|
-
{ generate: (input) => copycat.username(input), keywords: ["username"] },
|
|
320
|
-
{ generate: (input) => copycat.fullName(input), keywords: ["name"] },
|
|
321
|
-
{ generate: (input) => copycat.sentence(input, { max: 5, min: 2 }), keywords: ["title"] },
|
|
322
|
-
{ generate: (input) => copycat.url(input), keywords: ["url", "link", "image", "avatar"] },
|
|
323
|
-
{ generate: (input) => copycat.phoneNumber(input), keywords: ["phone"] },
|
|
324
|
-
{ generate: (input) => copycat.paragraph(input), keywords: ["description", "bio", "body", "content", "text"] },
|
|
325
|
-
{ generate: (input) => copycat.slug(input), keywords: ["slug", "key", "code"] },
|
|
326
|
-
{ generate: (input) => copycat.city(input), keywords: ["city"] },
|
|
327
|
-
{ generate: (input) => copycat.country(input), keywords: ["country"] },
|
|
328
|
-
{ generate: (input) => copycat.streetAddress(input), keywords: ["address", "street"] },
|
|
329
|
-
{ generate: (input) => copycat.password(input), keywords: ["password", "secret", "token"] }
|
|
330
|
-
];
|
|
331
|
-
const generateString = (fieldName, input, constraints) => {
|
|
332
|
-
const lower = fieldName.toLowerCase();
|
|
333
|
-
const rule = STRING_HEURISTICS.find((entry) => entry.keywords.some((keyword) => lower.includes(keyword)));
|
|
334
|
-
const value = rule === void 0 ? copycat.word(input) : rule.generate(input);
|
|
335
|
-
const { maxLength, minLength } = constraints;
|
|
336
|
-
if (maxLength !== void 0 && minLength !== void 0 && minLength > maxLength) {
|
|
337
|
-
throw new Error(
|
|
338
|
-
`Seed constraint error for field "${fieldName}": minLength (${String(minLength)}) > maxLength (${String(maxLength)}). Adjust the schema constraints.`
|
|
339
|
-
);
|
|
340
|
-
}
|
|
341
|
-
const truncated = maxLength !== void 0 && value.length > maxLength ? value.slice(0, maxLength) : value;
|
|
342
|
-
if (minLength !== void 0 && truncated.length < minLength) {
|
|
343
|
-
return truncated.padEnd(minLength, truncated.length > 0 ? truncated : "x");
|
|
344
|
-
}
|
|
345
|
-
return truncated;
|
|
346
|
-
};
|
|
347
|
-
const generateValue = (validator, fieldName, input) => {
|
|
348
|
-
const inner = unwrapOptional(validator);
|
|
349
|
-
const constraints = constraintsOf(inner);
|
|
350
|
-
if (constraints.enum !== void 0 && constraints.enum.length > 0) {
|
|
351
|
-
return copycat.oneOf(input, constraints.enum);
|
|
352
|
-
}
|
|
353
|
-
switch (inner.kind) {
|
|
354
|
-
case "any": {
|
|
355
|
-
return copycat.word(input);
|
|
356
|
-
}
|
|
357
|
-
case "array": {
|
|
358
|
-
const element = metaOf(inner).inner;
|
|
359
|
-
if (element === void 0) {
|
|
360
|
-
return [];
|
|
361
|
-
}
|
|
362
|
-
return copycat.times(input, [1, 3], (itemInput) => generateValue(element, fieldName, itemInput));
|
|
363
|
-
}
|
|
364
|
-
case "bigint": {
|
|
365
|
-
return copycat.int(input, { max: 1e6, min: 0 });
|
|
366
|
-
}
|
|
367
|
-
case "boolean": {
|
|
368
|
-
return copycat.bool(input);
|
|
369
|
-
}
|
|
370
|
-
case "bytes": {
|
|
371
|
-
return Array.from({ length: 8 }, (_, index) => copycat.int([input, index], { max: 255, min: 0 }));
|
|
372
|
-
}
|
|
373
|
-
case "date":
|
|
374
|
-
case "timestamp": {
|
|
375
|
-
return new Date(copycat.dateString(input)).getTime();
|
|
376
|
-
}
|
|
377
|
-
case "id": {
|
|
378
|
-
return copycat.uuid(input);
|
|
379
|
-
}
|
|
380
|
-
case "literal": {
|
|
381
|
-
return metaOf(inner).value;
|
|
382
|
-
}
|
|
383
|
-
case "null": {
|
|
384
|
-
return null;
|
|
385
|
-
}
|
|
386
|
-
case "number": {
|
|
387
|
-
return copycat.int(input, { max: constraints.maximum ?? 1e3, min: constraints.minimum ?? 0 });
|
|
388
|
-
}
|
|
389
|
-
case "object": {
|
|
390
|
-
const shape = metaOf(inner).shape ?? {};
|
|
391
|
-
return Object.fromEntries(Object.entries(shape).map(([key, child]) => [key, generateValue(child, key, [input, key])]));
|
|
392
|
-
}
|
|
393
|
-
case "record": {
|
|
394
|
-
const { valueValidator } = metaOf(inner);
|
|
395
|
-
const entries = copycat.times(input, [1, 3], (itemInput) => {
|
|
396
|
-
const key = copycat.word(["k", itemInput]);
|
|
397
|
-
const value = valueValidator === void 0 ? copycat.word(["v", itemInput]) : generateValue(valueValidator, fieldName, ["v", itemInput]);
|
|
398
|
-
return [key, value];
|
|
399
|
-
});
|
|
400
|
-
return Object.fromEntries(entries);
|
|
401
|
-
}
|
|
402
|
-
case "storage": {
|
|
403
|
-
return `seed/${copycat.uuid(input)}`;
|
|
404
|
-
}
|
|
405
|
-
case "string": {
|
|
406
|
-
return generateString(fieldName, input, constraints);
|
|
407
|
-
}
|
|
408
|
-
case "union": {
|
|
409
|
-
const members = metaOf(inner).members ?? [];
|
|
410
|
-
const chosen = copycat.oneOf(input, members);
|
|
411
|
-
return chosen === void 0 ? copycat.word(input) : generateValue(chosen, fieldName, [input, "u"]);
|
|
412
|
-
}
|
|
413
|
-
default: {
|
|
414
|
-
return copycat.word(input);
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
};
|
|
418
|
-
|
|
419
|
-
const resolveOverride = (override, context) => typeof override === "function" ? override(context) : override;
|
|
420
|
-
const fkFallback = (field, input) => {
|
|
421
|
-
if (field.optional) {
|
|
422
|
-
return void 0;
|
|
423
|
-
}
|
|
424
|
-
return field.nullable ? null : copycat.uuid(input);
|
|
425
|
-
};
|
|
426
|
-
const fkPool = (field, table, localIndex, idsByTable, existingIds) => {
|
|
427
|
-
const fkTable = field.fkTable;
|
|
428
|
-
const seeded = fkTable === table ? (idsByTable.get(table) ?? []).slice(0, localIndex) : idsByTable.get(fkTable) ?? [];
|
|
429
|
-
const existing = existingIds[fkTable] ?? [];
|
|
430
|
-
return existing.length === 0 ? seeded : [...seeded, ...existing];
|
|
431
|
-
};
|
|
432
|
-
const cellInput = (seed, table, index, column) => [seed, table, index, column];
|
|
433
|
-
const generateField = (field, table, input, localIndex, idsByTable, existingIds) => {
|
|
434
|
-
if (field.fkTable !== void 0) {
|
|
435
|
-
const pool = fkPool(field, table, localIndex, idsByTable, existingIds);
|
|
436
|
-
if (pool.length === 0) {
|
|
437
|
-
return fkFallback(field, input);
|
|
438
|
-
}
|
|
439
|
-
return copycat.oneOf(input, pool);
|
|
440
|
-
}
|
|
441
|
-
if (field.hasServerDefault) {
|
|
442
|
-
return void 0;
|
|
443
|
-
}
|
|
444
|
-
return generateValue(field.validator, field.name, input);
|
|
445
|
-
};
|
|
446
|
-
const seedPlan = (schema, options = {}) => {
|
|
447
|
-
const { counts = {}, defaultCount = 10, existingIds = {}, indexOffset = {}, only, overrides = {}, seed = 0 } = options;
|
|
448
|
-
setHashKey(seed);
|
|
449
|
-
const specs = introspectSchema(schema);
|
|
450
|
-
const requested = new Set(only ?? specs.map((spec) => spec.name));
|
|
451
|
-
const selected = new Set([...fkParentClosure(specs, requested)].filter((table) => requested.has(table) || (existingIds[table] ?? []).length === 0));
|
|
452
|
-
const order = orderTables(specs, selected);
|
|
453
|
-
const specByName = new Map(specs.map((spec) => [spec.name, spec]));
|
|
454
|
-
const idsByTable = /* @__PURE__ */ new Map();
|
|
455
|
-
const storeRows = {};
|
|
456
|
-
const plan = [];
|
|
457
|
-
for (const table of order) {
|
|
458
|
-
const spec = specByName.get(table);
|
|
459
|
-
if (spec === void 0) {
|
|
460
|
-
continue;
|
|
461
|
-
}
|
|
462
|
-
const tableOverrides = overrides[table] ?? {};
|
|
463
|
-
const count = counts[table] ?? defaultCount;
|
|
464
|
-
const offset = indexOffset[table] ?? 0;
|
|
465
|
-
const ids = [];
|
|
466
|
-
idsByTable.set(table, ids);
|
|
467
|
-
const rows = [];
|
|
468
|
-
storeRows[table] = rows;
|
|
469
|
-
for (let localIndex = 0; localIndex < count; localIndex += 1) {
|
|
470
|
-
const index = offset + localIndex;
|
|
471
|
-
const row = {};
|
|
472
|
-
const apply = (field, fallback) => {
|
|
473
|
-
if (Object.hasOwn(tableOverrides, field)) {
|
|
474
|
-
const overridden = resolveOverride(tableOverrides[field], { field, index, row, store: storeRows, table });
|
|
475
|
-
if (overridden !== void 0) {
|
|
476
|
-
row[field] = overridden;
|
|
477
|
-
return;
|
|
478
|
-
}
|
|
479
|
-
}
|
|
480
|
-
const value = fallback();
|
|
481
|
-
if (value !== void 0) {
|
|
482
|
-
row[field] = value;
|
|
483
|
-
}
|
|
484
|
-
};
|
|
485
|
-
apply("_id", () => copycat.uuid(cellInput(seed, table, index, "_id")));
|
|
486
|
-
ids.push(row._id);
|
|
487
|
-
for (const field of spec.fields) {
|
|
488
|
-
apply(field.name, () => generateField(field, table, cellInput(seed, table, index, field.name), localIndex, idsByTable, existingIds));
|
|
489
|
-
}
|
|
490
|
-
rows.push(row);
|
|
491
|
-
}
|
|
492
|
-
plan.push({ rows, table });
|
|
493
|
-
}
|
|
494
|
-
return plan;
|
|
495
|
-
};
|
|
496
|
-
|
|
497
|
-
export { setHashKey as a, copycat as c, introspectSchema as i, seedPlan as s };
|
|
@@ -1,78 +0,0 @@
|
|
|
1
|
-
import { Schema } from '@lunora/server';
|
|
2
|
-
/**
|
|
3
|
-
* The pure, I/O-free core of seeding. {@link seedPlan} introspects a schema,
|
|
4
|
-
* generates rows table-by-table in foreign-key order, and resolves every
|
|
5
|
-
* `v.id("parent")` column to a real id of an already-generated parent row. The
|
|
6
|
-
* result feeds every adapter (test harness, CLI, studio) — none of them
|
|
7
|
-
* re-implement generation.
|
|
8
|
-
*
|
|
9
|
-
* Determinism: a `seed` value selects the global copycat mapping, and each value
|
|
10
|
-
* is hashed from `[seed, table, index, field]`, so the same `(schema, options)`
|
|
11
|
-
* always yields byte-identical rows.
|
|
12
|
-
*/
|
|
13
|
-
/** A row context handed to an override function. */
|
|
14
|
-
interface OverrideContext {
|
|
15
|
-
field: string;
|
|
16
|
-
/** The row's absolute index (the `indexOffset` base plus its position in this batch). */
|
|
17
|
-
index: number;
|
|
18
|
-
/** The row built so far (system `_id` first, then earlier fields). */
|
|
19
|
-
row: Record<string, unknown>;
|
|
20
|
-
/**
|
|
21
|
-
* A live, read-only view of every table's rows generated so far this run,
|
|
22
|
-
* keyed by table name. Lets an override correlate across tables (e.g. copy a
|
|
23
|
-
* field from the parent row a foreign key points at). Rows for the current
|
|
24
|
-
* table accumulate as they are built, so only earlier rows are visible.
|
|
25
|
-
*/
|
|
26
|
-
store: Readonly<Record<string, ReadonlyArray<Record<string, unknown>>>>;
|
|
27
|
-
table: string;
|
|
28
|
-
}
|
|
29
|
-
/**
|
|
30
|
-
* Per-table, per-field overrides. Each override is a static value or a function
|
|
31
|
-
* of the row context; field `_id` overrides the generated primary key.
|
|
32
|
-
*/
|
|
33
|
-
type SeedOverrides = Record<string, Record<string, unknown>>;
|
|
34
|
-
/** Per-table row counts. */
|
|
35
|
-
type SeedCounts = Record<string, number>;
|
|
36
|
-
interface SeedOptions {
|
|
37
|
-
/** Rows per table; falls back to {@link SeedOptions.defaultCount} when a table is absent. */
|
|
38
|
-
counts?: SeedCounts;
|
|
39
|
-
/** Count used for any selected table not present in `counts` (default `10`). */
|
|
40
|
-
defaultCount?: number;
|
|
41
|
-
/**
|
|
42
|
-
* Ids of rows that already exist in the target store, keyed by table. Foreign
|
|
43
|
-
* keys may resolve to these in addition to freshly-seeded parents, and a
|
|
44
|
-
* parent table fully covered here is not re-seeded when it is only pulled in
|
|
45
|
-
* as an FK dependency (it is when named explicitly in `only`).
|
|
46
|
-
*/
|
|
47
|
-
existingIds?: Readonly<Record<string, ReadonlyArray<string>>>;
|
|
48
|
-
/**
|
|
49
|
-
* Per-table absolute index base for generation. Defaults to `0`. A client
|
|
50
|
-
* seeding the same table across several calls passes the running total so
|
|
51
|
-
* each batch hashes from fresh indices and never collides ids with an
|
|
52
|
-
* earlier batch.
|
|
53
|
-
*/
|
|
54
|
-
indexOffset?: Readonly<Record<string, number>>;
|
|
55
|
-
/**
|
|
56
|
-
* Restrict seeding to these tables. Transitive `v.id(...)` parents are added
|
|
57
|
-
* automatically (unless already covered by `existingIds`) so child foreign
|
|
58
|
-
* keys resolve to real rows. The result is still ordered by FK dependency.
|
|
59
|
-
* Default: all tables.
|
|
60
|
-
*/
|
|
61
|
-
only?: ReadonlyArray<string>;
|
|
62
|
-
/** Static values or functions overriding generated columns. */
|
|
63
|
-
overrides?: SeedOverrides;
|
|
64
|
-
/** Deterministic mapping selector — same seed ⇒ same rows. Default `0`. */
|
|
65
|
-
seed?: number;
|
|
66
|
-
}
|
|
67
|
-
/** One table's generated rows, in insert order. Each row carries an explicit `_id`. */
|
|
68
|
-
interface TablePlan {
|
|
69
|
-
rows: ReadonlyArray<Record<string, unknown>>;
|
|
70
|
-
table: string;
|
|
71
|
-
}
|
|
72
|
-
/**
|
|
73
|
-
* Build a deterministic, FK-consistent set of rows for `schema`.
|
|
74
|
-
* @returns one {@link TablePlan} per seeded table, ordered so a table's FK
|
|
75
|
-
* parents come before it.
|
|
76
|
-
*/
|
|
77
|
-
declare const seedPlan: (schema: Schema, options?: SeedOptions) => ReadonlyArray<TablePlan>;
|
|
78
|
-
export { OverrideContext as O, SeedCounts as S, TablePlan as T, SeedOptions as a, SeedOverrides as b, seedPlan as s };
|
|
@@ -1,78 +0,0 @@
|
|
|
1
|
-
import { Schema } from '@lunora/server';
|
|
2
|
-
/**
|
|
3
|
-
* The pure, I/O-free core of seeding. {@link seedPlan} introspects a schema,
|
|
4
|
-
* generates rows table-by-table in foreign-key order, and resolves every
|
|
5
|
-
* `v.id("parent")` column to a real id of an already-generated parent row. The
|
|
6
|
-
* result feeds every adapter (test harness, CLI, studio) — none of them
|
|
7
|
-
* re-implement generation.
|
|
8
|
-
*
|
|
9
|
-
* Determinism: a `seed` value selects the global copycat mapping, and each value
|
|
10
|
-
* is hashed from `[seed, table, index, field]`, so the same `(schema, options)`
|
|
11
|
-
* always yields byte-identical rows.
|
|
12
|
-
*/
|
|
13
|
-
/** A row context handed to an override function. */
|
|
14
|
-
interface OverrideContext {
|
|
15
|
-
field: string;
|
|
16
|
-
/** The row's absolute index (the `indexOffset` base plus its position in this batch). */
|
|
17
|
-
index: number;
|
|
18
|
-
/** The row built so far (system `_id` first, then earlier fields). */
|
|
19
|
-
row: Record<string, unknown>;
|
|
20
|
-
/**
|
|
21
|
-
* A live, read-only view of every table's rows generated so far this run,
|
|
22
|
-
* keyed by table name. Lets an override correlate across tables (e.g. copy a
|
|
23
|
-
* field from the parent row a foreign key points at). Rows for the current
|
|
24
|
-
* table accumulate as they are built, so only earlier rows are visible.
|
|
25
|
-
*/
|
|
26
|
-
store: Readonly<Record<string, ReadonlyArray<Record<string, unknown>>>>;
|
|
27
|
-
table: string;
|
|
28
|
-
}
|
|
29
|
-
/**
|
|
30
|
-
* Per-table, per-field overrides. Each override is a static value or a function
|
|
31
|
-
* of the row context; field `_id` overrides the generated primary key.
|
|
32
|
-
*/
|
|
33
|
-
type SeedOverrides = Record<string, Record<string, unknown>>;
|
|
34
|
-
/** Per-table row counts. */
|
|
35
|
-
type SeedCounts = Record<string, number>;
|
|
36
|
-
interface SeedOptions {
|
|
37
|
-
/** Rows per table; falls back to {@link SeedOptions.defaultCount} when a table is absent. */
|
|
38
|
-
counts?: SeedCounts;
|
|
39
|
-
/** Count used for any selected table not present in `counts` (default `10`). */
|
|
40
|
-
defaultCount?: number;
|
|
41
|
-
/**
|
|
42
|
-
* Ids of rows that already exist in the target store, keyed by table. Foreign
|
|
43
|
-
* keys may resolve to these in addition to freshly-seeded parents, and a
|
|
44
|
-
* parent table fully covered here is not re-seeded when it is only pulled in
|
|
45
|
-
* as an FK dependency (it is when named explicitly in `only`).
|
|
46
|
-
*/
|
|
47
|
-
existingIds?: Readonly<Record<string, ReadonlyArray<string>>>;
|
|
48
|
-
/**
|
|
49
|
-
* Per-table absolute index base for generation. Defaults to `0`. A client
|
|
50
|
-
* seeding the same table across several calls passes the running total so
|
|
51
|
-
* each batch hashes from fresh indices and never collides ids with an
|
|
52
|
-
* earlier batch.
|
|
53
|
-
*/
|
|
54
|
-
indexOffset?: Readonly<Record<string, number>>;
|
|
55
|
-
/**
|
|
56
|
-
* Restrict seeding to these tables. Transitive `v.id(...)` parents are added
|
|
57
|
-
* automatically (unless already covered by `existingIds`) so child foreign
|
|
58
|
-
* keys resolve to real rows. The result is still ordered by FK dependency.
|
|
59
|
-
* Default: all tables.
|
|
60
|
-
*/
|
|
61
|
-
only?: ReadonlyArray<string>;
|
|
62
|
-
/** Static values or functions overriding generated columns. */
|
|
63
|
-
overrides?: SeedOverrides;
|
|
64
|
-
/** Deterministic mapping selector — same seed ⇒ same rows. Default `0`. */
|
|
65
|
-
seed?: number;
|
|
66
|
-
}
|
|
67
|
-
/** One table's generated rows, in insert order. Each row carries an explicit `_id`. */
|
|
68
|
-
interface TablePlan {
|
|
69
|
-
rows: ReadonlyArray<Record<string, unknown>>;
|
|
70
|
-
table: string;
|
|
71
|
-
}
|
|
72
|
-
/**
|
|
73
|
-
* Build a deterministic, FK-consistent set of rows for `schema`.
|
|
74
|
-
* @returns one {@link TablePlan} per seeded table, ordered so a table's FK
|
|
75
|
-
* parents come before it.
|
|
76
|
-
*/
|
|
77
|
-
declare const seedPlan: (schema: Schema, options?: SeedOptions) => ReadonlyArray<TablePlan>;
|
|
78
|
-
export { OverrideContext as O, SeedCounts as S, TablePlan as T, SeedOptions as a, SeedOverrides as b, seedPlan as s };
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { s as seedPlan } from './plan-DirmkctQ.mjs';
|