joist-core 2.4.0-next.24 → 2.4.0-next.26
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/config.cjs +14 -13
- package/build/config.cjs.map +1 -1
- package/build/config.d.cts +14 -13
- package/build/config.d.cts.map +1 -1
- package/build/config.d.mts +14 -13
- package/build/config.d.mts.map +1 -1
- package/build/config.js +14 -13
- package/build/config.js.map +1 -1
- package/build/fields.cjs.map +1 -1
- package/build/fields.js.map +1 -1
- package/build/index.cjs.map +1 -1
- package/build/index.js.map +1 -1
- package/build/newTestInstance.cjs.map +1 -1
- package/build/newTestInstance.js.map +1 -1
- package/build/transitions.cjs.map +1 -1
- package/build/transitions.d.cts +6 -6
- package/build/transitions.d.mts +6 -6
- package/build/transitions.js.map +1 -1
- package/package.json +2 -2
package/build/config.cjs
CHANGED
|
@@ -154,16 +154,16 @@ var ConfigApi = class {
|
|
|
154
154
|
* The table is checked by the field's setter, so a disallowed transition throws a `ValidationErrors`
|
|
155
155
|
* immediately, instead of failing the next `em.flush`.
|
|
156
156
|
*/
|
|
157
|
-
|
|
158
|
-
const name = `
|
|
159
|
-
this.ensurePreBoot(name, "
|
|
157
|
+
setTransitions(fieldName, table) {
|
|
158
|
+
const name = `setTransitions(${getCallerName()})`;
|
|
159
|
+
this.ensurePreBoot(name, "setTransitions");
|
|
160
160
|
const config = this.fieldTransitions(fieldName);
|
|
161
|
-
if (config.table) require_utils.fail(`config.
|
|
161
|
+
if (config.table) require_utils.fail(`config.setTransitions was already called for ${fieldName}, use one table per field`);
|
|
162
162
|
config.table = table;
|
|
163
163
|
}
|
|
164
|
-
|
|
165
|
-
const name = `
|
|
166
|
-
this.ensurePreBoot(name, "
|
|
164
|
+
addTransitionRule(fieldName, match, hintOrRule, maybeRule) {
|
|
165
|
+
const name = `addTransitionRule(${getCallerName()})`;
|
|
166
|
+
this.ensurePreBoot(name, "addTransitionRule");
|
|
167
167
|
const rule = maybeRule ?? hintOrRule;
|
|
168
168
|
const hint = maybeRule ? hintOrRule : void 0;
|
|
169
169
|
this.fieldTransitions(fieldName).guards.push({
|
|
@@ -174,11 +174,11 @@ var ConfigApi = class {
|
|
|
174
174
|
}
|
|
175
175
|
});
|
|
176
176
|
}
|
|
177
|
-
|
|
177
|
+
addTransitionReaction(nameOrFieldName, fieldNameOrMatch, matchOrHintOrFn, hintOrFn, maybeFn) {
|
|
178
178
|
const named = typeof fieldNameOrMatch === "string";
|
|
179
|
-
const name = named ? nameOrFieldName : `
|
|
180
|
-
this.ensurePreBoot(name, "
|
|
181
|
-
this.ensureUniqueReactionName(name, "
|
|
179
|
+
const name = named ? nameOrFieldName : `addTransitionReaction(${getCallerName()})`;
|
|
180
|
+
this.ensurePreBoot(name, "addTransitionReaction");
|
|
181
|
+
this.ensureUniqueReactionName(name, "addTransitionReaction");
|
|
182
182
|
const fieldName = named ? fieldNameOrMatch : nameOrFieldName;
|
|
183
183
|
const match = named ? matchOrHintOrFn : fieldNameOrMatch;
|
|
184
184
|
const hintOrCallback = named ? hintOrFn : matchOrHintOrFn;
|
|
@@ -254,10 +254,11 @@ var ConfigData = class {
|
|
|
254
254
|
commitRules = [];
|
|
255
255
|
/** The reactions for this entity type. */
|
|
256
256
|
reactions = [];
|
|
257
|
-
/** Names shared by addReaction and
|
|
257
|
+
/** Names shared by addReaction and addTransitionReaction, including commit-phase callbacks. */
|
|
258
258
|
reactionNames = /* @__PURE__ */ new Set();
|
|
259
259
|
/**
|
|
260
|
-
* Field name -> its `
|
|
260
|
+
* Field name -> its `setTransitions`, `addTransitionRule`, and `addTransitionReaction` config, with
|
|
261
|
+
* accessors not yet converted.
|
|
261
262
|
*
|
|
262
263
|
* The keys are also the fields whose factories accept `withX` opts.
|
|
263
264
|
*/
|
package/build/config.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.cjs","names":["getMetadata","convertToLoadHint","toTransition","AsyncDefault","fail"],"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;;;;;;;;CA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"version":3,"file":"config.cjs","names":["getMetadata","convertToLoadHint","toTransition","AsyncDefault","fail"],"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/** An `addTransitionRule` 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 `addTransitionReaction` 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 setTransitions<K extends Settable<T>>(fieldName: K, table: TransitionTable<TransitionStates<T, K>>): void {\n const name = `setTransitions(${getCallerName()})`;\n this.ensurePreBoot(name, \"setTransitions\");\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.setTransitions 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 * `setTransitions` 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 addTransitionRule<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 addTransitionRule<K extends Settable<T>>(\n fieldName: K,\n match: GuardTransitionMatch<TransitionStates<T, K>>,\n rule: TransitionGuardFn<T, TransitionType<T, K>>,\n ): void;\n addTransitionRule(fieldName: string, match: GuardTransitionMatch<any>, hintOrRule: any, maybeRule?: any): void {\n const name = `addTransitionRule(${getCallerName()})`;\n this.ensurePreBoot(name, \"addTransitionRule\");\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 an `addTransitionRule` 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 addTransitionReaction<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 addTransitionReaction<K extends Settable<T>>(\n fieldName: K,\n match: OnTransitionMatch<TransitionStates<T, K>>,\n fn: TransitionFn<T, C, TransitionType<T, K>>,\n ): void;\n addTransitionReaction<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 addTransitionReaction<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 addTransitionReaction(\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 : `addTransitionReaction(${getCallerName()})`;\n this.ensurePreBoot(name, \"addTransitionReaction\");\n this.ensureUniqueReactionName(name, \"addTransitionReaction\");\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 addTransitionReaction, including commit-phase callbacks. */\n reactionNames: Set<string> = new Set();\n /**\n * Field name -> its `setTransitions`, `addTransitionRule`, and `addTransitionReaction` config, with\n * 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,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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/config.d.cts
CHANGED
|
@@ -17,9 +17,9 @@ type AddReactionOpts = {
|
|
|
17
17
|
runOnce?: boolean;
|
|
18
18
|
name?: string;
|
|
19
19
|
};
|
|
20
|
-
/**
|
|
20
|
+
/** An `addTransitionRule` rule, which also gets the transition it is checking, since the entity may have moved on. */
|
|
21
21
|
type TransitionGuardFn<T extends Entity, V> = (entity: T, transition: Transition<V>) => MaybePromise<ValidationRuleResult>;
|
|
22
|
-
/** An `
|
|
22
|
+
/** An `addTransitionReaction` function, which also gets the transition it is handling, since the entity may have moved on. */
|
|
23
23
|
type TransitionFn<T extends Entity, C, V> = (entity: T, ctx: C, transition: Transition<V>) => MaybePromise<unknown>;
|
|
24
24
|
/** The enum type of a transition field, i.e. `PublisherStatus`. */
|
|
25
25
|
type TransitionType<T extends Entity, K extends keyof FieldsOf<T>> = FieldsOf<T>[K] extends EntityField ? NonNullable<FieldsOf<T>[K]["type"]> : never;
|
|
@@ -174,20 +174,20 @@ declare class ConfigApi<T extends Entity, C> {
|
|
|
174
174
|
* The table is checked by the field's setter, so a disallowed transition throws a `ValidationErrors`
|
|
175
175
|
* immediately, instead of failing the next `em.flush`.
|
|
176
176
|
*/
|
|
177
|
-
|
|
177
|
+
setTransitions<K extends Settable<T>>(fieldName: K, table: TransitionTable<TransitionStates<T, K>>): void;
|
|
178
178
|
/**
|
|
179
179
|
* Checks each matching transition before its callbacks run, and rejects it if the guard returns an error.
|
|
180
180
|
*
|
|
181
181
|
* Use this for "a transition is allowed only when ..." checks that depend on other data, while
|
|
182
|
-
* `
|
|
182
|
+
* `setTransitions` declares the transitions that are possible at all. The `hint` is a load hint, like
|
|
183
183
|
* `beforeFlush`'s, so it's loaded before `rule` runs, but only `fieldName` itself triggers the guard.
|
|
184
184
|
*
|
|
185
185
|
* Guards run with reactions, for every matching transition, even if the
|
|
186
186
|
* field has moved on since. The entity is in its current state, so `rule` also gets the `transition`
|
|
187
187
|
* it is checking. Guards never run on creation and are not rechecked during final validation.
|
|
188
188
|
*/
|
|
189
|
-
|
|
190
|
-
|
|
189
|
+
addTransitionRule<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
|
+
addTransitionRule<K extends Settable<T>>(fieldName: K, match: GuardTransitionMatch<TransitionStates<T, K>>, rule: TransitionGuardFn<T, TransitionType<T, K>>): void;
|
|
191
191
|
/**
|
|
192
192
|
* Runs `fn` for each state transition of `fieldName` that matches `match`.
|
|
193
193
|
*
|
|
@@ -196,7 +196,7 @@ declare class ConfigApi<T extends Entity, C> {
|
|
|
196
196
|
*
|
|
197
197
|
* Callbacks run with reactions, once for every matching transition, in order,
|
|
198
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
|
|
199
|
+
* `transition` it is handling. Transitions that an `addTransitionRule` rejects don't fire.
|
|
200
200
|
*
|
|
201
201
|
* Creating an entity with a matching `to` state fires too, unless `match.from` is set or
|
|
202
202
|
* `match.onCreate` is `false`. Set `match.phase: "commit"` to run in `beforeCommit` instead, i.e.
|
|
@@ -209,10 +209,10 @@ declare class ConfigApi<T extends Entity, C> {
|
|
|
209
209
|
* Pass a unique name as the first argument when registering multiple callbacks from a shared
|
|
210
210
|
* helper or loop. Duplicate names on the same config are rejected when registered.
|
|
211
211
|
*/
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
212
|
+
addTransitionReaction<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
|
+
addTransitionReaction<K extends Settable<T>>(fieldName: K, match: OnTransitionMatch<TransitionStates<T, K>>, fn: TransitionFn<T, C, TransitionType<T, K>>): void;
|
|
214
|
+
addTransitionReaction<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
|
+
addTransitionReaction<K extends Settable<T>>(name: string, fieldName: K, match: OnTransitionMatch<TransitionStates<T, K>>, fn: TransitionFn<T, C, TransitionType<T, K>>): void;
|
|
216
216
|
/** Adds a synchronous default for `fieldName` to a hard-coded `value`. */
|
|
217
217
|
setDefault<K extends Settable<T>, F = FieldsOf<T>[K]>(fieldName: K, value: F extends EntityField ? F["type"] : never): void;
|
|
218
218
|
/** Adds a synchronous default for `fieldName` to the result of simple sync lambda. */
|
|
@@ -320,10 +320,11 @@ declare class ConfigData<T extends Entity, C> {
|
|
|
320
320
|
commitRules: ValidationRuleInternal<T>[];
|
|
321
321
|
/** The reactions for this entity type. */
|
|
322
322
|
reactions: ReactionInternal<T, any, C>[];
|
|
323
|
-
/** Names shared by addReaction and
|
|
323
|
+
/** Names shared by addReaction and addTransitionReaction, including commit-phase callbacks. */
|
|
324
324
|
reactionNames: Set<string>;
|
|
325
325
|
/**
|
|
326
|
-
* Field name -> its `
|
|
326
|
+
* Field name -> its `setTransitions`, `addTransitionRule`, and `addTransitionReaction` config, with
|
|
327
|
+
* accessors not yet converted.
|
|
327
328
|
*
|
|
328
329
|
* The keys are also the fields whose factories accept `withX` opts.
|
|
329
330
|
*/
|
package/build/config.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.d.cts","names":[],"sources":["../src/config.ts"],"mappings":";;;;;;;;;;;;;KA8BY;KAQP,OAAO,UAAU,QAAQ,MAAM,QAAQ,GAAG,KAAK,MAAM;KAErD;EAAoB;EAAmB;;;KA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
19
|
};
|
|
20
|
-
/**
|
|
20
|
+
/** An `addTransitionRule` rule, which also gets the transition it is checking, since the entity may have moved on. */
|
|
21
21
|
type TransitionGuardFn<T extends Entity, V> = (entity: T, transition: Transition<V>) => MaybePromise<ValidationRuleResult>;
|
|
22
|
-
/** An `
|
|
22
|
+
/** An `addTransitionReaction` function, which also gets the transition it is handling, since the entity may have moved on. */
|
|
23
23
|
type TransitionFn<T extends Entity, C, V> = (entity: T, ctx: C, transition: Transition<V>) => MaybePromise<unknown>;
|
|
24
24
|
/** The enum type of a transition field, i.e. `PublisherStatus`. */
|
|
25
25
|
type TransitionType<T extends Entity, K extends keyof FieldsOf<T>> = FieldsOf<T>[K] extends EntityField ? NonNullable<FieldsOf<T>[K]["type"]> : never;
|
|
@@ -174,20 +174,20 @@ declare class ConfigApi<T extends Entity, C> {
|
|
|
174
174
|
* The table is checked by the field's setter, so a disallowed transition throws a `ValidationErrors`
|
|
175
175
|
* immediately, instead of failing the next `em.flush`.
|
|
176
176
|
*/
|
|
177
|
-
|
|
177
|
+
setTransitions<K extends Settable<T>>(fieldName: K, table: TransitionTable<TransitionStates<T, K>>): void;
|
|
178
178
|
/**
|
|
179
179
|
* Checks each matching transition before its callbacks run, and rejects it if the guard returns an error.
|
|
180
180
|
*
|
|
181
181
|
* Use this for "a transition is allowed only when ..." checks that depend on other data, while
|
|
182
|
-
* `
|
|
182
|
+
* `setTransitions` declares the transitions that are possible at all. The `hint` is a load hint, like
|
|
183
183
|
* `beforeFlush`'s, so it's loaded before `rule` runs, but only `fieldName` itself triggers the guard.
|
|
184
184
|
*
|
|
185
185
|
* Guards run with reactions, for every matching transition, even if the
|
|
186
186
|
* field has moved on since. The entity is in its current state, so `rule` also gets the `transition`
|
|
187
187
|
* it is checking. Guards never run on creation and are not rechecked during final validation.
|
|
188
188
|
*/
|
|
189
|
-
|
|
190
|
-
|
|
189
|
+
addTransitionRule<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
|
+
addTransitionRule<K extends Settable<T>>(fieldName: K, match: GuardTransitionMatch<TransitionStates<T, K>>, rule: TransitionGuardFn<T, TransitionType<T, K>>): void;
|
|
191
191
|
/**
|
|
192
192
|
* Runs `fn` for each state transition of `fieldName` that matches `match`.
|
|
193
193
|
*
|
|
@@ -196,7 +196,7 @@ declare class ConfigApi<T extends Entity, C> {
|
|
|
196
196
|
*
|
|
197
197
|
* Callbacks run with reactions, once for every matching transition, in order,
|
|
198
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
|
|
199
|
+
* `transition` it is handling. Transitions that an `addTransitionRule` rejects don't fire.
|
|
200
200
|
*
|
|
201
201
|
* Creating an entity with a matching `to` state fires too, unless `match.from` is set or
|
|
202
202
|
* `match.onCreate` is `false`. Set `match.phase: "commit"` to run in `beforeCommit` instead, i.e.
|
|
@@ -209,10 +209,10 @@ declare class ConfigApi<T extends Entity, C> {
|
|
|
209
209
|
* Pass a unique name as the first argument when registering multiple callbacks from a shared
|
|
210
210
|
* helper or loop. Duplicate names on the same config are rejected when registered.
|
|
211
211
|
*/
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
212
|
+
addTransitionReaction<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
|
+
addTransitionReaction<K extends Settable<T>>(fieldName: K, match: OnTransitionMatch<TransitionStates<T, K>>, fn: TransitionFn<T, C, TransitionType<T, K>>): void;
|
|
214
|
+
addTransitionReaction<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
|
+
addTransitionReaction<K extends Settable<T>>(name: string, fieldName: K, match: OnTransitionMatch<TransitionStates<T, K>>, fn: TransitionFn<T, C, TransitionType<T, K>>): void;
|
|
216
216
|
/** Adds a synchronous default for `fieldName` to a hard-coded `value`. */
|
|
217
217
|
setDefault<K extends Settable<T>, F = FieldsOf<T>[K]>(fieldName: K, value: F extends EntityField ? F["type"] : never): void;
|
|
218
218
|
/** Adds a synchronous default for `fieldName` to the result of simple sync lambda. */
|
|
@@ -320,10 +320,11 @@ declare class ConfigData<T extends Entity, C> {
|
|
|
320
320
|
commitRules: ValidationRuleInternal<T>[];
|
|
321
321
|
/** The reactions for this entity type. */
|
|
322
322
|
reactions: ReactionInternal<T, any, C>[];
|
|
323
|
-
/** Names shared by addReaction and
|
|
323
|
+
/** Names shared by addReaction and addTransitionReaction, including commit-phase callbacks. */
|
|
324
324
|
reactionNames: Set<string>;
|
|
325
325
|
/**
|
|
326
|
-
* Field name -> its `
|
|
326
|
+
* Field name -> its `setTransitions`, `addTransitionRule`, and `addTransitionReaction` config, with
|
|
327
|
+
* accessors not yet converted.
|
|
327
328
|
*
|
|
328
329
|
* The keys are also the fields whose factories accept `withX` opts.
|
|
329
330
|
*/
|
package/build/config.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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,gBA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AM;;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;;;;;;;EAOf,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
|
@@ -153,16 +153,16 @@ var ConfigApi = class {
|
|
|
153
153
|
* The table is checked by the field's setter, so a disallowed transition throws a `ValidationErrors`
|
|
154
154
|
* immediately, instead of failing the next `em.flush`.
|
|
155
155
|
*/
|
|
156
|
-
|
|
157
|
-
const name = `
|
|
158
|
-
this.ensurePreBoot(name, "
|
|
156
|
+
setTransitions(fieldName, table) {
|
|
157
|
+
const name = `setTransitions(${getCallerName()})`;
|
|
158
|
+
this.ensurePreBoot(name, "setTransitions");
|
|
159
159
|
const config = this.fieldTransitions(fieldName);
|
|
160
|
-
if (config.table) fail(`config.
|
|
160
|
+
if (config.table) fail(`config.setTransitions was already called for ${fieldName}, use one table per field`);
|
|
161
161
|
config.table = table;
|
|
162
162
|
}
|
|
163
|
-
|
|
164
|
-
const name = `
|
|
165
|
-
this.ensurePreBoot(name, "
|
|
163
|
+
addTransitionRule(fieldName, match, hintOrRule, maybeRule) {
|
|
164
|
+
const name = `addTransitionRule(${getCallerName()})`;
|
|
165
|
+
this.ensurePreBoot(name, "addTransitionRule");
|
|
166
166
|
const rule = maybeRule ?? hintOrRule;
|
|
167
167
|
const hint = maybeRule ? hintOrRule : void 0;
|
|
168
168
|
this.fieldTransitions(fieldName).guards.push({
|
|
@@ -173,11 +173,11 @@ var ConfigApi = class {
|
|
|
173
173
|
}
|
|
174
174
|
});
|
|
175
175
|
}
|
|
176
|
-
|
|
176
|
+
addTransitionReaction(nameOrFieldName, fieldNameOrMatch, matchOrHintOrFn, hintOrFn, maybeFn) {
|
|
177
177
|
const named = typeof fieldNameOrMatch === "string";
|
|
178
|
-
const name = named ? nameOrFieldName : `
|
|
179
|
-
this.ensurePreBoot(name, "
|
|
180
|
-
this.ensureUniqueReactionName(name, "
|
|
178
|
+
const name = named ? nameOrFieldName : `addTransitionReaction(${getCallerName()})`;
|
|
179
|
+
this.ensurePreBoot(name, "addTransitionReaction");
|
|
180
|
+
this.ensureUniqueReactionName(name, "addTransitionReaction");
|
|
181
181
|
const fieldName = named ? fieldNameOrMatch : nameOrFieldName;
|
|
182
182
|
const match = named ? matchOrHintOrFn : fieldNameOrMatch;
|
|
183
183
|
const hintOrCallback = named ? hintOrFn : matchOrHintOrFn;
|
|
@@ -253,10 +253,11 @@ var ConfigData = class {
|
|
|
253
253
|
commitRules = [];
|
|
254
254
|
/** The reactions for this entity type. */
|
|
255
255
|
reactions = [];
|
|
256
|
-
/** Names shared by addReaction and
|
|
256
|
+
/** Names shared by addReaction and addTransitionReaction, including commit-phase callbacks. */
|
|
257
257
|
reactionNames = /* @__PURE__ */ new Set();
|
|
258
258
|
/**
|
|
259
|
-
* Field name -> its `
|
|
259
|
+
* Field name -> its `setTransitions`, `addTransitionRule`, and `addTransitionReaction` config, with
|
|
260
|
+
* accessors not yet converted.
|
|
260
261
|
*
|
|
261
262
|
* The keys are also the fields whose factories accept `withX` opts.
|
|
262
263
|
*/
|