joist-core 2.4.0-next.2 → 2.4.0-next.21
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/build/EntityManager.cjs +25 -11
- package/build/EntityManager.cjs.map +1 -1
- package/build/EntityManager.d.cts +11 -4
- package/build/EntityManager.d.cts.map +1 -1
- package/build/EntityManager.d.mts +11 -4
- package/build/EntityManager.d.mts.map +1 -1
- package/build/EntityManager.js +25 -13
- package/build/EntityManager.js.map +1 -1
- package/build/EntityMetadata.cjs +0 -1
- package/build/EntityMetadata.cjs.map +1 -1
- package/build/EntityMetadata.d.cts +8 -4
- package/build/EntityMetadata.d.cts.map +1 -1
- package/build/EntityMetadata.d.mts +8 -4
- package/build/EntityMetadata.d.mts.map +1 -1
- package/build/EntityMetadata.js +0 -1
- package/build/EntityMetadata.js.map +1 -1
- package/build/IndexManager.cjs +23 -5
- package/build/IndexManager.cjs.map +1 -1
- package/build/IndexManager.d.cts.map +1 -1
- package/build/IndexManager.d.mts.map +1 -1
- package/build/IndexManager.js +23 -5
- package/build/IndexManager.js.map +1 -1
- package/build/batchloaders/populateBatchLoader.cjs +2 -2
- package/build/batchloaders/populateBatchLoader.js +2 -2
- package/build/batchloaders/recursiveChildrenBatchLoader.cjs +1 -1
- package/build/batchloaders/recursiveChildrenBatchLoader.js +1 -1
- package/build/batchloaders/recursiveM2mBatchLoader.cjs +1 -1
- package/build/batchloaders/recursiveM2mBatchLoader.js +1 -1
- package/build/batchloaders/recursiveParentsBatchLoader.cjs +1 -1
- package/build/batchloaders/recursiveParentsBatchLoader.js +1 -1
- package/build/config.cjs +74 -1
- package/build/config.cjs.map +1 -1
- package/build/config.d.cts +83 -2
- package/build/config.d.cts.map +1 -1
- package/build/config.d.mts +83 -2
- package/build/config.d.mts.map +1 -1
- package/build/config.js +74 -1
- package/build/config.js.map +1 -1
- package/build/configure.cjs +6 -2
- package/build/configure.cjs.map +1 -1
- package/build/configure.d.cts.map +1 -1
- package/build/configure.d.mts.map +1 -1
- package/build/configure.js +6 -2
- package/build/configure.js.map +1 -1
- package/build/dataloaders/findDataLoader.cjs +1 -1
- package/build/dataloaders/findDataLoader.js +1 -1
- package/build/dataloaders/findOrCreateDataLoader.cjs +6 -2
- package/build/dataloaders/findOrCreateDataLoader.cjs.map +1 -1
- package/build/dataloaders/findOrCreateDataLoader.d.cts.map +1 -1
- package/build/dataloaders/findOrCreateDataLoader.d.mts.map +1 -1
- package/build/dataloaders/findOrCreateDataLoader.js +7 -3
- package/build/dataloaders/findOrCreateDataLoader.js.map +1 -1
- package/build/dataloaders/findPaginatedDataLoader.cjs +1 -1
- package/build/dataloaders/findPaginatedDataLoader.js +1 -1
- package/build/defaults.cjs +2 -2
- package/build/defaults.js +2 -2
- package/build/fields.cjs +1 -0
- package/build/fields.cjs.map +1 -1
- package/build/fields.d.cts.map +1 -1
- package/build/fields.d.mts.map +1 -1
- package/build/fields.js +1 -0
- package/build/fields.js.map +1 -1
- package/build/index.cjs +13 -8
- package/build/index.cjs.map +1 -1
- package/build/index.d.cts +4 -3
- package/build/index.d.cts.map +1 -1
- package/build/index.d.mts +4 -3
- package/build/index.d.mts.map +1 -1
- package/build/index.js +13 -10
- package/build/index.js.map +1 -1
- package/build/json.cjs +3 -3
- package/build/json.js +3 -3
- package/build/loading/loadHints.cjs +1 -1
- package/build/loading/loadHints.js +1 -1
- package/build/loading/withLoaded.cjs +2 -2
- package/build/loading/withLoaded.js +2 -2
- package/build/newTestInstance.cjs +1 -0
- package/build/newTestInstance.cjs.map +1 -1
- package/build/newTestInstance.d.cts.map +1 -1
- package/build/newTestInstance.d.mts.map +1 -1
- package/build/newTestInstance.js +1 -0
- package/build/newTestInstance.js.map +1 -1
- package/build/preloading/partitionHint.cjs +1 -1
- package/build/preloading/partitionHint.js +1 -1
- package/build/queries/sql/execute.cjs +68 -89
- package/build/queries/sql/execute.cjs.map +1 -1
- package/build/queries/sql/execute.d.cts +35 -18
- package/build/queries/sql/execute.d.cts.map +1 -1
- package/build/queries/sql/execute.d.mts +35 -18
- package/build/queries/sql/execute.d.mts.map +1 -1
- package/build/queries/sql/execute.js +70 -91
- package/build/queries/sql/execute.js.map +1 -1
- package/build/queries/sql/query.cjs +77 -30
- package/build/queries/sql/query.cjs.map +1 -1
- package/build/queries/sql/query.d.cts +64 -21
- package/build/queries/sql/query.d.cts.map +1 -1
- package/build/queries/sql/query.d.mts +64 -21
- package/build/queries/sql/query.d.mts.map +1 -1
- package/build/queries/sql/query.js +75 -30
- package/build/queries/sql/query.js.map +1 -1
- package/build/reactivity/ReactionsManager.cjs +168 -2
- package/build/reactivity/ReactionsManager.cjs.map +1 -1
- package/build/reactivity/ReactionsManager.d.cts +54 -1
- package/build/reactivity/ReactionsManager.d.cts.map +1 -1
- package/build/reactivity/ReactionsManager.d.mts +54 -1
- package/build/reactivity/ReactionsManager.d.mts.map +1 -1
- package/build/reactivity/ReactionsManager.js +169 -3
- package/build/reactivity/ReactionsManager.js.map +1 -1
- package/build/reactivity/reactiveHints.cjs +3 -3
- package/build/reactivity/reactiveHints.cjs.map +1 -1
- package/build/reactivity/reactiveHints.d.cts.map +1 -1
- package/build/reactivity/reactiveHints.d.mts.map +1 -1
- package/build/reactivity/reactiveHints.js +3 -3
- package/build/reactivity/reactiveHints.js.map +1 -1
- package/build/relations/AsyncReactiveField.cjs +3 -3
- package/build/relations/AsyncReactiveField.js +3 -3
- package/build/relations/LazyField.cjs +14 -0
- package/build/relations/LazyField.cjs.map +1 -1
- package/build/relations/LazyField.d.cts +6 -0
- package/build/relations/LazyField.d.cts.map +1 -1
- package/build/relations/LazyField.d.mts +6 -0
- package/build/relations/LazyField.d.mts.map +1 -1
- package/build/relations/LazyField.js +14 -0
- package/build/relations/LazyField.js.map +1 -1
- package/build/relations/ReactiveField.cjs +2 -2
- package/build/relations/ReactiveField.js +2 -2
- package/build/relations/ReactiveManyToMany.cjs +1 -1
- package/build/relations/ReactiveManyToMany.js +1 -1
- package/build/relations/ReactiveReference.cjs +1 -1
- package/build/relations/ReactiveReference.js +1 -1
- package/build/relations/RecursiveCollection.cjs +3 -3
- package/build/relations/RecursiveCollection.js +3 -3
- package/build/relations/hasProperty.cjs +2 -2
- package/build/relations/hasProperty.js +2 -2
- package/build/relations/index.cjs +5 -5
- package/build/relations/index.js +5 -5
- package/build/resurrection.cjs +11 -1
- package/build/resurrection.cjs.map +1 -1
- package/build/resurrection.d.cts +4 -1
- package/build/resurrection.d.cts.map +1 -1
- package/build/resurrection.d.mts +4 -1
- package/build/resurrection.d.mts.map +1 -1
- package/build/resurrection.js +11 -2
- package/build/resurrection.js.map +1 -1
- package/build/transitions.cjs +89 -0
- package/build/transitions.cjs.map +1 -0
- package/build/transitions.d.cts +110 -0
- package/build/transitions.d.cts.map +1 -0
- package/build/transitions.d.mts +110 -0
- package/build/transitions.d.mts.map +1 -0
- package/build/transitions.js +84 -0
- package/build/transitions.js.map +1 -0
- package/package.json +2 -2
package/build/config.d.mts
CHANGED
|
@@ -2,7 +2,8 @@ import { FieldsOf } from "./typeMap.mjs";
|
|
|
2
2
|
import { MaybePromise } from "./utils.mjs";
|
|
3
3
|
import { LoadHint, Loaded, RelationsIn } from "./loading/loadHints.mjs";
|
|
4
4
|
import { Reacted, ReactiveHint } from "./reactivity/reactiveHints.mjs";
|
|
5
|
-
import { ValidationRule, ValidationRuleInternal } from "./rules.mjs";
|
|
5
|
+
import { ValidationRule, ValidationRuleInternal, ValidationRuleResult } from "./rules.mjs";
|
|
6
|
+
import { FieldTransitionsConfig, GuardTransitionMatch, OnTransitionMatch, Transition, TransitionTable } from "./transitions.mjs";
|
|
6
7
|
import { EntityMetadata } from "./EntityMetadata.mjs";
|
|
7
8
|
import { AsyncDefault } from "./defaults.mjs";
|
|
8
9
|
import { EntityField, SettableFields } from "./EntityFields.mjs";
|
|
@@ -16,6 +17,21 @@ type AddReactionOpts = {
|
|
|
16
17
|
runOnce?: boolean;
|
|
17
18
|
name?: string;
|
|
18
19
|
};
|
|
20
|
+
/** A `guardTransition` rule, which also gets the transition it is checking, since the entity may have moved on. */
|
|
21
|
+
type TransitionGuardFn<T extends Entity, V> = (entity: T, transition: Transition<V>) => MaybePromise<ValidationRuleResult>;
|
|
22
|
+
/** An `onTransition` function, which also gets the transition it is handling, since the entity may have moved on. */
|
|
23
|
+
type TransitionFn<T extends Entity, C, V> = (entity: T, ctx: C, transition: Transition<V>) => MaybePromise<unknown>;
|
|
24
|
+
/** The enum type of a transition field, i.e. `PublisherStatus`. */
|
|
25
|
+
type TransitionType<T extends Entity, K extends keyof FieldsOf<T>> = FieldsOf<T>[K] extends EntityField ? NonNullable<FieldsOf<T>[K]["type"]> : never;
|
|
26
|
+
/**
|
|
27
|
+
* The state names that `transitions` tables and `match`es accept for an enum field, i.e. `"Draft"` for
|
|
28
|
+
* `PublisherStatus.Draft`.
|
|
29
|
+
*
|
|
30
|
+
* We only accept the enum's accessors, not its codes or members, so every table reads the same way.
|
|
31
|
+
*/
|
|
32
|
+
type TransitionStates<T extends Entity, K extends keyof FieldsOf<T>> = FieldsOf<T>[K] extends {
|
|
33
|
+
accessors: infer A extends string;
|
|
34
|
+
} ? A : never;
|
|
19
35
|
declare const constraintNameToValidationError: Record<string, string>;
|
|
20
36
|
type Settable<T extends Entity> = keyof SettableFields<FieldsOf<T>> & string;
|
|
21
37
|
/**
|
|
@@ -107,6 +123,9 @@ declare class ConfigApi<T extends Entity, C> {
|
|
|
107
123
|
* 4. Can run multiple times per flush, like an RF/RF. Be careful to avoid creating
|
|
108
124
|
* circular dependencies in the hint and to make the function idempotent.
|
|
109
125
|
*
|
|
126
|
+
* Names default to the registration's source location. Pass unique names when registering multiple
|
|
127
|
+
* reactions from a shared helper or loop; duplicate names on the same config are rejected.
|
|
128
|
+
*
|
|
110
129
|
* @param hint The fields to watch for changes and load before running the reaction
|
|
111
130
|
* @param fn The reaction function to run
|
|
112
131
|
*/
|
|
@@ -144,6 +163,56 @@ declare class ConfigApi<T extends Entity, C> {
|
|
|
144
163
|
* @param fn The reaction function to run
|
|
145
164
|
*/
|
|
146
165
|
addReaction<H extends ReactiveHint<T>>(opts: AddReactionOpts, hint: H, fn: HookFn<Loaded<T, H>, C>): void;
|
|
166
|
+
/**
|
|
167
|
+
* Declares which state transitions of the enum `fieldName` are allowed, i.e. `{ Draft: ["Open"], Open: ["Closed"] }`.
|
|
168
|
+
*
|
|
169
|
+
* Keys and values are the enum's accessors as strings, i.e. `"Draft"` for `AuthorStatus.Draft`.
|
|
170
|
+
*
|
|
171
|
+
* A state that is missing from the table, or maps to `[]`, is treated as a terminal state & cannot be
|
|
172
|
+
* changed. Creating an entity is not a transition, so a new entity may start in any state.
|
|
173
|
+
*
|
|
174
|
+
* The table is checked by the field's setter, so a disallowed transition throws a `ValidationErrors`
|
|
175
|
+
* immediately, instead of failing the next `em.flush`.
|
|
176
|
+
*/
|
|
177
|
+
transitions<K extends Settable<T>>(fieldName: K, table: TransitionTable<TransitionStates<T, K>>): void;
|
|
178
|
+
/**
|
|
179
|
+
* Checks each matching transition before its callbacks run, and rejects it if the guard returns an error.
|
|
180
|
+
*
|
|
181
|
+
* Use this for "a transition is allowed only when ..." checks that depend on other data, while
|
|
182
|
+
* `transitions` declares the transitions that are possible at all. The `hint` is a load hint, like
|
|
183
|
+
* `beforeFlush`'s, so it's loaded before `rule` runs, but only `fieldName` itself triggers the guard.
|
|
184
|
+
*
|
|
185
|
+
* Guards run with reactions, for every matching transition, even if the
|
|
186
|
+
* field has moved on since. The entity is in its current state, so `rule` also gets the `transition`
|
|
187
|
+
* it is checking. Guards never run on creation and are not rechecked during final validation.
|
|
188
|
+
*/
|
|
189
|
+
guardTransition<K extends Settable<T>, H extends LoadHint<T>>(fieldName: K, match: GuardTransitionMatch<TransitionStates<T, K>>, hint: H, rule: TransitionGuardFn<Loaded<T, H>, TransitionType<T, K>>): void;
|
|
190
|
+
guardTransition<K extends Settable<T>>(fieldName: K, match: GuardTransitionMatch<TransitionStates<T, K>>, rule: TransitionGuardFn<T, TransitionType<T, K>>): void;
|
|
191
|
+
/**
|
|
192
|
+
* Runs `fn` for each state transition of `fieldName` that matches `match`.
|
|
193
|
+
*
|
|
194
|
+
* This runs alongside reactions (see `addReaction`), but only state changes queue callbacks.
|
|
195
|
+
* The `hint` is a load hint, like `beforeFlush`'s, so it is loaded but not reacted to.
|
|
196
|
+
*
|
|
197
|
+
* Callbacks run with reactions, once for every matching transition, in order,
|
|
198
|
+
* even if the field has moved on since. The entity is in its current state, so `fn` also gets the
|
|
199
|
+
* `transition` it is handling. Transitions that a `guardTransition` rejects don't fire.
|
|
200
|
+
*
|
|
201
|
+
* Creating an entity with a matching `to` state fires too, unless `match.from` is set or
|
|
202
|
+
* `match.onCreate` is `false`. Set `match.phase: "commit"` to run in `beforeCommit` instead, i.e.
|
|
203
|
+
* for enqueueing jobs.
|
|
204
|
+
*
|
|
205
|
+
* Callbacks that read a new entity's `id` should use `match.phase: "commit"`. Other callbacks may run
|
|
206
|
+
* before ids are assigned, and Joist does not rerun them on a `NoIdError` because their side effects
|
|
207
|
+
* could repeat.
|
|
208
|
+
*
|
|
209
|
+
* Pass a unique name as the first argument when registering multiple callbacks from a shared
|
|
210
|
+
* helper or loop. Duplicate names on the same config are rejected when registered.
|
|
211
|
+
*/
|
|
212
|
+
onTransition<K extends Settable<T>, H extends LoadHint<T>>(fieldName: K, match: OnTransitionMatch<TransitionStates<T, K>>, hint: H, fn: TransitionFn<Loaded<T, H>, C, TransitionType<T, K>>): void;
|
|
213
|
+
onTransition<K extends Settable<T>>(fieldName: K, match: OnTransitionMatch<TransitionStates<T, K>>, fn: TransitionFn<T, C, TransitionType<T, K>>): void;
|
|
214
|
+
onTransition<K extends Settable<T>, H extends LoadHint<T>>(name: string, fieldName: K, match: OnTransitionMatch<TransitionStates<T, K>>, hint: H, fn: TransitionFn<Loaded<T, H>, C, TransitionType<T, K>>): void;
|
|
215
|
+
onTransition<K extends Settable<T>>(name: string, fieldName: K, match: OnTransitionMatch<TransitionStates<T, K>>, fn: TransitionFn<T, C, TransitionType<T, K>>): void;
|
|
147
216
|
/** Adds a synchronous default for `fieldName` to a hard-coded `value`. */
|
|
148
217
|
setDefault<K extends Settable<T>, F = FieldsOf<T>[K]>(fieldName: K, value: F extends EntityField ? F["type"] : never): void;
|
|
149
218
|
/** Adds a synchronous default for `fieldName` to the result of simple sync lambda. */
|
|
@@ -157,6 +226,10 @@ declare class ConfigApi<T extends Entity, C> {
|
|
|
157
226
|
* A noop method that exists solely to keep the `config.placeholder()` line in the initial entity file,
|
|
158
227
|
* until the user is ready to use it. */
|
|
159
228
|
placeholder(): void;
|
|
229
|
+
/** Returns `fieldName`'s transition config, creating it on first use. */
|
|
230
|
+
private fieldTransitions;
|
|
231
|
+
/** Requires unique names across ordinary reactions and transition callbacks. */
|
|
232
|
+
private ensureUniqueReactionName;
|
|
160
233
|
private ensurePreBoot;
|
|
161
234
|
}
|
|
162
235
|
/**
|
|
@@ -247,6 +320,14 @@ declare class ConfigData<T extends Entity, C> {
|
|
|
247
320
|
commitRules: ValidationRuleInternal<T>[];
|
|
248
321
|
/** The reactions for this entity type. */
|
|
249
322
|
reactions: ReactionInternal<T, any, C>[];
|
|
323
|
+
/** Names shared by addReaction and onTransition, including commit-phase callbacks. */
|
|
324
|
+
reactionNames: Set<string>;
|
|
325
|
+
/**
|
|
326
|
+
* Field name -> its `transitions`, `guardTransition`, and `onTransition` config, with accessors not yet converted.
|
|
327
|
+
*
|
|
328
|
+
* The keys are also the fields whose factories accept `withX` opts.
|
|
329
|
+
*/
|
|
330
|
+
transitions: Record<string, FieldTransitionsConfig<T, C>>;
|
|
250
331
|
/** The hooks for this entity type. */
|
|
251
332
|
hooks: Record<EntityHook, HookFn<T, C>[]>;
|
|
252
333
|
/** Synchronous defaults for this entity type, invoked on `em.create`. */
|
|
@@ -273,5 +354,5 @@ declare function getFilePath(line: string): string;
|
|
|
273
354
|
/** Given a callstack, uses heuristics to find the first line that looks like user code. */
|
|
274
355
|
declare function findUserCodeLine(lines: string[]): string;
|
|
275
356
|
//#endregion
|
|
276
|
-
export { ConfigApi, ConfigData, EntityHook, Reactable, Reaction, ReactiveField, ReactiveRule, constraintNameToValidationError, findUserCodeLine, getCallerName, getFilePath, getFuzzyCallerName, resetBootFlag, setAfterMetadataLocked, setBooted };
|
|
357
|
+
export { ConfigApi, ConfigData, EntityHook, Reactable, Reaction, ReactiveField, ReactiveRule, TransitionGuardFn, constraintNameToValidationError, findUserCodeLine, getCallerName, getFilePath, getFuzzyCallerName, resetBootFlag, setAfterMetadataLocked, setBooted };
|
|
277
358
|
//# sourceMappingURL=config.d.mts.map
|
package/build/config.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.d.mts","names":[],"sources":["../src/config.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"config.d.mts","names":[],"sources":["../src/config.ts"],"mappings":";;;;;;;;;;;;;KA8BY;KAQP,OAAO,UAAU,QAAQ,MAAM,QAAQ,GAAG,KAAK,MAAM;KAErD;EAAoB;EAAmB;;;KAGhC,kBAAkB,UAAU,QAAQ,MAC9C,QAAQ,GACR,YAAY,WAAW,OACpB,aAAa;;KAGb,aAAa,UAAU,QAAQ,GAAG,MAAM,QAAQ,GAAG,KAAK,GAAG,YAAY,WAAW,OAAO;;KAGzF,eAAe,UAAU,QAAQ,gBAAgB,SAAS,MAAM,SAAS,GAAG,WAAW,cACxF,YAAY,SAAS,GAAG;;;;;;;KASvB,iBAAiB,UAAU,QAAQ,gBAAgB,SAAS,MAAM,SAAS,GAAG;EACjF,iBAAiB;IAEf;cAGS,iCAAiC;KAEzC,SAAS,UAAU,gBAAgB,eAAe,SAAS;;;;;;;;iBAYhD;iBAIA;;cAKH,UAAU,UAAU,QAAQ;EACvC,QAAM,WAAA,GAAA;;;;;;;;EASN,qBAAqB,wBAAwB;;;;;;;;;;;EAe7C,aAAa,0BAA0B,GAAG,YAAY,QAAQ,GAAG,WAAW;;;;;;;;;;;;EAyB5E,QAAQ,UAAU,aAA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AAY;IAAa,YAAY,UAAU;MAChD,aAAa,IAAI,QAAQ,sBACzB,UAAU,cACR,aAAa;;;;EAiBrB;;UAGQ;;UAKA;UASA;;;;;;;;;;;;iBA8BM;;;;;;;UAYC;;EAEf,QAAQ;;EAER;;EAEA,MAAM;;EAEN;;EAEA;;EAEA,IAAI;;;;;;;;UASW;EACf;;EAEA;;EAEA;;EAEA,MAAM;;EAEN;;EAEA;EACA;;UAGe;EACf;;EAEA,QAAQ;;EAER;;EAEA;;EAEA,MAAM;;EAEN;;EAEA;;EAEA,IAAI;;EAEJ;;KAGU,YAAY,gBAAgB;UAE9B,iBAAiB,UAAU,QAAQ,UAAU,aAAa,IAAI;EACtE;EACA,IAAI,OAAO,GAAG;EACd,MAAM;EACN;;KAGG,sBAAsB,UAAU,WAAW,MAAM,eAAe;;cAGxD,WAAW,UAAU,QAAQ;EACxC,wBAAwB,sBAAsB;EAC9C,gBAAgB;;EAEhB,OAAO,uBAAuB;;EAE9B,aAAa,uBAAuB;;EAEpC,WAAW,iBAAiB,QAAQ;;EAEpC,eAAe;;;;;;EAMf,aAAa,eAAe,uBAAuB,GAAG;;EAEtD,OAAO,OAAO,YAAY,OAAO,GAAG;;EAUpC,cAAc,iBAAiB,QAAQ;;EAEvC,eAAe,eAAe,aAAa;EAG3C,eAAe;EAEf,qBAAqB;EAErB,YAAY;EACZ,qBAAqB,YAAY,YAAY;EAC7C,eAAe,UAAU,YAAY;EAErC,yBAAyB;;EAEzB,eAAe,gBAAgB,QAAQ,GAAG,WAAW;;iBAGvC,cAAc;iBAWd;;;;;;iBAeA,YAAY;;iBAMZ,iBAAiB"}
|
package/build/config.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { convertToLoadHint } from "./reactivity/reactiveHints.js";
|
|
2
1
|
import { fail } from "./utils.js";
|
|
2
|
+
import { convertToLoadHint } from "./reactivity/reactiveHints.js";
|
|
3
3
|
import "./rules.js";
|
|
4
|
+
import { toTransition } from "./transitions.js";
|
|
4
5
|
import { resetConstructorMap } from "./configure.js";
|
|
5
6
|
import { getMetadata } from "./EntityMetadata.js";
|
|
6
7
|
import { AsyncDefault } from "./defaults.js";
|
|
@@ -122,6 +123,7 @@ var ConfigApi = class {
|
|
|
122
123
|
const hint = maybeFn ? hintOrFn : nameOrOptsOrHint;
|
|
123
124
|
const { name = getCallerName(), runOnce = false } = maybeFn ? typeof nameOrOptsOrHint === "string" ? { name: nameOrOptsOrHint } : nameOrOptsOrHint : {};
|
|
124
125
|
this.ensurePreBoot(name, "addReaction");
|
|
126
|
+
this.ensureUniqueReactionName(name, "addReaction");
|
|
125
127
|
const loadHints = /* @__PURE__ */ new Map();
|
|
126
128
|
const wrappedFn = (entity, ctx) => {
|
|
127
129
|
const meta = getMetadata(entity);
|
|
@@ -140,6 +142,57 @@ var ConfigApi = class {
|
|
|
140
142
|
runOnce
|
|
141
143
|
});
|
|
142
144
|
}
|
|
145
|
+
/**
|
|
146
|
+
* Declares which state transitions of the enum `fieldName` are allowed, i.e. `{ Draft: ["Open"], Open: ["Closed"] }`.
|
|
147
|
+
*
|
|
148
|
+
* Keys and values are the enum's accessors as strings, i.e. `"Draft"` for `AuthorStatus.Draft`.
|
|
149
|
+
*
|
|
150
|
+
* A state that is missing from the table, or maps to `[]`, is treated as a terminal state & cannot be
|
|
151
|
+
* changed. Creating an entity is not a transition, so a new entity may start in any state.
|
|
152
|
+
*
|
|
153
|
+
* The table is checked by the field's setter, so a disallowed transition throws a `ValidationErrors`
|
|
154
|
+
* immediately, instead of failing the next `em.flush`.
|
|
155
|
+
*/
|
|
156
|
+
transitions(fieldName, table) {
|
|
157
|
+
const name = `transitions(${getCallerName()})`;
|
|
158
|
+
this.ensurePreBoot(name, "transitions");
|
|
159
|
+
const config = this.fieldTransitions(fieldName);
|
|
160
|
+
if (config.table) fail(`config.transitions was already called for ${fieldName}, use one table per field`);
|
|
161
|
+
config.table = table;
|
|
162
|
+
}
|
|
163
|
+
guardTransition(fieldName, match, hintOrRule, maybeRule) {
|
|
164
|
+
const name = `guardTransition(${getCallerName()})`;
|
|
165
|
+
this.ensurePreBoot(name, "guardTransition");
|
|
166
|
+
const rule = maybeRule ?? hintOrRule;
|
|
167
|
+
const hint = maybeRule ? hintOrRule : void 0;
|
|
168
|
+
this.fieldTransitions(fieldName).guards.push({
|
|
169
|
+
match,
|
|
170
|
+
run(entity, step) {
|
|
171
|
+
const transition = toTransition(step);
|
|
172
|
+
return hint === void 0 ? rule(entity, transition) : entity.em.populate(entity, hint).then((loaded) => rule(loaded, transition));
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
onTransition(nameOrFieldName, fieldNameOrMatch, matchOrHintOrFn, hintOrFn, maybeFn) {
|
|
177
|
+
const named = typeof fieldNameOrMatch === "string";
|
|
178
|
+
const name = named ? nameOrFieldName : `onTransition(${getCallerName()})`;
|
|
179
|
+
this.ensurePreBoot(name, "onTransition");
|
|
180
|
+
this.ensureUniqueReactionName(name, "onTransition");
|
|
181
|
+
const fieldName = named ? fieldNameOrMatch : nameOrFieldName;
|
|
182
|
+
const match = named ? matchOrHintOrFn : fieldNameOrMatch;
|
|
183
|
+
const hintOrCallback = named ? hintOrFn : matchOrHintOrFn;
|
|
184
|
+
const callback = named ? maybeFn : hintOrFn;
|
|
185
|
+
const fn = callback ?? hintOrCallback;
|
|
186
|
+
const hint = callback ? hintOrCallback : void 0;
|
|
187
|
+
this.fieldTransitions(fieldName).callbacks.push({
|
|
188
|
+
name,
|
|
189
|
+
match,
|
|
190
|
+
run(entity, ctx, step) {
|
|
191
|
+
const transition = toTransition(step);
|
|
192
|
+
return hint === void 0 ? fn(entity, ctx, transition) : entity.em.populate(entity, hint).then((loaded) => fn(loaded, ctx, transition));
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
}
|
|
143
196
|
setDefault(fieldName, hintOrFnOrValue, fn) {
|
|
144
197
|
this.ensurePreBoot(getCallerName(), "setDefault");
|
|
145
198
|
if (fn) {
|
|
@@ -151,6 +204,18 @@ var ConfigApi = class {
|
|
|
151
204
|
* A noop method that exists solely to keep the `config.placeholder()` line in the initial entity file,
|
|
152
205
|
* until the user is ready to use it. */
|
|
153
206
|
placeholder() {}
|
|
207
|
+
/** Returns `fieldName`'s transition config, creating it on first use. */
|
|
208
|
+
fieldTransitions(fieldName) {
|
|
209
|
+
return this.__data.transitions[fieldName] ??= {
|
|
210
|
+
guards: [],
|
|
211
|
+
callbacks: []
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
/** Requires unique names across ordinary reactions and transition callbacks. */
|
|
215
|
+
ensureUniqueReactionName(name, op) {
|
|
216
|
+
if (this.__data.reactionNames.has(name)) throw new Error(`Duplicate reaction name "${name}" in config.${op}. Pass a unique name when registering reactions from a shared helper or loop.`);
|
|
217
|
+
this.__data.reactionNames.add(name);
|
|
218
|
+
}
|
|
154
219
|
ensurePreBoot(name, op) {
|
|
155
220
|
if (booted) {
|
|
156
221
|
if (isRunningInNextJs()) {
|
|
@@ -188,6 +253,14 @@ var ConfigData = class {
|
|
|
188
253
|
commitRules = [];
|
|
189
254
|
/** The reactions for this entity type. */
|
|
190
255
|
reactions = [];
|
|
256
|
+
/** Names shared by addReaction and onTransition, including commit-phase callbacks. */
|
|
257
|
+
reactionNames = /* @__PURE__ */ new Set();
|
|
258
|
+
/**
|
|
259
|
+
* Field name -> its `transitions`, `guardTransition`, and `onTransition` config, with accessors not yet converted.
|
|
260
|
+
*
|
|
261
|
+
* The keys are also the fields whose factories accept `withX` opts.
|
|
262
|
+
*/
|
|
263
|
+
transitions = {};
|
|
191
264
|
/** The hooks for this entity type. */
|
|
192
265
|
hooks = {
|
|
193
266
|
beforeDelete: [],
|
package/build/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","names":[],"sources":["../src/config.ts"],"sourcesContent":["import { resetConstructorMap } from \"src/configure.ts\";\nimport { AsyncDefault } from \"src/defaults.ts\";\nimport { type Entity } from \"src/Entity.ts\";\nimport {\n type EntityConstructor,\n type EntityField,\n type EntityMetadata,\n type FieldsOf,\n type LoadHint,\n type Loaded,\n type MaybeAbstractEntityConstructor,\n type Reacted,\n type ReactiveHint,\n type RelationsIn,\n type SettableFields,\n fail,\n getMetadata,\n} from \"src/index.ts\";\nimport { convertToLoadHint } from \"src/reactivity/reactiveHints.ts\";\nimport { type ValidationRule, type ValidationRuleInternal } from \"src/rules.ts\";\nimport { type MaybePromise } from \"src/utils.ts\";\n\nexport type EntityHook =\n | \"beforeFlush\"\n | \"beforeCreate\"\n | \"beforeUpdate\"\n | \"beforeDelete\"\n | \"afterValidation\"\n | \"beforeCommit\"\n | \"afterCommit\";\ntype HookFn<T extends Entity, C> = (entity: T, ctx: C) => MaybePromise<unknown>;\n\ntype AddReactionOpts = { runOnce?: boolean; name?: string };\n\nexport const constraintNameToValidationError: Record<string, string> = {};\n\ntype Settable<T extends Entity> = keyof SettableFields<FieldsOf<T>> & string;\n\nlet booted = false;\nlet afterMetadataLocked = false;\n\n/**\n * Called at the end of `configureMetadata` to indicate the boot process is complete.\n *\n * We use this flag to prevent users from mistakenly calling `config` methods after the boot\n * process is complete, i.e. from hooks or other post-boot invocations, where the calls are\n * not guaranteed to work because Joist's reactivity graph has already been initialized.\n */\nexport function setBooted(): void {\n booted = true;\n}\n\nexport function setAfterMetadataLocked(): void {\n afterMetadataLocked = true;\n}\n\n/** The public API to configure an Entity's hooks & validation rules. */\nexport class ConfigApi<T extends Entity, C> {\n __data = new ConfigData<T, C>();\n\n /**\n * Maps a given `constraintName`, i.e. `authors_publisher_id_unique_index`, to a hard-coded-but-pretty validation errors.\n *\n * Note that the validationError must be hard-coded b/c we cannot tease out \"which entity\" caused a given\n * constraint failure from the SQL database. If you really need pretty-and-custom validation errors, you'll\n * need to check the constraint by hand ahead of time, before calling `em.flush`.\n */\n addConstraintMessage(constraintName: string, validationError: string) {\n this.ensurePreBoot(getCallerName(), \"addConstraintMessage\");\n constraintNameToValidationError[constraintName] = validationError;\n }\n\n /**\n * Maps a `RecursiveCycleError` on the given recursive collection field to a custom validation error.\n *\n * When a cycle is detected in a recursive collection (e.g. `parentsRecursive`), instead of\n * throwing a raw `RecursiveCycleError`, `em.flush` will convert it into a `ValidationErrors`\n * using the provided message function.\n *\n * The `messageFn` receives the entity that detected the cycle and the cycle path (array of\n * entities forming the cycle), and should return a validation error string.\n */\n addCycleRule(fieldName: string & keyof T, messageFn: (entity: T, cyclePath: Entity[]) => string) {\n this.ensurePreBoot(getCallerName(), \"addCycleRule\");\n this.__data.cycleMessages[fieldName] = messageFn;\n // Register a reactive rule that loads the recursive collection and catches cycle errors.\n // The rule uses the recursive collection's underlying relation as a reactive hint so it\n // triggers when the collection changes.\n const hint = fieldName as any;\n const fn = () => {\n // We don't actually need a try/catch/anything here, b/c if there is a cycle, it\n // will cause a CycleError during followReverseHint, and never even get to calling this fn.\n };\n this.__data.rules.push({ name: `addCycleRule(${getCallerName()})`, fn, hint });\n }\n\n /**\n * Adds a validation rule for this entity.\n *\n * If `hint` is passed, then the rule's lambda will be: 1) passed a view of the entity with only\n * the fields included in `hint` marked as accessible, and 2) the rule will be called reactively any\n * time any field in the `hint` changes.\n *\n * If lambdas want to access fields w/o having them marked for reactivity, the rule can either\n * include the field as readonly with a `:ro` suffix, i.e. `firstName:ro`, or the lambda can\n * access the `reacted.entity` property to get a full view of the entity's fields and methods.\n */\n addRule<H extends ReactiveHint<T>>(hint: H, rule: ValidationRule<Reacted<T, H>>): void;\n addRule(rule: ValidationRule<T>): void;\n addRule(ruleOrHint: ValidationRule<T> | any, maybeRule?: ValidationRule<any>): void {\n // Keep the name for easy debugging/tracing later\n const name = `addRule(${getCallerName()})`;\n this.ensurePreBoot(name, \"addRule\");\n pushValidationRule(this.__data.rules, name, ruleOrHint, maybeRule);\n }\n\n /**\n * Adds a \"commit rule\" that runs like a regular validation rule (see {@link addRule}), but *after*\n * the entity's `INSERT`/`UPDATE`/`DELETE` has been flushed to the database and *before* the\n * transaction `COMMIT`s, i.e. still within the transaction.\n *\n * The point of running this late is that any `em.find`s the rule makes will query the _changed_\n * state (the just-flushed rows), instead of the pre-flush state that regular `addRule` rules see.\n * This is useful for cross-row invariants that are easiest to express as a query, e.g. \"at most\n * one active `AuthorSchedule` per author\", where the rule wants to `em.find` the sibling rows\n * that were themselves just inserted/updated in this same flush.\n *\n * Like `addRule`, if a `hint` is passed the rule is reactive: it runs whenever any field in the\n * hint changes (walking back to the owning entity), and the lambda gets a `Reacted` view.\n */\n addCommitRule<H extends ReactiveHint<T>>(hint: H, rule: ValidationRule<Reacted<T, H>>): void;\n addCommitRule(rule: ValidationRule<T>): void;\n addCommitRule(ruleOrHint: ValidationRule<T> | any, maybeRule?: ValidationRule<any>): void {\n // Keep the name for easy debugging/tracing later\n const name = `addCommitRule(${getCallerName()})`;\n this.ensurePreBoot(name, \"addCommitRule\");\n pushValidationRule(this.__data.commitRules, name, ruleOrHint, maybeRule);\n }\n\n /** If both this entity, and `cstr` entities, are in the same `em.flush`, run us first. */\n runHooksBefore(cstr: EntityConstructor<any>): void {\n this.__data.runHooksBefore.push(cstr);\n }\n\n /** Deletes any entity/entities pointed to by `relation` when this entity is deleted. */\n cascadeDelete(relation: keyof RelationsIn<T> & LoadHint<T>): void {\n this.ensurePreBoot(getCallerName(), \"cascadeDelete\");\n this.__data.cascadeDeleteFields.push(relation);\n }\n\n touchOnChange(relation: keyof RelationsIn<T>): void {\n this.ensurePreBoot(getCallerName(), \"touchOnChange\");\n this.__data.touchOnChange.add(relation);\n }\n\n private addHook(hook: EntityHook, ruleOrHint: HookFn<T, C> | any, maybeFn?: HookFn<Loaded<T, any>, C>) {\n this.ensurePreBoot(getCallerName(), \"addHook\");\n if (typeof ruleOrHint === \"function\") {\n this.__data.hooks[hook].push(ruleOrHint);\n } else {\n const fn = async (entity: T, ctx: C) => {\n // TODO Use this for reactive beforeFlush\n const loaded = await entity.em.populate(entity, ruleOrHint);\n return maybeFn!(loaded, ctx);\n };\n // Squirrel our hint away where configureMetadata can find it\n (fn as any).hint = ruleOrHint;\n this.__data.hooks[hook].push(fn);\n }\n }\n\n afterMetadata(fn: AfterMetadataCallback<T>): void {\n if (afterMetadataLocked) {\n throw new Error(\n `config.afterMetadata on ${getCallerName()} must only be called on boot, before calling \\`configureMetadata\\` and not from other \\`afterMetadata\\` hooks.`,\n );\n }\n this.__data.afterMetadataCallbacks.push(fn);\n }\n\n beforeDelete<H extends LoadHint<T>>(populate: H, fn: HookFn<Loaded<T, H>, C>): void;\n beforeDelete(fn: HookFn<T, C>): void;\n beforeDelete(ruleOrHint: HookFn<T, C> | any, maybeFn?: HookFn<Loaded<T, any>, C>): void {\n this.addHook(\"beforeDelete\", ruleOrHint, maybeFn);\n }\n\n beforeFlush<H extends LoadHint<T>>(populate: H, fn: HookFn<Loaded<T, H>, C>): void;\n beforeFlush(fn: HookFn<T, C>): void;\n beforeFlush(ruleOrHint: HookFn<T, C> | any, maybeFn?: HookFn<Loaded<T, any>, C>): void {\n this.addHook(\"beforeFlush\", ruleOrHint, maybeFn);\n }\n\n // beforeCreate still needs to take a hint because even though the entity itself is New<T>, we might want to load\n // a nested relation that isn't loaded yet\n beforeCreate<H extends LoadHint<T>>(populate: H, fn: HookFn<Loaded<T, H>, C>): void;\n beforeCreate(fn: HookFn<T, C>): void;\n beforeCreate(ruleOrHint: HookFn<T, C> | any, maybeFn?: HookFn<Loaded<T, any>, C>): void {\n this.addHook(\"beforeCreate\", ruleOrHint, maybeFn);\n }\n\n beforeUpdate<H extends LoadHint<T>>(populate: H, fn: HookFn<Loaded<T, H>, C>): void;\n beforeUpdate(fn: HookFn<T, C>): void;\n beforeUpdate(ruleOrHint: HookFn<T, C> | any, maybeFn?: HookFn<Loaded<T, any>, C>): void {\n this.addHook(\"beforeUpdate\", ruleOrHint, maybeFn);\n }\n\n afterValidation<H extends LoadHint<T>>(populate: H, fn: HookFn<Loaded<T, H>, C>): void;\n afterValidation(fn: HookFn<T, C>): void;\n afterValidation(ruleOrHint: HookFn<T, C> | any, maybeFn?: HookFn<Loaded<T, any>, C>): void {\n this.addHook(\"afterValidation\", ruleOrHint, maybeFn);\n }\n\n beforeCommit(fn: HookFn<T, C>): void {\n this.addHook(\"beforeCommit\", fn);\n }\n\n afterCommit(fn: HookFn<T, C>): void {\n this.addHook(\"afterCommit\", fn);\n }\n\n /**\n * Adds a reaction that runs during flush whenever fields in the `hint` change.\n *\n * Reactions are somewhere in between hooks and reactive fields/references:\n * 1. Can make arbitrary changes to any entity like a hook\n * 2. Only run when the provided hint has changes, not on every flush, like an RF/RR\n * 3. Run when the entity itself has no changes, like an RF/RF\n * 4. Can run multiple times per flush, like an RF/RF. Be careful to avoid creating\n * circular dependencies in the hint and to make the function idempotent.\n *\n * @param hint The fields to watch for changes and load before running the reaction\n * @param fn The reaction function to run\n */\n addReaction<H extends ReactiveHint<T>>(hint: H, fn: HookFn<Loaded<T, H>, C>): void;\n /**\n * Adds a named reaction that runs during flush whenever fields in the `hint` change.\n *\n * Reactions are somewhere in between hooks and reactive fields/references:\n * 1. Can make arbitrary changes to any entity like a hook\n * 2. Only run when `hint` has changes, not on every flush, like an RF/RR\n * 3. Can run when the entity itself has no changes, like an RF/RF\n * 4. Can run multiple times per flush, like an RF/RF. Be careful to avoid creating\n * circular dependencies in the hint and to make the function idempotent.\n *\n * @param name A name to identify this reaction for debugging\n * @param hint The fields to watch for changes and load before running the reaction\n * @param fn The reaction function to run\n */\n addReaction<H extends ReactiveHint<T>>(name: string, hint: H, fn: HookFn<Loaded<T, H>, C>): void;\n /**\n * Adds a reaction that runs during flush whenever fields in the `hint` change.\n *\n * Reactions are somewhere in between hooks and reactive fields/references:\n * 1. Can make arbitrary changes to any entity like a hook\n * 2. Only run when `hint` has changes, not on every flush, like an RF/RR\n * 3. Can run when the entity itself has no changes, like an RF/RF\n * 4. Can run multiple times per flush, like an RF/RF. Be careful to avoid creating\n * circular dependencies in the hint and to make the function idempotent.\n *\n * @param opts Options object containing:\n * - runOnce - If true, the reaction will only run once per flush, not every time the hint changes. Optional.\n * default: false.\n * - name - A name to identify this reaction for debugging\n * @param hint The fields to watch for changes and load before running the reaction\n * @param fn The reaction function to run\n */\n addReaction<H extends ReactiveHint<T>>(opts: AddReactionOpts, hint: H, fn: HookFn<Loaded<T, H>, C>): void;\n addReaction<H extends ReactiveHint<T>>(\n nameOrOptsOrHint: string | AddReactionOpts | H,\n hintOrFn: H | HookFn<Loaded<T, H>, C>,\n maybeFn?: HookFn<Loaded<T, H>, C>,\n ): void {\n // Keep the name so we can uniquely identify this reaction later and also aid debugging/tracing\n const fn = maybeFn ?? (hintOrFn as HookFn<Loaded<T, H>, C>);\n const hint = (maybeFn ? hintOrFn : nameOrOptsOrHint) as H;\n const opts = maybeFn\n ? typeof nameOrOptsOrHint === \"string\"\n ? { name: nameOrOptsOrHint }\n : (nameOrOptsOrHint as AddReactionOpts)\n : {};\n const { name = getCallerName(), runOnce = false } = opts;\n this.ensurePreBoot(name, \"addReaction\");\n // Cache load hints per-meta because CTI subtypes may resolve `hint` to different\n // load hints (e.g. an AsyncProperty overridden in the subtype with subtype-only relations).\n const loadHints = new Map<EntityMetadata, LoadHint<T>>();\n const wrappedFn = (entity: T, ctx: C) => {\n const meta = getMetadata(entity);\n let loadHint = loadHints.get(meta);\n if (loadHint === undefined) {\n loadHint = convertToLoadHint<T>(meta, hint);\n loadHints.set(meta, loadHint);\n }\n if (Object.keys(loadHint).length > 0) {\n return entity.em.populate(entity, loadHint).then((loaded) => fn(loaded as Loaded<T, H>, ctx));\n }\n return fn(entity as Loaded<T, H>, ctx);\n };\n this.__data.reactions.push({ name, fn: wrappedFn, hint, runOnce });\n }\n\n /** Adds a synchronous default for `fieldName` to a hard-coded `value`. */\n setDefault<K extends Settable<T>, F = FieldsOf<T>[K]>(\n fieldName: K,\n // Allow returning undefined to mean \"no default\"\n value: F extends EntityField ? F[\"type\"] : never,\n ): void;\n /** Adds a synchronous default for `fieldName` to the result of simple sync lambda. */\n setDefault<K extends Settable<T>, F = FieldsOf<T>[K]>(\n fieldName: K,\n // ...this doesn't technically declare what other fields of `entity` we depend on,\n // which ideally we want to drive \"which default to set first?\" precedence decisions.\n fn: (entity: T) => F extends EntityField ? F[\"type\"] | undefined : never,\n ): void;\n /** Adds an asynchronous default for `fieldName` to the result of a hinted lambda. */\n setDefault<K extends Settable<T>, const H extends ReactiveHint<T>, F = FieldsOf<T>[K]>(\n fieldName: K,\n // We use a ReactiveHint so that we get field-level dependencies that means someday\n // we could drive \"which default to set first?\" precedence decisions.\n hint: H,\n fn: (\n entity: Reacted<T, H>,\n ctx: C,\n ) => F extends { kind: \"m2o\"; type: infer T extends Entity }\n ? MaybePromise<T | Reacted<T, {}> | undefined>\n : F extends EntityField\n ? MaybePromise<F[\"type\"] | undefined>\n : never,\n ): void;\n setDefault<K extends keyof SettableFields<FieldsOf<T>> & string>(fieldName: K, hintOrFnOrValue: any, fn?: any): void {\n this.ensurePreBoot(getCallerName(), \"setDefault\");\n if (fn) {\n // If we're called once by the codegen, and again by the user, override the syncDefault\n delete this.__data.syncDefaults[fieldName];\n this.__data.asyncDefaults[fieldName] = new AsyncDefault(fieldName, hintOrFnOrValue, fn);\n } else {\n this.__data.syncDefaults[fieldName] = hintOrFnOrValue;\n }\n }\n\n /**\n * A noop method that exists solely to keep the `config.placeholder()` line in the initial entity file,\n * until the user is ready to use it. */\n placeholder(): void {}\n\n private ensurePreBoot(name: string, op: string): void {\n if (booted) {\n // Detect if this is NextJS and we're in a hot-reload situation\n if (isRunningInNextJs()) {\n // Reset our bag of config data to collect only the new rules/hooks\n this.__data = new ConfigData();\n resetBootFlag();\n } else {\n throw new Error(\n `config.${op} call on ${name} must only be called on boot, before calling \\`configureMetadata\\`.`,\n );\n }\n }\n }\n}\n\nfunction isRunningInNextJs(): boolean {\n return \"__NEXT_HTTP_AGENT\" in globalThis || \"__NEXT_HTTPS_AGENT\" in globalThis;\n}\n\n/**\n * Allows projects to manually reset the internal `booted` flag.\n *\n * This is only necessary if they're using hot-reloading and reloading their entity files\n * without restarting the server.\n *\n * Generally most tools like tsx or ts-node-dev reload the whole process, so don't need\n * to call this, but if Joist is used in a framework that does actual-hot-reloading, this\n * it will be necessary.\n */\nexport function resetBootFlag(): void {\n booted = false;\n afterMetadataLocked = false;\n resetConstructorMap();\n}\n\n/**\n * Stores a path back to a reactive rule.\n *\n * I.e. if `Book` has a `ruleFn` that reacts to `Author.title`, then `Author`'s config will have\n * a `ReactiveRule` with fields `[\"title\"]`, path `books`, and rule `ruleFn`.\n */\nexport interface ReactiveRule {\n /** The source we're reacting to, specifically which base/subtype cstr. */\n source: MaybeAbstractEntityConstructor<any>;\n /** The fields on this source entity that would trigger the downstream rule's eval. */\n fields: string[];\n /** The constructor of downstream entity that owns the reactive rule. */\n cstr: MaybeAbstractEntityConstructor<any>;\n /** The name (source location) of the downstream reactive rule. */\n name: string;\n /** The path from this source entity to the downstream entity that needs evaled. */\n path: string[];\n /** The downstream validation rule to eval. */\n fn: ValidationRule<any>;\n}\n\n/**\n * Stores a path back to a reactive derived field.\n *\n * I.e. if `Book.displayName` is an `asyncField` that reacts to `Author.title`, then `Author`'s config will have\n * a `ReactiveFields` with fields `[\"title\"]`, path `books`, and name `displayName`.\n */\nexport interface ReactiveField {\n kind: \"populate\" | \"query\";\n /** The fields on this source entity that would trigger the downstream field's recalc. */\n fields: string[];\n /** Read-only/immutable fields that are used in the derived field. */\n isReadOnly: boolean;\n /** The constructor of downstream entity that owns the derived field. */\n cstr: MaybeAbstractEntityConstructor<any>;\n /** The path from this source entity to the downstream entity that needs recalced. */\n path: string[];\n /** The name of the reactive field in the downstream entity to recalc. */\n name: string;\n runOnce: false;\n}\n\nexport interface Reaction {\n kind: \"reaction\";\n /** The source we're reacting to, specifically which base/subtype cstr. */\n source: MaybeAbstractEntityConstructor<any>;\n /** The fields on this source entity that would trigger the downstream hook's eval. */\n fields: string[];\n /** Read-only/immutable fields that are used in the function. */\n isReadOnly: boolean;\n /** The constructor of downstream entity that owns the reaction. */\n cstr: MaybeAbstractEntityConstructor<any>;\n /** The name (source location) of the downstream reaction. */\n name: string;\n /** The path from this source entity to the downstream entity for this reaction. */\n path: string[];\n /** The downstream reaction function. */\n fn: HookFn<any, any>;\n /** If true, the reaction should only run once per flush, not every time the hint changes. */\n runOnce: boolean;\n}\n\nexport type Reactable = ReactiveField | Reaction;\n\ninterface ReactionInternal<T extends Entity, H extends ReactiveHint<T>, C> {\n name: string;\n fn: HookFn<T, C>;\n hint: H;\n runOnce: boolean;\n}\n\ntype AfterMetadataCallback<T extends Entity> = (meta: EntityMetadata<T>) => void;\n\n/** The internal state of an entity's configuration data, i.e. validation rules/hooks. */\nexport class ConfigData<T extends Entity, C> {\n afterMetadataCallbacks: AfterMetadataCallback<T>[] = [];\n runHooksBefore: EntityConstructor<any>[] = [];\n /** The validation rules for this entity type. */\n rules: ValidationRuleInternal<T>[] = [];\n /** The \"commit rules\" for this entity type, i.e. validation rules that run post-flush/pre-commit. */\n commitRules: ValidationRuleInternal<T>[] = [];\n /** The reactions for this entity type. */\n reactions: ReactionInternal<T, any, C>[] = [];\n /** The hooks for this entity type. */\n hooks: Record<EntityHook, HookFn<T, C>[]> = {\n beforeDelete: [],\n beforeFlush: [],\n beforeCreate: [],\n beforeUpdate: [],\n afterValidation: [],\n beforeCommit: [],\n afterCommit: [],\n };\n /** Synchronous defaults for this entity type, invoked on `em.create`. */\n syncDefaults: Record<string, ((entity: T) => void) | unknown> = {};\n /** Asynchronous defaults for this entity type, invoked on `em.flush`. */\n asyncDefaults: Record<string, AsyncDefault<T>> = {};\n\n // An array of the reactive rules that depend on this entity\n reactiveRules: ReactiveRule[] = [];\n // An array of the reactive *commit* rules (post-flush/pre-commit) that depend on this entity\n reactiveCommitRules: ReactiveRule[] = [];\n // An array of the reactive fields and reactions that depend on this entity\n reactables: Reactable[] = [];\n cascadeDeleteFields: Array<keyof RelationsIn<T>> = [];\n touchOnChange: Set<keyof RelationsIn<T>> = new Set();\n // Constantly converting reactive hints to load hints is expense, so cache them here\n cachedReactiveLoadHints: Record<string, any> = {};\n /** Maps recursive collection fieldNames to custom cycle error message functions. */\n cycleMessages: Record<string, (entity: T, cyclePath: Entity[]) => string> = {};\n}\n\nexport function getCallerName(extraFrames: number = 0): string {\n const err = getStack();\n // E.g. at Object.<anonymous> (/home/stephen/homebound/graphql-service/src/entities/Activity.ts:86:8)\n // (Make sure to drop lines that don't start with 'at' b/c the stack format can differ\n // slightly i.e. if running via tsx/using a node loader (probably?)\n const line = err.stack!.split(\"\\n\").filter((line) => line.includes(\" at \"))[3 + extraFrames];\n const parts = line.split(\"/\");\n // Get the last part, which will be the file name, i.e. Activity.ts:86:8\n return parts[parts.length - 1].replace(/:\\d+\\)?$/, \"\");\n}\n\nexport function getFuzzyCallerName(): string {\n const err = getStack();\n const lines = err\n .stack!.split(\"\\n\")\n // E.g. at Object.<anonymous> (/home/stephen/homebound/graphql-service/src/entities/Activity.ts:86:8)\n .filter((line) => line.includes(\" at \"));\n const line = findUserCodeLine(lines);\n return getFilePath(line);\n}\n\n/**\n * Given a callstack line return the file name.\n *\n * I.e. `at Object.<anonymous> (/home/stephen/homebound/graphql-service/src/entities/Activity.ts:86:8)`\n */\nexport function getFilePath(line: string): string {\n const parts = line.split(\"/\");\n return parts[parts.length - 1].replace(/:\\d+\\)?$/, \"\"); // Drop the `:8)`at the end\n}\n\n/** Given a callstack, uses heuristics to find the first line that looks like user code. */\nexport function findUserCodeLine(lines: string[]): string {\n return (\n lines.find((line) => {\n // When running Joist's own integration tests, if we ignore `/joist-orm/`, we'll end up ignoring\n // everything because `joist-orm` is the name of the repository/working copy itself.\n const withinWorkingCopyJoist = line.includes(\"/packages/orm/\") || line.includes(\"/packages/core\");\n // But once we're not in a working copy, assume any `/joist-orm/` in the path === internal orm stack frames\n const withinProductionJoist =\n !withinWorkingCopyJoist && (line.includes(\"/joist-orm/src/\") || line.includes(\"/joist-core/src\"));\n const nodeInternals = line.includes(\"node:internal/\") || line.includes(\"Promise.all\");\n const isUserCode = !withinWorkingCopyJoist && !withinProductionJoist && !nodeInternals;\n // const isRecalc = line.includes(\".recalcPending\");\n const isDefault = line.includes(\"/defaults.ts\");\n // Batched calls like findOrCreate won't have a stack trace back to the true caller, so just stop there\n const isDataloader = line.includes(\"/dataloaders/\");\n // If this is the `newTestInstance` call\n // What about:\n // recalcSynchronousDerivedFields\n return (\n (isDefault || isDataloader || isUserCode) &&\n !line.includes(\"Codegen.ts\") &&\n // I wanted to exclude this, but it was actually our utils/entities.ts maybeSetDefault helper method\n // !line.includes(\"entities.ts\") &&\n // Ignore loops in joist code like setOpts\n !line.includes(\"at Array\") &&\n // Ignore the Author.ts constructor calling setOpts\n !line.includes(\"at new \")\n );\n }) ?? fail(\"Could not find caller name\")\n );\n}\n\nconst getStack: () => { stack?: string } = \"captureStackTrace\" in Error ? getStackFromCapture : getStackFromObject;\n\nfunction getStackFromCapture(): { stack?: string } {\n const obj = {};\n Error.captureStackTrace(obj);\n return obj as any;\n}\n\nfunction getStackFromObject(): { stack?: string } {\n try {\n throw Error(\"\");\n } catch (err) {\n return err as Error;\n }\n}\n\n/** Pushes a validation rule (either the raw or hinted/reactive form) onto `rules`, shared by `addRule`/`addCommitRule`. */\nfunction pushValidationRule<T extends Entity>(\n rules: ValidationRuleInternal<T>[],\n name: string,\n ruleOrHint: ValidationRule<T> | any,\n maybeRule: ValidationRule<any> | undefined,\n): void {\n if (typeof ruleOrHint === \"function\") {\n rules.push({ name, fn: ruleOrHint, hint: undefined });\n } else {\n const hint = ruleOrHint;\n // Cache load hints per-meta because CTI subtypes may resolve `hint` to different\n // load hints (e.g. an AsyncProperty overridden in the subtype with subtype-only relations).\n const loadHints = new Map<EntityMetadata, LoadHint<T>>();\n const fn = (entity: T) => {\n const meta = getMetadata(entity);\n let loadHint = loadHints.get(meta);\n if (loadHint === undefined) {\n loadHint = convertToLoadHint<T>(meta, hint);\n loadHints.set(meta, loadHint);\n }\n if (Object.keys(loadHint).length > 0) {\n return entity.em.populate(entity, loadHint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AS,YAAY,KAI3B,CAAC,KAAK,SAAS,UAAU,KAEzB,CAAC,KAAK,SAAS,SAAS;CAE5B,CAAC,KAAK,KAAK,4BAA4B;AAE3C;AAEA,MAAM,WAAqC,uBAAuB,QAAQ,sBAAsB;AAEhG,SAAS,sBAA0C;CACjD,MAAM,MAAM,CAAC;CACb,MAAM,kBAAkB,GAAG;CAC3B,OAAO;AACT;AAEA,SAAS,qBAAyC;CAChD,IAAI;EACF,MAAM,MAAM,EAAE;CAChB,SAAS,KAAK;EACZ,OAAO;CACT;AACF;;AAGA,SAAS,mBACP,OACA,MACA,YACA,WACM;CACN,IAAI,OAAO,eAAe,YACxB,MAAM,KAAK;EAAE;EAAM,IAAI;EAAY,MAAM,KAAA;CAAU,CAAC;MAC/C;EACL,MAAM,OAAO;EAGb,MAAM,4BAAY,IAAI,IAAiC;EACvD,MAAM,MAAM,WAAc;GACxB,MAAM,OAAO,YAAY,MAAM;GAC/B,IAAI,WAAW,UAAU,IAAI,IAAI;GACjC,IAAI,aAAa,KAAA,GAAW;IAC1B,WAAW,kBAAqB,MAAM,IAAI;IAC1C,UAAU,IAAI,MAAM,QAAQ;GAC9B;GACA,IAAI,OAAO,KAAK,QAAQ,CAAC,CAAC,SAAS,GACjC,OAAO,OAAO,GAAG,SAAS,QAAQ,QAAQ,CAAC,CAAC,KAAK,SAAU;GAE7D,OAAO,UAAW,MAAM;EAC1B;EACA,MAAM,KAAK;GAAE;GAAM;GAAI;EAAK,CAAC;CAC/B;AACF"}
|
|
1
|
+
{"version":3,"file":"config.js","names":[],"sources":["../src/config.ts"],"sourcesContent":["import { resetConstructorMap } from \"src/configure.ts\";\nimport { AsyncDefault } from \"src/defaults.ts\";\nimport { type Entity } from \"src/Entity.ts\";\nimport {\n type EntityConstructor,\n type EntityField,\n type EntityMetadata,\n type FieldsOf,\n type LoadHint,\n type Loaded,\n type MaybeAbstractEntityConstructor,\n type Reacted,\n type ReactiveHint,\n type RelationsIn,\n type SettableFields,\n fail,\n getMetadata,\n} from \"src/index.ts\";\nimport { convertToLoadHint } from \"src/reactivity/reactiveHints.ts\";\nimport { type ValidationRule, type ValidationRuleInternal, type ValidationRuleResult } from \"src/rules.ts\";\nimport {\n type FieldTransitionsConfig,\n type GuardTransitionMatch,\n type OnTransitionMatch,\n type Transition,\n type TransitionTable,\n toTransition,\n} from \"src/transitions.ts\";\nimport { type MaybePromise } from \"src/utils.ts\";\n\nexport type EntityHook =\n | \"beforeFlush\"\n | \"beforeCreate\"\n | \"beforeUpdate\"\n | \"beforeDelete\"\n | \"afterValidation\"\n | \"beforeCommit\"\n | \"afterCommit\";\ntype HookFn<T extends Entity, C> = (entity: T, ctx: C) => MaybePromise<unknown>;\n\ntype AddReactionOpts = { runOnce?: boolean; name?: string };\n\n/** A `guardTransition` rule, which also gets the transition it is checking, since the entity may have moved on. */\nexport type TransitionGuardFn<T extends Entity, V> = (\n entity: T,\n transition: Transition<V>,\n) => MaybePromise<ValidationRuleResult>;\n\n/** An `onTransition` function, which also gets the transition it is handling, since the entity may have moved on. */\ntype TransitionFn<T extends Entity, C, V> = (entity: T, ctx: C, transition: Transition<V>) => MaybePromise<unknown>;\n\n/** The enum type of a transition field, i.e. `PublisherStatus`. */\ntype TransitionType<T extends Entity, K extends keyof FieldsOf<T>> = FieldsOf<T>[K] extends EntityField\n ? NonNullable<FieldsOf<T>[K][\"type\"]>\n : never;\n\n/**\n * The state names that `transitions` tables and `match`es accept for an enum field, i.e. `\"Draft\"` for\n * `PublisherStatus.Draft`.\n *\n * We only accept the enum's accessors, not its codes or members, so every table reads the same way.\n */\ntype TransitionStates<T extends Entity, K extends keyof FieldsOf<T>> = FieldsOf<T>[K] extends {\n accessors: infer A extends string;\n}\n ? A\n : never;\n\nexport const constraintNameToValidationError: Record<string, string> = {};\n\ntype Settable<T extends Entity> = keyof SettableFields<FieldsOf<T>> & string;\n\nlet booted = false;\nlet afterMetadataLocked = false;\n\n/**\n * Called at the end of `configureMetadata` to indicate the boot process is complete.\n *\n * We use this flag to prevent users from mistakenly calling `config` methods after the boot\n * process is complete, i.e. from hooks or other post-boot invocations, where the calls are\n * not guaranteed to work because Joist's reactivity graph has already been initialized.\n */\nexport function setBooted(): void {\n booted = true;\n}\n\nexport function setAfterMetadataLocked(): void {\n afterMetadataLocked = true;\n}\n\n/** The public API to configure an Entity's hooks & validation rules. */\nexport class ConfigApi<T extends Entity, C> {\n __data = new ConfigData<T, C>();\n\n /**\n * Maps a given `constraintName`, i.e. `authors_publisher_id_unique_index`, to a hard-coded-but-pretty validation errors.\n *\n * Note that the validationError must be hard-coded b/c we cannot tease out \"which entity\" caused a given\n * constraint failure from the SQL database. If you really need pretty-and-custom validation errors, you'll\n * need to check the constraint by hand ahead of time, before calling `em.flush`.\n */\n addConstraintMessage(constraintName: string, validationError: string) {\n this.ensurePreBoot(getCallerName(), \"addConstraintMessage\");\n constraintNameToValidationError[constraintName] = validationError;\n }\n\n /**\n * Maps a `RecursiveCycleError` on the given recursive collection field to a custom validation error.\n *\n * When a cycle is detected in a recursive collection (e.g. `parentsRecursive`), instead of\n * throwing a raw `RecursiveCycleError`, `em.flush` will convert it into a `ValidationErrors`\n * using the provided message function.\n *\n * The `messageFn` receives the entity that detected the cycle and the cycle path (array of\n * entities forming the cycle), and should return a validation error string.\n */\n addCycleRule(fieldName: string & keyof T, messageFn: (entity: T, cyclePath: Entity[]) => string) {\n this.ensurePreBoot(getCallerName(), \"addCycleRule\");\n this.__data.cycleMessages[fieldName] = messageFn;\n // Register a reactive rule that loads the recursive collection and catches cycle errors.\n // The rule uses the recursive collection's underlying relation as a reactive hint so it\n // triggers when the collection changes.\n const hint = fieldName as any;\n const fn = () => {\n // We don't actually need a try/catch/anything here, b/c if there is a cycle, it\n // will cause a CycleError during followReverseHint, and never even get to calling this fn.\n };\n this.__data.rules.push({ name: `addCycleRule(${getCallerName()})`, fn, hint });\n }\n\n /**\n * Adds a validation rule for this entity.\n *\n * If `hint` is passed, then the rule's lambda will be: 1) passed a view of the entity with only\n * the fields included in `hint` marked as accessible, and 2) the rule will be called reactively any\n * time any field in the `hint` changes.\n *\n * If lambdas want to access fields w/o having them marked for reactivity, the rule can either\n * include the field as readonly with a `:ro` suffix, i.e. `firstName:ro`, or the lambda can\n * access the `reacted.entity` property to get a full view of the entity's fields and methods.\n */\n addRule<H extends ReactiveHint<T>>(hint: H, rule: ValidationRule<Reacted<T, H>>): void;\n addRule(rule: ValidationRule<T>): void;\n addRule(ruleOrHint: ValidationRule<T> | any, maybeRule?: ValidationRule<any>): void {\n // Keep the name for easy debugging/tracing later\n const name = `addRule(${getCallerName()})`;\n this.ensurePreBoot(name, \"addRule\");\n pushValidationRule(this.__data.rules, name, ruleOrHint, maybeRule);\n }\n\n /**\n * Adds a \"commit rule\" that runs like a regular validation rule (see {@link addRule}), but *after*\n * the entity's `INSERT`/`UPDATE`/`DELETE` has been flushed to the database and *before* the\n * transaction `COMMIT`s, i.e. still within the transaction.\n *\n * The point of running this late is that any `em.find`s the rule makes will query the _changed_\n * state (the just-flushed rows), instead of the pre-flush state that regular `addRule` rules see.\n * This is useful for cross-row invariants that are easiest to express as a query, e.g. \"at most\n * one active `AuthorSchedule` per author\", where the rule wants to `em.find` the sibling rows\n * that were themselves just inserted/updated in this same flush.\n *\n * Like `addRule`, if a `hint` is passed the rule is reactive: it runs whenever any field in the\n * hint changes (walking back to the owning entity), and the lambda gets a `Reacted` view.\n */\n addCommitRule<H extends ReactiveHint<T>>(hint: H, rule: ValidationRule<Reacted<T, H>>): void;\n addCommitRule(rule: ValidationRule<T>): void;\n addCommitRule(ruleOrHint: ValidationRule<T> | any, maybeRule?: ValidationRule<any>): void {\n // Keep the name for easy debugging/tracing later\n const name = `addCommitRule(${getCallerName()})`;\n this.ensurePreBoot(name, \"addCommitRule\");\n pushValidationRule(this.__data.commitRules, name, ruleOrHint, maybeRule);\n }\n\n /** If both this entity, and `cstr` entities, are in the same `em.flush`, run us first. */\n runHooksBefore(cstr: EntityConstructor<any>): void {\n this.__data.runHooksBefore.push(cstr);\n }\n\n /** Deletes any entity/entities pointed to by `relation` when this entity is deleted. */\n cascadeDelete(relation: keyof RelationsIn<T> & LoadHint<T>): void {\n this.ensurePreBoot(getCallerName(), \"cascadeDelete\");\n this.__data.cascadeDeleteFields.push(relation);\n }\n\n touchOnChange(relation: keyof RelationsIn<T>): void {\n this.ensurePreBoot(getCallerName(), \"touchOnChange\");\n this.__data.touchOnChange.add(relation);\n }\n\n private addHook(hook: EntityHook, ruleOrHint: HookFn<T, C> | any, maybeFn?: HookFn<Loaded<T, any>, C>) {\n this.ensurePreBoot(getCallerName(), \"addHook\");\n if (typeof ruleOrHint === \"function\") {\n this.__data.hooks[hook].push(ruleOrHint);\n } else {\n const fn = async (entity: T, ctx: C) => {\n // TODO Use this for reactive beforeFlush\n const loaded = await entity.em.populate(entity, ruleOrHint);\n return maybeFn!(loaded, ctx);\n };\n // Squirrel our hint away where configureMetadata can find it\n (fn as any).hint = ruleOrHint;\n this.__data.hooks[hook].push(fn);\n }\n }\n\n afterMetadata(fn: AfterMetadataCallback<T>): void {\n if (afterMetadataLocked) {\n throw new Error(\n `config.afterMetadata on ${getCallerName()} must only be called on boot, before calling \\`configureMetadata\\` and not from other \\`afterMetadata\\` hooks.`,\n );\n }\n this.__data.afterMetadataCallbacks.push(fn);\n }\n\n beforeDelete<H extends LoadHint<T>>(populate: H, fn: HookFn<Loaded<T, H>, C>): void;\n beforeDelete(fn: HookFn<T, C>): void;\n beforeDelete(ruleOrHint: HookFn<T, C> | any, maybeFn?: HookFn<Loaded<T, any>, C>): void {\n this.addHook(\"beforeDelete\", ruleOrHint, maybeFn);\n }\n\n beforeFlush<H extends LoadHint<T>>(populate: H, fn: HookFn<Loaded<T, H>, C>): void;\n beforeFlush(fn: HookFn<T, C>): void;\n beforeFlush(ruleOrHint: HookFn<T, C> | any, maybeFn?: HookFn<Loaded<T, any>, C>): void {\n this.addHook(\"beforeFlush\", ruleOrHint, maybeFn);\n }\n\n // beforeCreate still needs to take a hint because even though the entity itself is New<T>, we might want to load\n // a nested relation that isn't loaded yet\n beforeCreate<H extends LoadHint<T>>(populate: H, fn: HookFn<Loaded<T, H>, C>): void;\n beforeCreate(fn: HookFn<T, C>): void;\n beforeCreate(ruleOrHint: HookFn<T, C> | any, maybeFn?: HookFn<Loaded<T, any>, C>): void {\n this.addHook(\"beforeCreate\", ruleOrHint, maybeFn);\n }\n\n beforeUpdate<H extends LoadHint<T>>(populate: H, fn: HookFn<Loaded<T, H>, C>): void;\n beforeUpdate(fn: HookFn<T, C>): void;\n beforeUpdate(ruleOrHint: HookFn<T, C> | any, maybeFn?: HookFn<Loaded<T, any>, C>): void {\n this.addHook(\"beforeUpdate\", ruleOrHint, maybeFn);\n }\n\n afterValidation<H extends LoadHint<T>>(populate: H, fn: HookFn<Loaded<T, H>, C>): void;\n afterValidation(fn: HookFn<T, C>): void;\n afterValidation(ruleOrHint: HookFn<T, C> | any, maybeFn?: HookFn<Loaded<T, any>, C>): void {\n this.addHook(\"afterValidation\", ruleOrHint, maybeFn);\n }\n\n beforeCommit(fn: HookFn<T, C>): void {\n this.addHook(\"beforeCommit\", fn);\n }\n\n afterCommit(fn: HookFn<T, C>): void {\n this.addHook(\"afterCommit\", fn);\n }\n\n /**\n * Adds a reaction that runs during flush whenever fields in the `hint` change.\n *\n * Reactions are somewhere in between hooks and reactive fields/references:\n * 1. Can make arbitrary changes to any entity like a hook\n * 2. Only run when the provided hint has changes, not on every flush, like an RF/RR\n * 3. Run when the entity itself has no changes, like an RF/RF\n * 4. Can run multiple times per flush, like an RF/RF. Be careful to avoid creating\n * circular dependencies in the hint and to make the function idempotent.\n *\n * Names default to the registration's source location. Pass unique names when registering multiple\n * reactions from a shared helper or loop; duplicate names on the same config are rejected.\n *\n * @param hint The fields to watch for changes and load before running the reaction\n * @param fn The reaction function to run\n */\n addReaction<H extends ReactiveHint<T>>(hint: H, fn: HookFn<Loaded<T, H>, C>): void;\n /**\n * Adds a named reaction that runs during flush whenever fields in the `hint` change.\n *\n * Reactions are somewhere in between hooks and reactive fields/references:\n * 1. Can make arbitrary changes to any entity like a hook\n * 2. Only run when `hint` has changes, not on every flush, like an RF/RR\n * 3. Can run when the entity itself has no changes, like an RF/RF\n * 4. Can run multiple times per flush, like an RF/RF. Be careful to avoid creating\n * circular dependencies in the hint and to make the function idempotent.\n *\n * @param name A name to identify this reaction for debugging\n * @param hint The fields to watch for changes and load before running the reaction\n * @param fn The reaction function to run\n */\n addReaction<H extends ReactiveHint<T>>(name: string, hint: H, fn: HookFn<Loaded<T, H>, C>): void;\n /**\n * Adds a reaction that runs during flush whenever fields in the `hint` change.\n *\n * Reactions are somewhere in between hooks and reactive fields/references:\n * 1. Can make arbitrary changes to any entity like a hook\n * 2. Only run when `hint` has changes, not on every flush, like an RF/RR\n * 3. Can run when the entity itself has no changes, like an RF/RF\n * 4. Can run multiple times per flush, like an RF/RF. Be careful to avoid creating\n * circular dependencies in the hint and to make the function idempotent.\n *\n * @param opts Options object containing:\n * - runOnce - If true, the reaction will only run once per flush, not every time the hint changes. Optional.\n * default: false.\n * - name - A name to identify this reaction for debugging\n * @param hint The fields to watch for changes and load before running the reaction\n * @param fn The reaction function to run\n */\n addReaction<H extends ReactiveHint<T>>(opts: AddReactionOpts, hint: H, fn: HookFn<Loaded<T, H>, C>): void;\n addReaction<H extends ReactiveHint<T>>(\n nameOrOptsOrHint: string | AddReactionOpts | H,\n hintOrFn: H | HookFn<Loaded<T, H>, C>,\n maybeFn?: HookFn<Loaded<T, H>, C>,\n ): void {\n // Keep the name so we can uniquely identify this reaction later and also aid debugging/tracing\n const fn = maybeFn ?? (hintOrFn as HookFn<Loaded<T, H>, C>);\n const hint = (maybeFn ? hintOrFn : nameOrOptsOrHint) as H;\n const opts = maybeFn\n ? typeof nameOrOptsOrHint === \"string\"\n ? { name: nameOrOptsOrHint }\n : (nameOrOptsOrHint as AddReactionOpts)\n : {};\n const { name = getCallerName(), runOnce = false } = opts;\n this.ensurePreBoot(name, \"addReaction\");\n this.ensureUniqueReactionName(name, \"addReaction\");\n // Cache load hints per-meta because CTI subtypes may resolve `hint` to different\n // load hints (e.g. an AsyncProperty overridden in the subtype with subtype-only relations).\n const loadHints = new Map<EntityMetadata, LoadHint<T>>();\n const wrappedFn = (entity: T, ctx: C) => {\n const meta = getMetadata(entity);\n let loadHint = loadHints.get(meta);\n if (loadHint === undefined) {\n loadHint = convertToLoadHint<T>(meta, hint);\n loadHints.set(meta, loadHint);\n }\n if (Object.keys(loadHint).length > 0) {\n return entity.em.populate(entity, loadHint).then((loaded) => fn(loaded as Loaded<T, H>, ctx));\n }\n return fn(entity as Loaded<T, H>, ctx);\n };\n this.__data.reactions.push({ name, fn: wrappedFn, hint, runOnce });\n }\n\n /**\n * Declares which state transitions of the enum `fieldName` are allowed, i.e. `{ Draft: [\"Open\"], Open: [\"Closed\"] }`.\n *\n * Keys and values are the enum's accessors as strings, i.e. `\"Draft\"` for `AuthorStatus.Draft`.\n *\n * A state that is missing from the table, or maps to `[]`, is treated as a terminal state & cannot be\n * changed. Creating an entity is not a transition, so a new entity may start in any state.\n *\n * The table is checked by the field's setter, so a disallowed transition throws a `ValidationErrors`\n * immediately, instead of failing the next `em.flush`.\n */\n transitions<K extends Settable<T>>(fieldName: K, table: TransitionTable<TransitionStates<T, K>>): void {\n const name = `transitions(${getCallerName()})`;\n this.ensurePreBoot(name, \"transitions\");\n const config = this.fieldTransitions(fieldName);\n // Subtypes add their own tables on their own configs, so a 2nd table on this config is a mistake\n if (config.table) fail(`config.transitions was already called for ${fieldName}, use one table per field`);\n // Accessors are converted to codes after boot, see `buildFieldTransitions`\n config.table = table;\n }\n\n /**\n * Checks each matching transition before its callbacks run, and rejects it if the guard returns an error.\n *\n * Use this for \"a transition is allowed only when ...\" checks that depend on other data, while\n * `transitions` declares the transitions that are possible at all. The `hint` is a load hint, like\n * `beforeFlush`'s, so it's loaded before `rule` runs, but only `fieldName` itself triggers the guard.\n *\n * Guards run with reactions, for every matching transition, even if the\n * field has moved on since. The entity is in its current state, so `rule` also gets the `transition`\n * it is checking. Guards never run on creation and are not rechecked during final validation.\n */\n guardTransition<K extends Settable<T>, H extends LoadHint<T>>(\n fieldName: K,\n match: GuardTransitionMatch<TransitionStates<T, K>>,\n hint: H,\n rule: TransitionGuardFn<Loaded<T, H>, TransitionType<T, K>>,\n ): void;\n guardTransition<K extends Settable<T>>(\n fieldName: K,\n match: GuardTransitionMatch<TransitionStates<T, K>>,\n rule: TransitionGuardFn<T, TransitionType<T, K>>,\n ): void;\n guardTransition(fieldName: string, match: GuardTransitionMatch<any>, hintOrRule: any, maybeRule?: any): void {\n const name = `guardTransition(${getCallerName()})`;\n this.ensurePreBoot(name, \"guardTransition\");\n const rule: TransitionGuardFn<T, any> = maybeRule ?? hintOrRule;\n const hint: LoadHint<T> | undefined = maybeRule ? hintOrRule : undefined;\n // The dispatcher evaluates matching guards once before invoking any callbacks for the transition.\n this.fieldTransitions(fieldName).guards.push({\n match,\n run(entity, step) {\n const transition = toTransition(step);\n return hint === undefined\n ? rule(entity, transition)\n : entity.em.populate(entity, hint).then((loaded) => rule(loaded, transition));\n },\n });\n }\n\n /**\n * Runs `fn` for each state transition of `fieldName` that matches `match`.\n *\n * This runs alongside reactions (see `addReaction`), but only state changes queue callbacks.\n * The `hint` is a load hint, like `beforeFlush`'s, so it is loaded but not reacted to.\n *\n * Callbacks run with reactions, once for every matching transition, in order,\n * even if the field has moved on since. The entity is in its current state, so `fn` also gets the\n * `transition` it is handling. Transitions that a `guardTransition` rejects don't fire.\n *\n * Creating an entity with a matching `to` state fires too, unless `match.from` is set or\n * `match.onCreate` is `false`. Set `match.phase: \"commit\"` to run in `beforeCommit` instead, i.e.\n * for enqueueing jobs.\n *\n * Callbacks that read a new entity's `id` should use `match.phase: \"commit\"`. Other callbacks may run\n * before ids are assigned, and Joist does not rerun them on a `NoIdError` because their side effects\n * could repeat.\n *\n * Pass a unique name as the first argument when registering multiple callbacks from a shared\n * helper or loop. Duplicate names on the same config are rejected when registered.\n */\n onTransition<K extends Settable<T>, H extends LoadHint<T>>(\n fieldName: K,\n match: OnTransitionMatch<TransitionStates<T, K>>,\n hint: H,\n fn: TransitionFn<Loaded<T, H>, C, TransitionType<T, K>>,\n ): void;\n onTransition<K extends Settable<T>>(\n fieldName: K,\n match: OnTransitionMatch<TransitionStates<T, K>>,\n fn: TransitionFn<T, C, TransitionType<T, K>>,\n ): void;\n onTransition<K extends Settable<T>, H extends LoadHint<T>>(\n name: string,\n fieldName: K,\n match: OnTransitionMatch<TransitionStates<T, K>>,\n hint: H,\n fn: TransitionFn<Loaded<T, H>, C, TransitionType<T, K>>,\n ): void;\n onTransition<K extends Settable<T>>(\n name: string,\n fieldName: K,\n match: OnTransitionMatch<TransitionStates<T, K>>,\n fn: TransitionFn<T, C, TransitionType<T, K>>,\n ): void;\n onTransition(\n nameOrFieldName: string,\n fieldNameOrMatch: string | OnTransitionMatch<any>,\n matchOrHintOrFn: any,\n hintOrFn?: any,\n maybeFn?: any,\n ): void {\n const named = typeof fieldNameOrMatch === \"string\";\n const name = named ? nameOrFieldName : `onTransition(${getCallerName()})`;\n this.ensurePreBoot(name, \"onTransition\");\n this.ensureUniqueReactionName(name, \"onTransition\");\n\n // Resolve the overloads\n const fieldName = named ? fieldNameOrMatch : nameOrFieldName;\n const match: OnTransitionMatch<any> = named ? matchOrHintOrFn : fieldNameOrMatch;\n const hintOrCallback = named ? hintOrFn : matchOrHintOrFn;\n const callback = named ? maybeFn : hintOrFn;\n const fn: TransitionFn<T, C, any> = callback ?? hintOrCallback;\n const hint: LoadHint<T> | undefined = callback ? hintOrCallback : undefined;\n\n // Transition queues trigger callbacks; hinted data is only loaded, not watched for changes.\n this.fieldTransitions(fieldName).callbacks.push({\n name,\n match,\n run(entity, ctx, step) {\n const transition = toTransition(step);\n return hint === undefined\n ? fn(entity, ctx, transition)\n : entity.em.populate(entity, hint).then((loaded) => fn(loaded, ctx, transition));\n },\n });\n }\n\n /** Adds a synchronous default for `fieldName` to a hard-coded `value`. */\n setDefault<K extends Settable<T>, F = FieldsOf<T>[K]>(\n fieldName: K,\n // Allow returning undefined to mean \"no default\"\n value: F extends EntityField ? F[\"type\"] : never,\n ): void;\n /** Adds a synchronous default for `fieldName` to the result of simple sync lambda. */\n setDefault<K extends Settable<T>, F = FieldsOf<T>[K]>(\n fieldName: K,\n // ...this doesn't technically declare what other fields of `entity` we depend on,\n // which ideally we want to drive \"which default to set first?\" precedence decisions.\n fn: (entity: T) => F extends EntityField ? F[\"type\"] | undefined : never,\n ): void;\n /** Adds an asynchronous default for `fieldName` to the result of a hinted lambda. */\n setDefault<K extends Settable<T>, const H extends ReactiveHint<T>, F = FieldsOf<T>[K]>(\n fieldName: K,\n // We use a ReactiveHint so that we get field-level dependencies that means someday\n // we could drive \"which default to set first?\" precedence decisions.\n hint: H,\n fn: (\n entity: Reacted<T, H>,\n ctx: C,\n ) => F extends { kind: \"m2o\"; type: infer T extends Entity }\n ? MaybePromise<T | Reacted<T, {}> | undefined>\n : F extends EntityField\n ? MaybePromise<F[\"type\"] | undefined>\n : never,\n ): void;\n setDefault<K extends keyof SettableFields<FieldsOf<T>> & string>(fieldName: K, hintOrFnOrValue: any, fn?: any): void {\n this.ensurePreBoot(getCallerName(), \"setDefault\");\n if (fn) {\n // If we're called once by the codegen, and again by the user, override the syncDefault\n delete this.__data.syncDefaults[fieldName];\n this.__data.asyncDefaults[fieldName] = new AsyncDefault(fieldName, hintOrFnOrValue, fn);\n } else {\n this.__data.syncDefaults[fieldName] = hintOrFnOrValue;\n }\n }\n\n /**\n * A noop method that exists solely to keep the `config.placeholder()` line in the initial entity file,\n * until the user is ready to use it. */\n placeholder(): void {}\n\n /** Returns `fieldName`'s transition config, creating it on first use. */\n private fieldTransitions(fieldName: string): FieldTransitionsConfig<T, C> {\n return (this.__data.transitions[fieldName] ??= { guards: [], callbacks: [] });\n }\n\n /** Requires unique names across ordinary reactions and transition callbacks. */\n private ensureUniqueReactionName(name: string, op: string): void {\n if (this.__data.reactionNames.has(name)) {\n throw new Error(\n `Duplicate reaction name \"${name}\" in config.${op}. Pass a unique name when registering reactions from a shared helper or loop.`,\n );\n }\n this.__data.reactionNames.add(name);\n }\n\n private ensurePreBoot(name: string, op: string): void {\n if (booted) {\n // Detect if this is NextJS and we're in a hot-reload situation\n if (isRunningInNextJs()) {\n // Reset our bag of config data to collect only the new rules/hooks\n this.__data = new ConfigData();\n resetBootFlag();\n } else {\n throw new Error(\n `config.${op} call on ${name} must only be called on boot, before calling \\`configureMetadata\\`.`,\n );\n }\n }\n }\n}\n\nfunction isRunningInNextJs(): boolean {\n return \"__NEXT_HTTP_AGENT\" in globalThis || \"__NEXT_HTTPS_AGENT\" in globalThis;\n}\n\n/**\n * Allows projects to manually reset the internal `booted` flag.\n *\n * This is only necessary if they're using hot-reloading and reloading their entity files\n * without restarting the server.\n *\n * Generally most tools like tsx or ts-node-dev reload the whole process, so don't need\n * to call this, but if Joist is used in a framework that does actual-hot-reloading, this\n * it will be necessary.\n */\nexport function resetBootFlag(): void {\n booted = false;\n afterMetadataLocked = false;\n resetConstructorMap();\n}\n\n/**\n * Stores a path back to a reactive rule.\n *\n * I.e. if `Book` has a `ruleFn` that reacts to `Author.title`, then `Author`'s config will have\n * a `ReactiveRule` with fields `[\"title\"]`, path `books`, and rule `ruleFn`.\n */\nexport interface ReactiveRule {\n /** The source we're reacting to, specifically which base/subtype cstr. */\n source: MaybeAbstractEntityConstructor<any>;\n /** The fields on this source entity that would trigger the downstream rule's eval. */\n fields: string[];\n /** The constructor of downstream entity that owns the reactive rule. */\n cstr: MaybeAbstractEntityConstructor<any>;\n /** The name (source location) of the downstream reactive rule. */\n name: string;\n /** The path from this source entity to the downstream entity that needs evaled. */\n path: string[];\n /** The downstream validation rule to eval. */\n fn: ValidationRule<any>;\n}\n\n/**\n * Stores a path back to a reactive derived field.\n *\n * I.e. if `Book.displayName` is an `asyncField` that reacts to `Author.title`, then `Author`'s config will have\n * a `ReactiveFields` with fields `[\"title\"]`, path `books`, and name `displayName`.\n */\nexport interface ReactiveField {\n kind: \"populate\" | \"query\";\n /** The fields on this source entity that would trigger the downstream field's recalc. */\n fields: string[];\n /** Read-only/immutable fields that are used in the derived field. */\n isReadOnly: boolean;\n /** The constructor of downstream entity that owns the derived field. */\n cstr: MaybeAbstractEntityConstructor<any>;\n /** The path from this source entity to the downstream entity that needs recalced. */\n path: string[];\n /** The name of the reactive field in the downstream entity to recalc. */\n name: string;\n runOnce: false;\n}\n\nexport interface Reaction {\n kind: \"reaction\";\n /** The source we're reacting to, specifically which base/subtype cstr. */\n source: MaybeAbstractEntityConstructor<any>;\n /** The fields on this source entity that would trigger the downstream hook's eval. */\n fields: string[];\n /** Read-only/immutable fields that are used in the function. */\n isReadOnly: boolean;\n /** The constructor of downstream entity that owns the reaction. */\n cstr: MaybeAbstractEntityConstructor<any>;\n /** The name (source location) of the downstream reaction. */\n name: string;\n /** The path from this source entity to the downstream entity for this reaction. */\n path: string[];\n /** The downstream reaction function. */\n fn: HookFn<any, any>;\n /** If true, the reaction should only run once per flush, not every time the hint changes. */\n runOnce: boolean;\n}\n\nexport type Reactable = ReactiveField | Reaction;\n\ninterface ReactionInternal<T extends Entity, H extends ReactiveHint<T>, C> {\n name: string;\n fn: HookFn<T, C>;\n hint: H;\n runOnce: boolean;\n}\n\ntype AfterMetadataCallback<T extends Entity> = (meta: EntityMetadata<T>) => void;\n\n/** The internal state of an entity's configuration data, i.e. validation rules/hooks. */\nexport class ConfigData<T extends Entity, C> {\n afterMetadataCallbacks: AfterMetadataCallback<T>[] = [];\n runHooksBefore: EntityConstructor<any>[] = [];\n /** The validation rules for this entity type. */\n rules: ValidationRuleInternal<T>[] = [];\n /** The \"commit rules\" for this entity type, i.e. validation rules that run post-flush/pre-commit. */\n commitRules: ValidationRuleInternal<T>[] = [];\n /** The reactions for this entity type. */\n reactions: ReactionInternal<T, any, C>[] = [];\n /** Names shared by addReaction and onTransition, including commit-phase callbacks. */\n reactionNames: Set<string> = new Set();\n /**\n * Field name -> its `transitions`, `guardTransition`, and `onTransition` config, with accessors not yet converted.\n *\n * The keys are also the fields whose factories accept `withX` opts.\n */\n transitions: Record<string, FieldTransitionsConfig<T, C>> = {};\n /** The hooks for this entity type. */\n hooks: Record<EntityHook, HookFn<T, C>[]> = {\n beforeDelete: [],\n beforeFlush: [],\n beforeCreate: [],\n beforeUpdate: [],\n afterValidation: [],\n beforeCommit: [],\n afterCommit: [],\n };\n /** Synchronous defaults for this entity type, invoked on `em.create`. */\n syncDefaults: Record<string, ((entity: T) => void) | unknown> = {};\n /** Asynchronous defaults for this entity type, invoked on `em.flush`. */\n asyncDefaults: Record<string, AsyncDefault<T>> = {};\n\n // An array of the reactive rules that depend on this entity\n reactiveRules: ReactiveRule[] = [];\n // An array of the reactive *commit* rules (post-flush/pre-commit) that depend on this entity\n reactiveCommitRules: ReactiveRule[] = [];\n // An array of the reactive fields and reactions that depend on this entity\n reactables: Reactable[] = [];\n cascadeDeleteFields: Array<keyof RelationsIn<T>> = [];\n touchOnChange: Set<keyof RelationsIn<T>> = new Set();\n // Constantly converting reactive hints to load hints is expense, so cache them here\n cachedReactiveLoadHints: Record<string, any> = {};\n /** Maps recursive collection fieldNames to custom cycle error message functions. */\n cycleMessages: Record<string, (entity: T, cyclePath: Entity[]) => string> = {};\n}\n\nexport function getCallerName(extraFrames: number = 0): string {\n const err = getStack();\n // E.g. at Object.<anonymous> (/home/stephen/homebound/graphql-service/src/entities/Activity.ts:86:8)\n // (Make sure to drop lines that don't start with 'at' b/c the stack format can differ\n // slightly i.e. if running via tsx/using a node loader (probably?)\n const line = err.stack!.split(\"\\n\").filter((line) => line.includes(\" at \"))[3 + extraFrames];\n const parts = line.split(\"/\");\n // Get the last part, which will be the file name, i.e. Activity.ts:86:8\n return parts[parts.length - 1].replace(/:\\d+\\)?$/, \"\");\n}\n\nexport function getFuzzyCallerName(): string {\n const err = getStack();\n const lines = err\n .stack!.split(\"\\n\")\n // E.g. at Object.<anonymous> (/home/stephen/homebound/graphql-service/src/entities/Activity.ts:86:8)\n .filter((line) => line.includes(\" at \"));\n const line = findUserCodeLine(lines);\n return getFilePath(line);\n}\n\n/**\n * Given a callstack line return the file name.\n *\n * I.e. `at Object.<anonymous> (/home/stephen/homebound/graphql-service/src/entities/Activity.ts:86:8)`\n */\nexport function getFilePath(line: string): string {\n const parts = line.split(\"/\");\n return parts[parts.length - 1].replace(/:\\d+\\)?$/, \"\"); // Drop the `:8)`at the end\n}\n\n/** Given a callstack, uses heuristics to find the first line that looks like user code. */\nexport function findUserCodeLine(lines: string[]): string {\n return (\n lines.find((line) => {\n // When running Joist's own integration tests, if we ignore `/joist-orm/`, we'll end up ignoring\n // everything because `joist-orm` is the name of the repository/working copy itself.\n const withinWorkingCopyJoist = line.includes(\"/packages/orm/\") || line.includes(\"/packages/core\");\n // But once we're not in a working copy, assume any `/joist-orm/` in the path === internal orm stack frames\n const withinProductionJoist =\n !withinWorkingCopyJoist && (line.includes(\"/joist-orm/src/\") || line.includes(\"/joist-core/src\"));\n const nodeInternals = line.includes(\"node:internal/\") || line.includes(\"Promise.all\");\n const isUserCode = !withinWorkingCopyJoist && !withinProductionJoist && !nodeInternals;\n // const isRecalc = line.includes(\".recalcPending\");\n const isDefault = line.includes(\"/defaults.ts\");\n // Batched calls like findOrCreate won't have a stack trace back to the true caller, so just stop there\n const isDataloader = line.includes(\"/dataloaders/\");\n // If this is the `newTestInstance` call\n // What about:\n // recalcSynchronousDerivedFields\n return (\n (isDefault || isDataloader || isUserCode) &&\n !line.includes(\"Codegen.ts\") &&\n // I wanted to exclude this, but it was actually our utils/entities.ts maybeSetDefault helper method\n // !line.includes(\"entities.ts\") &&\n // Ignore loops in joist code like setOpts\n !line.includes(\"at Array\") &&\n // Ignore the Author.ts constructor calling setOpts\n !line.includes(\"at new \")\n );\n }) ?? fail(\"Could not find caller name\")\n );\n}\n\nconst getStack: () => { stack?: string } = \"captureStackTrace\" in Error ? getStackFromCapture : getStackFromObject;\n\nfunction getStackFromCapture(): { stack?: string } {\n const obj = {};\n Error.captureStackTrace(obj);\n return obj as any;\n}\n\nfunction getStackFromObject(): { stack?: string } {\n try {\n throw Error(\"\");\n } catch (err) {\n return err as Error;\n }\n}\n\n/** Pushes a validation rule (either the raw or hinted/reactive form) onto `rules`, shared by `addRule`/`addCommitRule`. */\nfunction pushValidationRule<T extends Entity>(\n rules: ValidationRuleInternal<T>[],\n name: string,\n ruleOrHint: ValidationRule<T> | any,\n maybeRule: ValidationRule<any> | undefined,\n): void {\n if (typeof ruleOrHint === \"function\") {\n rules.push({ name, fn: ruleOrHint, hint: undefined });\n } else {\n const hint = ruleOrHint;\n // Cache load hints per-meta because CTI subtypes may resolve `hint` to different\n // load hints (e.g. an AsyncProperty overridden in the subtype with subtype-only relations).\n const loadHints = new Map<EntityMetadata, LoadHint<T>>();\n const fn = (entity: T) => {\n const meta = getMetadata(entity);\n let loadHint = loadHints.get(meta);\n if (loadHint === undefined) {\n loadHint = convertToLoadHint<T>(meta, hint);\n loadHints.set(meta, loadHint);\n }\n if (Object.keys(loadHint).length > 0) {\n return entity.em.populate(entity, loadHint).then(maybeRule!);\n }\n return maybeRule!(entity);\n };\n rules.push({ name, fn, hint });\n }\n}\n"],"mappings":";;;;;;;;;;AAoEA,MAAa,kCAA0D,CAAC;AAIxE,IAAI,SAAS;AACb,IAAI,sBAAsB;;;;;;;;AAS1B,SAAgB,YAAkB;CAChC,SAAS;AACX;AAEA,SAAgB,yBAA+B;CAC7C,sBAAsB;AACxB;;AAGA,IAAa,YAAb,MAA4C;CAC1C,SAAS,IAAI,WAAiB;;;;;;;;CAS9B,qBAAqB,gBAAwB,iBAAyB;EACpE,KAAK,cAAc,cAAc,GAAG,sBAAsB;EAC1D,gCAAgC,kBAAkB;CACpD;;;;;;;;;;;CAYA,aAAa,WAA6B,WAAuD;EAC/F,KAAK,cAAc,cAAc,GAAG,cAAc;EAClD,KAAK,OAAO,cAAc,aAAa;EAIvC,MAAM,OAAO;EACb,MAAM,WAAW,CAGjB;EACA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,KAAK,SAAS,SAAS;CAE5B,CAAC,KAAK,KAAK,4BAA4B;AAE3C;AAEA,MAAM,WAAqC,uBAAuB,QAAQ,sBAAsB;AAEhG,SAAS,sBAA0C;CACjD,MAAM,MAAM,CAAC;CACb,MAAM,kBAAkB,GAAG;CAC3B,OAAO;AACT;AAEA,SAAS,qBAAyC;CAChD,IAAI;EACF,MAAM,MAAM,EAAE;CAChB,SAAS,KAAK;EACZ,OAAO;CACT;AACF;;AAGA,SAAS,mBACP,OACA,MACA,YACA,WACM;CACN,IAAI,OAAO,eAAe,YACxB,MAAM,KAAK;EAAE;EAAM,IAAI;EAAY,MAAM,KAAA;CAAU,CAAC;MAC/C;EACL,MAAM,OAAO;EAGb,MAAM,4BAAY,IAAI,IAAiC;EACvD,MAAM,MAAM,WAAc;GACxB,MAAM,OAAO,YAAY,MAAM;GAC/B,IAAI,WAAW,UAAU,IAAI,IAAI;GACjC,IAAI,aAAa,KAAA,GAAW;IAC1B,WAAW,kBAAqB,MAAM,IAAI;IAC1C,UAAU,IAAI,MAAM,QAAQ;GAC9B;GACA,IAAI,OAAO,KAAK,QAAQ,CAAC,CAAC,SAAS,GACjC,OAAO,OAAO,GAAG,SAAS,QAAQ,QAAQ,CAAC,CAAC,KAAK,SAAU;GAE7D,OAAO,UAAW,MAAM;EAC1B;EACA,MAAM,KAAK;GAAE;GAAM;GAAI;EAAK,CAAC;CAC/B;AACF"}
|
package/build/configure.cjs
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_reactivity_reactiveHints = require("./reactivity/reactiveHints.cjs");
|
|
3
2
|
const require_keys = require("./keys.cjs");
|
|
4
3
|
require("./relations/ReactiveField.cjs");
|
|
5
4
|
const require_relations_AsyncReactiveField = require("./relations/AsyncReactiveField.cjs");
|
|
6
5
|
require("./relations/index.cjs");
|
|
7
6
|
const require_utils = require("./utils.cjs");
|
|
8
7
|
const require_getProperties = require("./getProperties.cjs");
|
|
8
|
+
const require_reactivity_reactiveHints = require("./reactivity/reactiveHints.cjs");
|
|
9
9
|
const require_rules = require("./rules.cjs");
|
|
10
|
+
const require_transitions = require("./transitions.cjs");
|
|
11
|
+
const require_config = require("./config.cjs");
|
|
10
12
|
const require_runtimeConfig = require("./runtimeConfig.cjs");
|
|
11
13
|
const require_serde_fieldSerde = require("./serde/fieldSerde.cjs");
|
|
12
|
-
const require_config = require("./config.cjs");
|
|
13
14
|
const require_EntityMetadata = require("./EntityMetadata.cjs");
|
|
14
15
|
const require_defaults = require("./defaults.cjs");
|
|
15
16
|
require("./EntityManager.cjs");
|
|
@@ -69,6 +70,9 @@ function installMetadataGetters(metas) {
|
|
|
69
70
|
/** Installs lazy getters for reactivity caches after reactivity has been reverse-indexed. */
|
|
70
71
|
function installReactiveMetadataGetters(metas) {
|
|
71
72
|
for (const meta of metas) {
|
|
73
|
+
require_utils.defineLazyGetter(meta, "transitions", function buildTransitions() {
|
|
74
|
+
return require_transitions.buildFieldTransitions(meta);
|
|
75
|
+
});
|
|
72
76
|
require_utils.defineLazyGetter(meta, "reactables", function buildReactables() {
|
|
73
77
|
return require_EntityMetadata.getBaseAndSelfMetas(meta).flatMap((m) => m.config.__data.reactables).filter((r) => !r.isReadOnly);
|
|
74
78
|
});
|