joist-core 2.5.0-next.24 → 2.5.0-next.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/build/PluginManager.cjs.map +1 -1
  2. package/build/PluginManager.d.cts +4 -2
  3. package/build/PluginManager.d.cts.map +1 -1
  4. package/build/PluginManager.d.mts +4 -2
  5. package/build/PluginManager.d.mts.map +1 -1
  6. package/build/PluginManager.js.map +1 -1
  7. package/build/fields.cjs +19 -5
  8. package/build/fields.cjs.map +1 -1
  9. package/build/fields.d.cts +6 -1
  10. package/build/fields.d.cts.map +1 -1
  11. package/build/fields.d.mts +6 -1
  12. package/build/fields.d.mts.map +1 -1
  13. package/build/fields.js +19 -6
  14. package/build/fields.js.map +1 -1
  15. package/build/relations/AsyncReactiveField.cjs +14 -3
  16. package/build/relations/AsyncReactiveField.cjs.map +1 -1
  17. package/build/relations/AsyncReactiveField.d.cts.map +1 -1
  18. package/build/relations/AsyncReactiveField.d.mts.map +1 -1
  19. package/build/relations/AsyncReactiveField.js +15 -4
  20. package/build/relations/AsyncReactiveField.js.map +1 -1
  21. package/build/relations/ManyToOneReference.cjs.map +1 -1
  22. package/build/relations/ManyToOneReference.d.cts.map +1 -1
  23. package/build/relations/ManyToOneReference.d.mts.map +1 -1
  24. package/build/relations/ManyToOneReference.js.map +1 -1
  25. package/build/relations/ReactiveField.cjs +55 -25
  26. package/build/relations/ReactiveField.cjs.map +1 -1
  27. package/build/relations/ReactiveField.d.cts +10 -1
  28. package/build/relations/ReactiveField.d.cts.map +1 -1
  29. package/build/relations/ReactiveField.d.mts +10 -1
  30. package/build/relations/ReactiveField.d.mts.map +1 -1
  31. package/build/relations/ReactiveField.js +56 -26
  32. package/build/relations/ReactiveField.js.map +1 -1
  33. package/build/relations/ReactiveManyToMany.cjs +15 -9
  34. package/build/relations/ReactiveManyToMany.cjs.map +1 -1
  35. package/build/relations/ReactiveManyToMany.d.cts.map +1 -1
  36. package/build/relations/ReactiveManyToMany.d.mts.map +1 -1
  37. package/build/relations/ReactiveManyToMany.js +15 -9
  38. package/build/relations/ReactiveManyToMany.js.map +1 -1
  39. package/build/relations/ReactiveReference.cjs +23 -9
  40. package/build/relations/ReactiveReference.cjs.map +1 -1
  41. package/build/relations/ReactiveReference.js +26 -12
  42. package/build/relations/ReactiveReference.js.map +1 -1
  43. package/build/relations/relationVisibility.cjs +19 -1
  44. package/build/relations/relationVisibility.cjs.map +1 -1
  45. package/build/relations/relationVisibility.d.cts +10 -0
  46. package/build/relations/relationVisibility.d.cts.map +1 -1
  47. package/build/relations/relationVisibility.d.mts +10 -0
  48. package/build/relations/relationVisibility.d.mts.map +1 -1
  49. package/build/relations/relationVisibility.js +17 -2
  50. package/build/relations/relationVisibility.js.map +1 -1
  51. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"PluginManager.cjs","names":["isDefined"],"sources":["../src/PluginManager.ts"],"sourcesContent":["import { type Entity } from \"src/Entity.ts\";\nimport { type EntityManager, type FindOperation, isDefined } from \"src/EntityManager.ts\";\nimport { type EntityMetadata } from \"src/EntityMetadata.ts\";\nimport type { JoinRowTodo, Todo } from \"src/flush/Todo.ts\";\nimport type { ParsedFindQuery } from \"src/queries/find/QueryParser.ts\";\nimport type { ParsedExecuteQuery, ParsedReadQuery } from \"src/queries/sql/ParsedQuery.ts\";\nimport { type RowData } from \"src/RowData.ts\";\n\ninterface PluginMethods {\n /** Called for em.query and SELECT em.execute queries, before join pruning. */\n beforeQuery?(query: ParsedReadQuery): void;\n\n /** Observes the top-level SELECT's rows after they are returned, before decoding or hydration. */\n afterQuery?(query: ParsedReadQuery, rows: RowData): void;\n\n /** Called before immediate mutations, which bypass entity setters and flush validation. Throw to deny. */\n beforeExecute?(query: ParsedExecuteQuery): void;\n\n /**\n * Called before a cold field read. Throw to deny access.\n * On visibility-aware EMs, called for every untrusted read and skipped for trusted reads.\n *\n * Ordinary EMs skip this hook once the field's getter is warm. Unset fields and internal reads\n * awaiting application read protection remain cold. A throwing callback can be retried.\n *\n * @param entity The entity instance being accessed\n * @param field The field name being retrieved\n */\n beforeGetField?(entity: Entity, field: string): void;\n\n /**\n * Called before a field value is set on an entity via setField.\n *\n * @param entity The entity instance being modified\n * @param field The field name being set\n * @param newValue The new value being assigned to the field\n */\n beforeSetField?(entity: Entity, field: string, newValue: any): void;\n\n /**\n * Called before a find operation is executed.\n *\n * @param meta Metadata for the entity type being queried\n * @param operation The type of find operation being performed\n * @param query The parsed query conditions\n * @param settings Query settings including limit and offset\n */\n beforeFind?(\n meta: EntityMetadata,\n operation: FindOperation,\n query: ParsedFindQuery,\n settings: {\n limit?: number;\n offset?: number;\n allowMultipleLeftJoins?: boolean;\n optimizeJoinsToExists?: boolean;\n pruneJoins?: boolean;\n keepAliases?: string[];\n },\n ): void;\n\n /**\n * Called after a find operation has been executed to observe the raw database rows.\n *\n * The result is an observation-only {@link RowData} view — i.e. `rows.rowCount` for metrics,\n * `rows.get(i, columnName)` for specific cells, or `rows.toRows()` to materialize POJO rows.\n * For lazy results, cells decode on access, so a hook that only counts rows costs nothing;\n * materializing via `toRows()` decodes every cell of every row. Mutating materialized rows is\n * unsupported and is not guaranteed to affect entity hydration.\n *\n * @param meta Metadata for the entity type that was queried\n * @param operation The type of find operation that was performed\n * @param rows A read-only view of the raw database rows returned from the query\n */\n afterFind?(meta: EntityMetadata, operation: FindOperation, rows: RowData): void;\n\n beforeValidate?(entities: readonly Entity[]): Promise<void> | void;\n\n afterValidate?(entities: readonly Entity[]): Promise<void> | void;\n\n afterWrite(entityTodos: Record<string, Todo>, joinRowTodos: Record<string, JoinRowTodo>): void;\n\n /**\n * Decides whether a hydrated entity may be returned by public EM and relation reads, including cache hits.\n *\n * This hook is synchronous. Plugins should maintain any expensive visibility metadata during hydration or\n * mutation and keep this lookup cheap. Joist skips this hook in trusted context. Relation factories select\n * subclasses at construction, so install this hook before accessing relations.\n */\n canViewEntity?(entity: Entity): boolean;\n}\n\nconst syncPluginMethods = [\n \"canViewEntity\",\n \"beforeGetField\",\n \"beforeSetField\",\n \"beforeFind\",\n \"beforeQuery\",\n \"afterQuery\",\n \"beforeExecute\",\n \"afterFind\",\n \"afterWrite\",\n] as const satisfies readonly (keyof PluginMethods)[];\nconst asyncPluginMethods = [\"beforeValidate\", \"afterValidate\"] as const satisfies readonly (keyof PluginMethods)[];\nconst emsSymbol = Symbol(\"ems\");\n/**\n * Base class for plugins that hook into entity lifecycle events.\n *\n * Plugins can implement any of the PluginMethods to intercept entity operations\n * and are automatically registered with the EntityManager when added via PluginManager.\n */\nexport abstract class Plugin {\n // We need to store the EntityManager references in a WeakRef array so that they can be garbage collected. If we\n // didn't do this, then multiple EMs with the same plugin instance could keep each other from being garbage collected.\n [emsSymbol]: WeakRef<EntityManager>[] = [];\n\n maybeCloneForNewEm(): this | undefined {\n return undefined;\n }\n\n get ems(): readonly EntityManager[] {\n return this[emsSymbol]\n .values()\n .map((wr) => wr.deref())\n .filter(isDefined)\n .toArray();\n }\n}\n\nexport interface Plugin extends PluginMethods {}\n\n/**\n * Manages plugin lifecycle and dispatches plugin callbacks to registered plugins.\n *\n * The PluginManager optimizes callback dispatch by only creating dispatcher methods\n * for callbacks that have at least one registered plugin, making unused plugin hooks\n * zero-cost at runtime.\n */\nexport class PluginManager implements Required<PluginMethods> {\n #plugins = new Set<Plugin>();\n readonly #pluginsByCallback: Partial<Record<keyof Plugin, Plugin[]>> = {};\n constructor(\n public readonly em: EntityManager,\n private readonly onVisibilityHook: () => void,\n ) {}\n\n /** Returns whether any registered plugin implements `method`, i.e. so callers can skip building its args. */\n hasHook(method: keyof PluginMethods): boolean {\n return this.#pluginsByCallback[method] !== undefined;\n }\n\n /**\n * Registers a plugin with this EntityManager.\n *\n * Dynamically creates dispatcher methods for any plugin callbacks implemented by this plugin,\n * enabling lazy initialization of only the hooks that are actually used.\n *\n * @throws Error if the plugin is already registered with another EntityManager\n */\n addPlugin(plugin: Plugin) {\n if (this.#plugins.has(plugin)) return; // if we're already added, then we can just early exit\n this.#plugins.add(plugin);\n plugin[emsSymbol].push(new WeakRef(this.em));\n for (const method of syncPluginMethods) {\n if (method in plugin) {\n (this.#pluginsByCallback[method] ??= []).push(plugin);\n // As a performance optimization, we only create the actual implementation for each method on the plugin manager\n // once we have at least one plugin using that method. This is to make it so any unused plugin methods are\n // effectively no-ops when called from within the em.\n if (!Object.hasOwn(this, method)) {\n if (method === \"canViewEntity\") {\n this.canViewEntity = function (entity) {\n for (const plugin of this.#pluginsByCallback.canViewEntity!) {\n if (!plugin.canViewEntity!(entity)) return false;\n }\n return true;\n };\n this.onVisibilityHook();\n } else {\n this[method] = function (this: PluginManager, ...args: any[]) {\n for (const plugin of this.#pluginsByCallback[method]!) {\n (plugin[method] as (...args: any[]) => unknown)(...args);\n }\n };\n }\n }\n }\n }\n for (const method of asyncPluginMethods) {\n if (method in plugin) {\n (this.#pluginsByCallback[method] ??= []).push(plugin);\n // Validate-phase plugin hooks are intentionally awaited without making hot-path hooks async.\n if (!Object.hasOwn(this, method)) {\n this[method] = async function (this: PluginManager, ...args: any[]) {\n for (const plugin of this.#pluginsByCallback[method]!) {\n await (plugin[method] as (...args: any[]) => Promise<void> | void)(...args);\n }\n };\n }\n }\n }\n }\n\n get plugins(): readonly Plugin[] {\n return [...this.#plugins];\n }\n\n cloneTo(other: PluginManager) {\n this.#plugins\n .values()\n .map((plugin) => plugin.maybeCloneForNewEm())\n .filter(isDefined)\n .forEach((plugin) => other.addPlugin(plugin));\n }\n\n // Defined as no-op functions initially instead of using optional chaining for performance reasons, see:\n // https://adventures.nodeland.dev/archive/noop-functions-vs-optional-chaining-a-performance/\n\n beforeGetField(entity: Entity, field: string): void {}\n beforeQuery(query: ParsedReadQuery): void {}\n afterQuery(query: ParsedReadQuery, rows: RowData): void {}\n beforeExecute(query: ParsedExecuteQuery): void {}\n beforeSetField(entity: Entity, field: string, newValue: any): void {}\n beforeFind(\n meta: EntityMetadata,\n operation: FindOperation,\n query: ParsedFindQuery,\n settings: {\n limit?: number;\n offset?: number;\n allowMultipleLeftJoins?: boolean;\n optimizeJoinsToExists?: boolean;\n pruneJoins?: boolean;\n keepAliases?: string[];\n },\n ): void {}\n afterFind(meta: EntityMetadata, operation: FindOperation, rows: RowData) {}\n beforeValidate(entities: readonly Entity[]): Promise<void> | void {}\n afterValidate(entities: readonly Entity[]): Promise<void> | void {}\n afterWrite(entityTodos: Record<string, Todo>, joinRowTodos: Record<string, JoinRowTodo>): void {}\n\n canViewEntity(entity: Entity): boolean {\n return true;\n }\n}\n"],"mappings":";;;;;AA4FA,MAAM,oBAAoB;CACxB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,qBAAqB,CAAC,kBAAkB,eAAe;AAC7D,MAAM,YAAY,OAAO,KAAK;;;;;;;AAO9B,IAAsB,SAAtB,MAA6B;CAG3B,CAAC,aAAuC,CAAC;CAEzC,qBAAuC,CAEvC;CAEA,IAAI,MAAgC;EAClC,OAAO,KAAK,UAAU,CACnB,OAAO,CAAC,CACR,KAAK,OAAO,GAAG,MAAM,CAAC,CAAC,CACvB,OAAOA,sBAAAA,SAAS,CAAC,CACjB,QAAQ;CACb;AACF;;;;;;;;AAWA,IAAa,gBAAb,MAA8D;CAI1C;CACC;CAJnB,2BAAW,IAAI,IAAY;CAC3B,qBAAuE,CAAC;CACxE,YACE,IACA,kBACA;EAFgB,KAAA,KAAA;EACC,KAAA,mBAAA;CAChB;;CAGH,QAAQ,QAAsC;EAC5C,OAAO,KAAK,mBAAmB,YAAY,KAAA;CAC7C;;;;;;;;;CAUA,UAAU,QAAgB;EACxB,IAAI,KAAK,SAAS,IAAI,MAAM,GAAG;EAC/B,KAAK,SAAS,IAAI,MAAM;EACxB,OAAO,UAAU,CAAC,KAAK,IAAI,QAAQ,KAAK,EAAE,CAAC;EAC3C,KAAK,MAAM,UAAU,mBACnB,IAAI,UAAU,QAAQ;GACpB,CAAC,KAAK,mBAAmB,YAAY,CAAC,EAAA,CAA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,cAAiD,CAAC;CAEhG,cAAc,QAAyB;EACrC,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"PluginManager.cjs","names":["isDefined"],"sources":["../src/PluginManager.ts"],"sourcesContent":["import { type Entity } from \"src/Entity.ts\";\nimport { type EntityManager, type FindOperation, isDefined } from \"src/EntityManager.ts\";\nimport { type EntityMetadata } from \"src/EntityMetadata.ts\";\nimport type { JoinRowTodo, Todo } from \"src/flush/Todo.ts\";\nimport type { ParsedFindQuery } from \"src/queries/find/QueryParser.ts\";\nimport type { ParsedExecuteQuery, ParsedReadQuery } from \"src/queries/sql/ParsedQuery.ts\";\nimport { type RowData } from \"src/RowData.ts\";\n\ninterface PluginMethods {\n /** Called for em.query and SELECT em.execute queries, before join pruning. */\n beforeQuery?(query: ParsedReadQuery): void;\n\n /** Observes the top-level SELECT's rows after they are returned, before decoding or hydration. */\n afterQuery?(query: ParsedReadQuery, rows: RowData): void;\n\n /** Called before immediate mutations, which bypass entity setters and flush validation. Throw to deny. */\n beforeExecute?(query: ParsedExecuteQuery): void;\n\n /**\n * Checks read access to this field on this entity. Throw to deny access.\n * On visibility-aware EMs, every untrusted read is checked. Trusted reads can reuse an earlier\n * successful check for the same field on the same entity, but untrusted reads cannot.\n * Use `isInTrustedContext()` if the field policy distinguishes ORM reads from caller reads.\n *\n * Ordinary EMs skip this hook once the field's getter is warm. Unset fields and internal reads\n * awaiting application read protection remain cold. A throwing callback can be retried.\n *\n * @param entity The entity instance being accessed\n * @param field The field name being retrieved\n */\n beforeGetField?(entity: Entity, field: string): void;\n\n /**\n * Called before a field value is set on an entity via setField.\n *\n * @param entity The entity instance being modified\n * @param field The field name being set\n * @param newValue The new value being assigned to the field\n */\n beforeSetField?(entity: Entity, field: string, newValue: any): void;\n\n /**\n * Called before a find operation is executed.\n *\n * @param meta Metadata for the entity type being queried\n * @param operation The type of find operation being performed\n * @param query The parsed query conditions\n * @param settings Query settings including limit and offset\n */\n beforeFind?(\n meta: EntityMetadata,\n operation: FindOperation,\n query: ParsedFindQuery,\n settings: {\n limit?: number;\n offset?: number;\n allowMultipleLeftJoins?: boolean;\n optimizeJoinsToExists?: boolean;\n pruneJoins?: boolean;\n keepAliases?: string[];\n },\n ): void;\n\n /**\n * Called after a find operation has been executed to observe the raw database rows.\n *\n * The result is an observation-only {@link RowData} view — i.e. `rows.rowCount` for metrics,\n * `rows.get(i, columnName)` for specific cells, or `rows.toRows()` to materialize POJO rows.\n * For lazy results, cells decode on access, so a hook that only counts rows costs nothing;\n * materializing via `toRows()` decodes every cell of every row. Mutating materialized rows is\n * unsupported and is not guaranteed to affect entity hydration.\n *\n * @param meta Metadata for the entity type that was queried\n * @param operation The type of find operation that was performed\n * @param rows A read-only view of the raw database rows returned from the query\n */\n afterFind?(meta: EntityMetadata, operation: FindOperation, rows: RowData): void;\n\n beforeValidate?(entities: readonly Entity[]): Promise<void> | void;\n\n afterValidate?(entities: readonly Entity[]): Promise<void> | void;\n\n afterWrite(entityTodos: Record<string, Todo>, joinRowTodos: Record<string, JoinRowTodo>): void;\n\n /**\n * Decides whether a hydrated entity may be returned by public EM and relation reads, including cache hits.\n *\n * This hook is synchronous. Plugins should maintain any expensive visibility metadata during hydration or\n * mutation and keep this lookup cheap. Joist skips this hook in trusted context. Relation factories select\n * subclasses at construction, so install this hook before accessing relations.\n */\n canViewEntity?(entity: Entity): boolean;\n}\n\nconst syncPluginMethods = [\n \"canViewEntity\",\n \"beforeGetField\",\n \"beforeSetField\",\n \"beforeFind\",\n \"beforeQuery\",\n \"afterQuery\",\n \"beforeExecute\",\n \"afterFind\",\n \"afterWrite\",\n] as const satisfies readonly (keyof PluginMethods)[];\nconst asyncPluginMethods = [\"beforeValidate\", \"afterValidate\"] as const satisfies readonly (keyof PluginMethods)[];\nconst emsSymbol = Symbol(\"ems\");\n/**\n * Base class for plugins that hook into entity lifecycle events.\n *\n * Plugins can implement any of the PluginMethods to intercept entity operations\n * and are automatically registered with the EntityManager when added via PluginManager.\n */\nexport abstract class Plugin {\n // We need to store the EntityManager references in a WeakRef array so that they can be garbage collected. If we\n // didn't do this, then multiple EMs with the same plugin instance could keep each other from being garbage collected.\n [emsSymbol]: WeakRef<EntityManager>[] = [];\n\n maybeCloneForNewEm(): this | undefined {\n return undefined;\n }\n\n get ems(): readonly EntityManager[] {\n return this[emsSymbol]\n .values()\n .map((wr) => wr.deref())\n .filter(isDefined)\n .toArray();\n }\n}\n\nexport interface Plugin extends PluginMethods {}\n\n/**\n * Manages plugin lifecycle and dispatches plugin callbacks to registered plugins.\n *\n * The PluginManager optimizes callback dispatch by only creating dispatcher methods\n * for callbacks that have at least one registered plugin, making unused plugin hooks\n * zero-cost at runtime.\n */\nexport class PluginManager implements Required<PluginMethods> {\n #plugins = new Set<Plugin>();\n readonly #pluginsByCallback: Partial<Record<keyof Plugin, Plugin[]>> = {};\n constructor(\n public readonly em: EntityManager,\n private readonly onVisibilityHook: () => void,\n ) {}\n\n /** Returns whether any registered plugin implements `method`, i.e. so callers can skip building its args. */\n hasHook(method: keyof PluginMethods): boolean {\n return this.#pluginsByCallback[method] !== undefined;\n }\n\n /**\n * Registers a plugin with this EntityManager.\n *\n * Dynamically creates dispatcher methods for any plugin callbacks implemented by this plugin,\n * enabling lazy initialization of only the hooks that are actually used.\n *\n * @throws Error if the plugin is already registered with another EntityManager\n */\n addPlugin(plugin: Plugin) {\n if (this.#plugins.has(plugin)) return; // if we're already added, then we can just early exit\n this.#plugins.add(plugin);\n plugin[emsSymbol].push(new WeakRef(this.em));\n for (const method of syncPluginMethods) {\n if (method in plugin) {\n (this.#pluginsByCallback[method] ??= []).push(plugin);\n // As a performance optimization, we only create the actual implementation for each method on the plugin manager\n // once we have at least one plugin using that method. This is to make it so any unused plugin methods are\n // effectively no-ops when called from within the em.\n if (!Object.hasOwn(this, method)) {\n if (method === \"canViewEntity\") {\n this.canViewEntity = function (entity) {\n for (const plugin of this.#pluginsByCallback.canViewEntity!) {\n if (!plugin.canViewEntity!(entity)) return false;\n }\n return true;\n };\n this.onVisibilityHook();\n } else {\n this[method] = function (this: PluginManager, ...args: any[]) {\n for (const plugin of this.#pluginsByCallback[method]!) {\n (plugin[method] as (...args: any[]) => unknown)(...args);\n }\n };\n }\n }\n }\n }\n for (const method of asyncPluginMethods) {\n if (method in plugin) {\n (this.#pluginsByCallback[method] ??= []).push(plugin);\n // Validate-phase plugin hooks are intentionally awaited without making hot-path hooks async.\n if (!Object.hasOwn(this, method)) {\n this[method] = async function (this: PluginManager, ...args: any[]) {\n for (const plugin of this.#pluginsByCallback[method]!) {\n await (plugin[method] as (...args: any[]) => Promise<void> | void)(...args);\n }\n };\n }\n }\n }\n }\n\n get plugins(): readonly Plugin[] {\n return [...this.#plugins];\n }\n\n cloneTo(other: PluginManager) {\n this.#plugins\n .values()\n .map((plugin) => plugin.maybeCloneForNewEm())\n .filter(isDefined)\n .forEach((plugin) => other.addPlugin(plugin));\n }\n\n // Defined as no-op functions initially instead of using optional chaining for performance reasons, see:\n // https://adventures.nodeland.dev/archive/noop-functions-vs-optional-chaining-a-performance/\n\n beforeGetField(entity: Entity, field: string): void {}\n beforeQuery(query: ParsedReadQuery): void {}\n afterQuery(query: ParsedReadQuery, rows: RowData): void {}\n beforeExecute(query: ParsedExecuteQuery): void {}\n beforeSetField(entity: Entity, field: string, newValue: any): void {}\n beforeFind(\n meta: EntityMetadata,\n operation: FindOperation,\n query: ParsedFindQuery,\n settings: {\n limit?: number;\n offset?: number;\n allowMultipleLeftJoins?: boolean;\n optimizeJoinsToExists?: boolean;\n pruneJoins?: boolean;\n keepAliases?: string[];\n },\n ): void {}\n afterFind(meta: EntityMetadata, operation: FindOperation, rows: RowData) {}\n beforeValidate(entities: readonly Entity[]): Promise<void> | void {}\n afterValidate(entities: readonly Entity[]): Promise<void> | void {}\n afterWrite(entityTodos: Record<string, Todo>, joinRowTodos: Record<string, JoinRowTodo>): void {}\n\n canViewEntity(entity: Entity): boolean {\n return true;\n }\n}\n"],"mappings":";;;;;AA8FA,MAAM,oBAAoB;CAC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;GAEJ;EACF;EAEF,KAAK,MAAM,UAAU,oBACnB,IAAI,UAAU,QAAQ;GACpB,CAAC,KAAK,mBAAmB,YAAY,CAAC,EAAA,CAAG,KAAK,MAAM;GAEpD,IAAI,CAAC,OAAO,OAAO,MAAM,MAAM,GAC7B,KAAK,UAAU,eAAqC,GAAG,MAAa;IAClE,KAAK,MAAM,UAAU,KAAK,mBAAmB,SAC3C,MAAO,OAAO,OAAO,CAA8C,GAAG,IAAI;GAE9E;EAEJ;CAEJ;CAEA,IAAI,UAA6B;EAC/B,OAAO,CAAC,GAAG,KAAK,QAAQ;CAC1B;CAEA,QAAQ,OAAsB;EAC5B,KAAK,SACF,OAAO,CAAC,CACR,KAAK,WAAW,OAAO,mBAAmB,CAAC,CAAC,CAC5C,OAAOA,sBAAAA,SAAS,CAAC,CACjB,SAAS,WAAW,MAAM,UAAU,MAAM,CAAC;CAChD;CAKA,eAAe,QAAgB,OAAqB,CAAC;CACrD,YAAY,OAA8B,CAAC;CAC3C,WAAW,OAAwB,MAAqB,CAAC;CACzD,cAAc,OAAiC,CAAC;CAChD,eAAe,QAAgB,OAAe,UAAqB,CAAC;CACpE,WACE,MACA,WACA,OACA,UAQM,CAAC;CACT,UAAU,MAAsB,WAA0B,MAAe,CAAC;CAC1E,eAAe,UAAmD,CAAC;CACnE,cAAc,UAAmD,CAAC;CAClE,WAAW,aAAmC,cAAiD,CAAC;CAEhG,cAAc,QAAyB;EACrC,OAAO;CACT;AACF"}
@@ -13,8 +13,10 @@ interface PluginMethods {
13
13
  /** Called before immediate mutations, which bypass entity setters and flush validation. Throw to deny. */
14
14
  beforeExecute?(query: ParsedExecuteQuery): void;
15
15
  /**
16
- * Called before a cold field read. Throw to deny access.
17
- * On visibility-aware EMs, called for every untrusted read and skipped for trusted reads.
16
+ * Checks read access to this field on this entity. Throw to deny access.
17
+ * On visibility-aware EMs, every untrusted read is checked. Trusted reads can reuse an earlier
18
+ * successful check for the same field on the same entity, but untrusted reads cannot.
19
+ * Use `isInTrustedContext()` if the field policy distinguishes ORM reads from caller reads.
18
20
  *
19
21
  * Ordinary EMs skip this hook once the field's getter is warm. Unset fields and internal reads
20
22
  * awaiting application read protection remain cold. A throwing callback can be retried.
@@ -1 +1 @@
1
- {"version":3,"file":"PluginManager.d.cts","names":[],"sources":["../src/PluginManager.ts"],"mappings":";;;;;;;UAQU;;EAER,aAAa,OAAO;;EAGpB,YAAY,OAAO,iBAAiB,MAAM;;EAG1C,eAAe,OAAO;;;;;;;;;;;EAYtB,gBAAgB,QAAQ,QAAQ;;;;;;;;EAShC,gBAAgB,QAAQ,QAAQ,eAAe;;;;;;;;;EAU/C,YACE,MAAM,gBACN,WAAW,eACX,OAAO,iBACP;IACE;IACA;IACA;IACA;IACA;IACA;;;;;;;;;;;;;;;EAiBJ,WAAW,MAAM,gBAAgB,WAAW,eAAe,MAAM;EAEjE,gBAAgB,mBAAmB,WAAW;EAE9C,eAAe,mBAAmB,WAAW;EAE7C,WAAW,aAAa,eAAe,OAAO,cAAc,eAAe;;;;;;;;EAS3E,eAAe,QAAQ;;cAenB;;;;;;;8BAOgB;GAGnB,YAAY,QAAQ;EAErB;MAII,gBAAgB;;iBASL,eAAe;;;;;;;;qBASnB,yBAAyB,SAAS;;WAI3B,IAAI;mBACH;EAFnB,YACkB,IAAI,eACH;;EAInB,QAAQ,cAAc;;;;;;;;;EAYtB,UAAU,QAAQ;MA4Cd,oBAAoB;EAIxB,QAAQ,OAAO;EAWf,eAAe,QAAQ,QAAQ;EAC/B,YAAY,OAAO;EACnB,WAAW,OAAO,iBAAiB,MAAM;EACzC,cAAc,OAAO;EACrB,eAAe,QAAQ,QAAQ,eAAe;EAC9C,WACE,MAAM,gBACN,WAAW,eACX,OAAO,iBACP;IACE;IACA;IACA;IACA;IACA;IACA;;EAGJ,UAAU,MAAM,gBAAgB,WAAW,eAAe,MAAM;EAChE,eAAe,mBAAmB,WAAW;EAC7C,cAAc,mBAAmB,WAAW;EAC5C,WAAW,aAAa,eAAe,OAAO,cAAc,eAAe;EAE3E,cAAc,QAAQ"}
1
+ {"version":3,"file":"PluginManager.d.cts","names":[],"sources":["../src/PluginManager.ts"],"mappings":";;;;;;;UAQU;;EAER,aAAa,OAAO;;EAGpB,YAAY,OAAO,iBAAiB,MAAM;;EAG1C,eAAe,OAAO;;;;;;;;;;;;;EActB,gBAAgB,QAAQ,QAAQ;;;;;;;;EAShC,gBAAgB,QAAQ,QAAQ,eAAe;;;;;;;;;EAU/C,YACE,MAAM,gBACN,WAAW,eACX,OAAO,iBACP;IACE;IACA;IACA;IACA;IACA;IACA;;;;;;;;;;;;;;;EAiBJ,WAAW,MAAM,gBAAgB,WAAW,eAAe,MAAM;EAEjE,gBAAgB,mBAAmB,WAAW;EAE9C,eAAe,mBAAmB,WAAW;EAE7C,WAAW,aAAa,eAAe,OAAO,cAAc,eAAe;;;;;;;;EAS3E,eAAe,QAAQ;;cAenB;;;;;;;8BAOgB;GAGnB,YAAY,QAAQ;EAErB;MAII,gBAAgB;;iBASL,eAAe;;;;;;;;qBASnB,yBAAyB,SAAS;;WAI3B,IAAI;mBACH;EAFnB,YACkB,IAAI,eACH;;EAInB,QAAQ,cAAc;;;;;;;;;EAYtB,UAAU,QAAQ;MA4Cd,oBAAoB;EAIxB,QAAQ,OAAO;EAWf,eAAe,QAAQ,QAAQ;EAC/B,YAAY,OAAO;EACnB,WAAW,OAAO,iBAAiB,MAAM;EACzC,cAAc,OAAO;EACrB,eAAe,QAAQ,QAAQ,eAAe;EAC9C,WACE,MAAM,gBACN,WAAW,eACX,OAAO,iBACP;IACE;IACA;IACA;IACA;IACA;IACA;;EAGJ,UAAU,MAAM,gBAAgB,WAAW,eAAe,MAAM;EAChE,eAAe,mBAAmB,WAAW;EAC7C,cAAc,mBAAmB,WAAW;EAC5C,WAAW,aAAa,eAAe,OAAO,cAAc,eAAe;EAE3E,cAAc,QAAQ"}
@@ -13,8 +13,10 @@ interface PluginMethods {
13
13
  /** Called before immediate mutations, which bypass entity setters and flush validation. Throw to deny. */
14
14
  beforeExecute?(query: ParsedExecuteQuery): void;
15
15
  /**
16
- * Called before a cold field read. Throw to deny access.
17
- * On visibility-aware EMs, called for every untrusted read and skipped for trusted reads.
16
+ * Checks read access to this field on this entity. Throw to deny access.
17
+ * On visibility-aware EMs, every untrusted read is checked. Trusted reads can reuse an earlier
18
+ * successful check for the same field on the same entity, but untrusted reads cannot.
19
+ * Use `isInTrustedContext()` if the field policy distinguishes ORM reads from caller reads.
18
20
  *
19
21
  * Ordinary EMs skip this hook once the field's getter is warm. Unset fields and internal reads
20
22
  * awaiting application read protection remain cold. A throwing callback can be retried.
@@ -1 +1 @@
1
- {"version":3,"file":"PluginManager.d.mts","names":[],"sources":["../src/PluginManager.ts"],"mappings":";;;;;;;UAQU;;EAER,aAAa,OAAO;;EAGpB,YAAY,OAAO,iBAAiB,MAAM;;EAG1C,eAAe,OAAO;;;;;;;;;;;EAYtB,gBAAgB,QAAQ,QAAQ;;;;;;;;EAShC,gBAAgB,QAAQ,QAAQ,eAAe;;;;;;;;;EAU/C,YACE,MAAM,gBACN,WAAW,eACX,OAAO,iBACP;IACE;IACA;IACA;IACA;IACA;IACA;;;;;;;;;;;;;;;EAiBJ,WAAW,MAAM,gBAAgB,WAAW,eAAe,MAAM;EAEjE,gBAAgB,mBAAmB,WAAW;EAE9C,eAAe,mBAAmB,WAAW;EAE7C,WAAW,aAAa,eAAe,OAAO,cAAc,eAAe;;;;;;;;EAS3E,eAAe,QAAQ;;cAenB;;;;;;;8BAOgB;GAGnB,YAAY,QAAQ;EAErB;MAII,gBAAgB;;iBASL,eAAe;;;;;;;;qBASnB,yBAAyB,SAAS;;WAI3B,IAAI;mBACH;EAFnB,YACkB,IAAI,eACH;;EAInB,QAAQ,cAAc;;;;;;;;;EAYtB,UAAU,QAAQ;MA4Cd,oBAAoB;EAIxB,QAAQ,OAAO;EAWf,eAAe,QAAQ,QAAQ;EAC/B,YAAY,OAAO;EACnB,WAAW,OAAO,iBAAiB,MAAM;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IACA;IACA;IACA;IACA;;EAGJ,UAAU,MAAM,gBAAgB,WAAW,eAAe,MAAM;EAChE,eAAe,mBAAmB,WAAW;EAC7C,cAAc,mBAAmB,WAAW;EAC5C,WAAW,aAAa,eAAe,OAAO,cAAc,eAAe;EAE3E,cAAc,QAAQ"}
@@ -1 +1 @@
1
- {"version":3,"file":"PluginManager.js","names":[],"sources":["../src/PluginManager.ts"],"sourcesContent":["import { type Entity } from \"src/Entity.ts\";\nimport { type EntityManager, type FindOperation, isDefined } from \"src/EntityManager.ts\";\nimport { type EntityMetadata } from \"src/EntityMetadata.ts\";\nimport type { JoinRowTodo, Todo } from \"src/flush/Todo.ts\";\nimport type { ParsedFindQuery } from \"src/queries/find/QueryParser.ts\";\nimport type { ParsedExecuteQuery, ParsedReadQuery } from \"src/queries/sql/ParsedQuery.ts\";\nimport { type RowData } from \"src/RowData.ts\";\n\ninterface PluginMethods {\n /** Called for em.query and SELECT em.execute queries, before join pruning. */\n beforeQuery?(query: ParsedReadQuery): void;\n\n /** Observes the top-level SELECT's rows after they are returned, before decoding or hydration. */\n afterQuery?(query: ParsedReadQuery, rows: RowData): void;\n\n /** Called before immediate mutations, which bypass entity setters and flush validation. Throw to deny. */\n beforeExecute?(query: ParsedExecuteQuery): void;\n\n /**\n * Called before a cold field read. Throw to deny access.\n * On visibility-aware EMs, called for every untrusted read and skipped for trusted reads.\n *\n * Ordinary EMs skip this hook once the field's getter is warm. Unset fields and internal reads\n * awaiting application read protection remain cold. A throwing callback can be retried.\n *\n * @param entity The entity instance being accessed\n * @param field The field name being retrieved\n */\n beforeGetField?(entity: Entity, field: string): void;\n\n /**\n * Called before a field value is set on an entity via setField.\n *\n * @param entity The entity instance being modified\n * @param field The field name being set\n * @param newValue The new value being assigned to the field\n */\n beforeSetField?(entity: Entity, field: string, newValue: any): void;\n\n /**\n * Called before a find operation is executed.\n *\n * @param meta Metadata for the entity type being queried\n * @param operation The type of find operation being performed\n * @param query The parsed query conditions\n * @param settings Query settings including limit and offset\n */\n beforeFind?(\n meta: EntityMetadata,\n operation: FindOperation,\n query: ParsedFindQuery,\n settings: {\n limit?: number;\n offset?: number;\n allowMultipleLeftJoins?: boolean;\n optimizeJoinsToExists?: boolean;\n pruneJoins?: boolean;\n keepAliases?: string[];\n },\n ): void;\n\n /**\n * Called after a find operation has been executed to observe the raw database rows.\n *\n * The result is an observation-only {@link RowData} view — i.e. `rows.rowCount` for metrics,\n * `rows.get(i, columnName)` for specific cells, or `rows.toRows()` to materialize POJO rows.\n * For lazy results, cells decode on access, so a hook that only counts rows costs nothing;\n * materializing via `toRows()` decodes every cell of every row. Mutating materialized rows is\n * unsupported and is not guaranteed to affect entity hydration.\n *\n * @param meta Metadata for the entity type that was queried\n * @param operation The type of find operation that was performed\n * @param rows A read-only view of the raw database rows returned from the query\n */\n afterFind?(meta: EntityMetadata, operation: FindOperation, rows: RowData): void;\n\n beforeValidate?(entities: readonly Entity[]): Promise<void> | void;\n\n afterValidate?(entities: readonly Entity[]): Promise<void> | void;\n\n afterWrite(entityTodos: Record<string, Todo>, joinRowTodos: Record<string, JoinRowTodo>): void;\n\n /**\n * Decides whether a hydrated entity may be returned by public EM and relation reads, including cache hits.\n *\n * This hook is synchronous. Plugins should maintain any expensive visibility metadata during hydration or\n * mutation and keep this lookup cheap. Joist skips this hook in trusted context. Relation factories select\n * subclasses at construction, so install this hook before accessing relations.\n */\n canViewEntity?(entity: Entity): boolean;\n}\n\nconst syncPluginMethods = [\n \"canViewEntity\",\n \"beforeGetField\",\n \"beforeSetField\",\n \"beforeFind\",\n \"beforeQuery\",\n \"afterQuery\",\n \"beforeExecute\",\n \"afterFind\",\n \"afterWrite\",\n] as const satisfies readonly (keyof PluginMethods)[];\nconst asyncPluginMethods = [\"beforeValidate\", \"afterValidate\"] as const satisfies readonly (keyof PluginMethods)[];\nconst emsSymbol = Symbol(\"ems\");\n/**\n * Base class for plugins that hook into entity lifecycle events.\n *\n * Plugins can implement any of the PluginMethods to intercept entity operations\n * and are automatically registered with the EntityManager when added via PluginManager.\n */\nexport abstract class Plugin {\n // We need to store the EntityManager references in a WeakRef array so that they can be garbage collected. If we\n // didn't do this, then multiple EMs with the same plugin instance could keep each other from being garbage collected.\n [emsSymbol]: WeakRef<EntityManager>[] = [];\n\n maybeCloneForNewEm(): this | undefined {\n return undefined;\n }\n\n get ems(): readonly EntityManager[] {\n return this[emsSymbol]\n .values()\n .map((wr) => wr.deref())\n .filter(isDefined)\n .toArray();\n }\n}\n\nexport interface Plugin extends PluginMethods {}\n\n/**\n * Manages plugin lifecycle and dispatches plugin callbacks to registered plugins.\n *\n * The PluginManager optimizes callback dispatch by only creating dispatcher methods\n * for callbacks that have at least one registered plugin, making unused plugin hooks\n * zero-cost at runtime.\n */\nexport class PluginManager implements Required<PluginMethods> {\n #plugins = new Set<Plugin>();\n readonly #pluginsByCallback: Partial<Record<keyof Plugin, Plugin[]>> = {};\n constructor(\n public readonly em: EntityManager,\n private readonly onVisibilityHook: () => void,\n ) {}\n\n /** Returns whether any registered plugin implements `method`, i.e. so callers can skip building its args. */\n hasHook(method: keyof PluginMethods): boolean {\n return this.#pluginsByCallback[method] !== undefined;\n }\n\n /**\n * Registers a plugin with this EntityManager.\n *\n * Dynamically creates dispatcher methods for any plugin callbacks implemented by this plugin,\n * enabling lazy initialization of only the hooks that are actually used.\n *\n * @throws Error if the plugin is already registered with another EntityManager\n */\n addPlugin(plugin: Plugin) {\n if (this.#plugins.has(plugin)) return; // if we're already added, then we can just early exit\n this.#plugins.add(plugin);\n plugin[emsSymbol].push(new WeakRef(this.em));\n for (const method of syncPluginMethods) {\n if (method in plugin) {\n (this.#pluginsByCallback[method] ??= []).push(plugin);\n // As a performance optimization, we only create the actual implementation for each method on the plugin manager\n // once we have at least one plugin using that method. This is to make it so any unused plugin methods are\n // effectively no-ops when called from within the em.\n if (!Object.hasOwn(this, method)) {\n if (method === \"canViewEntity\") {\n this.canViewEntity = function (entity) {\n for (const plugin of this.#pluginsByCallback.canViewEntity!) {\n if (!plugin.canViewEntity!(entity)) return false;\n }\n return true;\n };\n this.onVisibilityHook();\n } else {\n this[method] = function (this: PluginManager, ...args: any[]) {\n for (const plugin of this.#pluginsByCallback[method]!) {\n (plugin[method] as (...args: any[]) => unknown)(...args);\n }\n };\n }\n }\n }\n }\n for (const method of asyncPluginMethods) {\n if (method in plugin) {\n (this.#pluginsByCallback[method] ??= []).push(plugin);\n // Validate-phase plugin hooks are intentionally awaited without making hot-path hooks async.\n if (!Object.hasOwn(this, method)) {\n this[method] = async function (this: PluginManager, ...args: any[]) {\n for (const plugin of this.#pluginsByCallback[method]!) {\n await (plugin[method] as (...args: any[]) => Promise<void> | void)(...args);\n }\n };\n }\n }\n }\n }\n\n get plugins(): readonly Plugin[] {\n return [...this.#plugins];\n }\n\n cloneTo(other: PluginManager) {\n this.#plugins\n .values()\n .map((plugin) => plugin.maybeCloneForNewEm())\n .filter(isDefined)\n .forEach((plugin) => other.addPlugin(plugin));\n }\n\n // Defined as no-op functions initially instead of using optional chaining for performance reasons, see:\n // https://adventures.nodeland.dev/archive/noop-functions-vs-optional-chaining-a-performance/\n\n beforeGetField(entity: Entity, field: string): void {}\n beforeQuery(query: ParsedReadQuery): void {}\n afterQuery(query: ParsedReadQuery, rows: RowData): void {}\n beforeExecute(query: ParsedExecuteQuery): void {}\n beforeSetField(entity: Entity, field: string, newValue: any): void {}\n beforeFind(\n meta: EntityMetadata,\n operation: FindOperation,\n query: ParsedFindQuery,\n settings: {\n limit?: number;\n offset?: number;\n allowMultipleLeftJoins?: boolean;\n optimizeJoinsToExists?: boolean;\n pruneJoins?: boolean;\n keepAliases?: string[];\n },\n ): void {}\n afterFind(meta: EntityMetadata, operation: FindOperation, rows: RowData) {}\n beforeValidate(entities: readonly Entity[]): Promise<void> | void {}\n afterValidate(entities: readonly Entity[]): Promise<void> | void {}\n afterWrite(entityTodos: Record<string, Todo>, joinRowTodos: Record<string, JoinRowTodo>): void {}\n\n canViewEntity(entity: Entity): boolean {\n return true;\n }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,OAAO,CAAiC,GAAG,IAAI;IAE3D;GAEJ;EACF;EAEF,KAAK,MAAM,UAAU,oBACnB,IAAI,UAAU,QAAQ;GACpB,CAAC,KAAK,mBAAmB,YAAY,CAAC,EAAA,CAAG,KAAK,MAAM;GAEpD,IAAI,CAAC,OAAO,OAAO,MAAM,MAAM,GAC7B,KAAK,UAAU,eAAqC,GAAG,MAAa;IAClE,KAAK,MAAM,UAAU,KAAK,mBAAmB,SAC3C,MAAO,OAAO,OAAO,CAA8C,GAAG,IAAI;GAE9E;EAEJ;CAEJ;CAEA,IAAI,UAA6B;EAC/B,OAAO,CAAC,GAAG,KAAK,QAAQ;CAC1B;CAEA,QAAQ,OAAsB;EAC5B,KAAK,SACF,OAAO,CAAC,CACR,KAAK,WAAW,OAAO,mBAAmB,CAAC,CAAC,CAC5C,OAAO,SAAS,CAAC,CACjB,SAAS,WAAW,MAAM,UAAU,MAAM,CAAC;CAChD;CAKA,eAAe,QAAgB,OAAqB,CAAC;CACrD,YAAY,OAA8B,CAAC;CAC3C,WAAW,OAAwB,MAAqB,CAAC;CACzD,cAAc,OAAiC,CAAC;CAChD,eAAe,QAAgB,OAAe,UAAqB,CAAC;CACpE,WACE,MACA,WACA,OACA,UAQM,CAAC;CACT,UAAU,MAAsB,WAA0B,MAAe,CAAC;CAC1E,eAAe,UAAmD,CAAC;CACnE,cAAc,UAAmD,CAAC;CAClE,WAAW,aAAmC,cAAiD,CAAC;CAEhG,cAAc,QAAyB;EACrC,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"PluginManager.js","names":[],"sources":["../src/PluginManager.ts"],"sourcesContent":["import { type Entity } from \"src/Entity.ts\";\nimport { type EntityManager, type FindOperation, isDefined } from \"src/EntityManager.ts\";\nimport { type EntityMetadata } from \"src/EntityMetadata.ts\";\nimport type { JoinRowTodo, Todo } from \"src/flush/Todo.ts\";\nimport type { ParsedFindQuery } from \"src/queries/find/QueryParser.ts\";\nimport type { ParsedExecuteQuery, ParsedReadQuery } from \"src/queries/sql/ParsedQuery.ts\";\nimport { type RowData } from \"src/RowData.ts\";\n\ninterface PluginMethods {\n /** Called for em.query and SELECT em.execute queries, before join pruning. */\n beforeQuery?(query: ParsedReadQuery): void;\n\n /** Observes the top-level SELECT's rows after they are returned, before decoding or hydration. */\n afterQuery?(query: ParsedReadQuery, rows: RowData): void;\n\n /** Called before immediate mutations, which bypass entity setters and flush validation. Throw to deny. */\n beforeExecute?(query: ParsedExecuteQuery): void;\n\n /**\n * Checks read access to this field on this entity. Throw to deny access.\n * On visibility-aware EMs, every untrusted read is checked. Trusted reads can reuse an earlier\n * successful check for the same field on the same entity, but untrusted reads cannot.\n * Use `isInTrustedContext()` if the field policy distinguishes ORM reads from caller reads.\n *\n * Ordinary EMs skip this hook once the field's getter is warm. Unset fields and internal reads\n * awaiting application read protection remain cold. A throwing callback can be retried.\n *\n * @param entity The entity instance being accessed\n * @param field The field name being retrieved\n */\n beforeGetField?(entity: Entity, field: string): void;\n\n /**\n * Called before a field value is set on an entity via setField.\n *\n * @param entity The entity instance being modified\n * @param field The field name being set\n * @param newValue The new value being assigned to the field\n */\n beforeSetField?(entity: Entity, field: string, newValue: any): void;\n\n /**\n * Called before a find operation is executed.\n *\n * @param meta Metadata for the entity type being queried\n * @param operation The type of find operation being performed\n * @param query The parsed query conditions\n * @param settings Query settings including limit and offset\n */\n beforeFind?(\n meta: EntityMetadata,\n operation: FindOperation,\n query: ParsedFindQuery,\n settings: {\n limit?: number;\n offset?: number;\n allowMultipleLeftJoins?: boolean;\n optimizeJoinsToExists?: boolean;\n pruneJoins?: boolean;\n keepAliases?: string[];\n },\n ): void;\n\n /**\n * Called after a find operation has been executed to observe the raw database rows.\n *\n * The result is an observation-only {@link RowData} view — i.e. `rows.rowCount` for metrics,\n * `rows.get(i, columnName)` for specific cells, or `rows.toRows()` to materialize POJO rows.\n * For lazy results, cells decode on access, so a hook that only counts rows costs nothing;\n * materializing via `toRows()` decodes every cell of every row. Mutating materialized rows is\n * unsupported and is not guaranteed to affect entity hydration.\n *\n * @param meta Metadata for the entity type that was queried\n * @param operation The type of find operation that was performed\n * @param rows A read-only view of the raw database rows returned from the query\n */\n afterFind?(meta: EntityMetadata, operation: FindOperation, rows: RowData): void;\n\n beforeValidate?(entities: readonly Entity[]): Promise<void> | void;\n\n afterValidate?(entities: readonly Entity[]): Promise<void> | void;\n\n afterWrite(entityTodos: Record<string, Todo>, joinRowTodos: Record<string, JoinRowTodo>): void;\n\n /**\n * Decides whether a hydrated entity may be returned by public EM and relation reads, including cache hits.\n *\n * This hook is synchronous. Plugins should maintain any expensive visibility metadata during hydration or\n * mutation and keep this lookup cheap. Joist skips this hook in trusted context. Relation factories select\n * subclasses at construction, so install this hook before accessing relations.\n */\n canViewEntity?(entity: Entity): boolean;\n}\n\nconst syncPluginMethods = [\n \"canViewEntity\",\n \"beforeGetField\",\n \"beforeSetField\",\n \"beforeFind\",\n \"beforeQuery\",\n \"afterQuery\",\n \"beforeExecute\",\n \"afterFind\",\n \"afterWrite\",\n] as const satisfies readonly (keyof PluginMethods)[];\nconst asyncPluginMethods = [\"beforeValidate\", \"afterValidate\"] as const satisfies readonly (keyof PluginMethods)[];\nconst emsSymbol = Symbol(\"ems\");\n/**\n * Base class for plugins that hook into entity lifecycle events.\n *\n * Plugins can implement any of the PluginMethods to intercept entity operations\n * and are automatically registered with the EntityManager when added via PluginManager.\n */\nexport abstract class Plugin {\n // We need to store the EntityManager references in a WeakRef array so that they can be garbage collected. If we\n // didn't do this, then multiple EMs with the same plugin instance could keep each other from being garbage collected.\n [emsSymbol]: WeakRef<EntityManager>[] = [];\n\n maybeCloneForNewEm(): this | undefined {\n return undefined;\n }\n\n get ems(): readonly EntityManager[] {\n return this[emsSymbol]\n .values()\n .map((wr) => wr.deref())\n .filter(isDefined)\n .toArray();\n }\n}\n\nexport interface Plugin extends PluginMethods {}\n\n/**\n * Manages plugin lifecycle and dispatches plugin callbacks to registered plugins.\n *\n * The PluginManager optimizes callback dispatch by only creating dispatcher methods\n * for callbacks that have at least one registered plugin, making unused plugin hooks\n * zero-cost at runtime.\n */\nexport class PluginManager implements Required<PluginMethods> {\n #plugins = new Set<Plugin>();\n readonly #pluginsByCallback: Partial<Record<keyof Plugin, Plugin[]>> = {};\n constructor(\n public readonly em: EntityManager,\n private readonly onVisibilityHook: () => void,\n ) {}\n\n /** Returns whether any registered plugin implements `method`, i.e. so callers can skip building its args. */\n hasHook(method: keyof PluginMethods): boolean {\n return this.#pluginsByCallback[method] !== undefined;\n }\n\n /**\n * Registers a plugin with this EntityManager.\n *\n * Dynamically creates dispatcher methods for any plugin callbacks implemented by this plugin,\n * enabling lazy initialization of only the hooks that are actually used.\n *\n * @throws Error if the plugin is already registered with another EntityManager\n */\n addPlugin(plugin: Plugin) {\n if (this.#plugins.has(plugin)) return; // if we're already added, then we can just early exit\n this.#plugins.add(plugin);\n plugin[emsSymbol].push(new WeakRef(this.em));\n for (const method of syncPluginMethods) {\n if (method in plugin) {\n (this.#pluginsByCallback[method] ??= []).push(plugin);\n // As a performance optimization, we only create the actual implementation for each method on the plugin manager\n // once we have at least one plugin using that method. This is to make it so any unused plugin methods are\n // effectively no-ops when called from within the em.\n if (!Object.hasOwn(this, method)) {\n if (method === \"canViewEntity\") {\n this.canViewEntity = function (entity) {\n for (const plugin of this.#pluginsByCallback.canViewEntity!) {\n if (!plugin.canViewEntity!(entity)) return false;\n }\n return true;\n };\n this.onVisibilityHook();\n } else {\n this[method] = function (this: PluginManager, ...args: any[]) {\n for (const plugin of this.#pluginsByCallback[method]!) {\n (plugin[method] as (...args: any[]) => unknown)(...args);\n }\n };\n }\n }\n }\n }\n for (const method of asyncPluginMethods) {\n if (method in plugin) {\n (this.#pluginsByCallback[method] ??= []).push(plugin);\n // Validate-phase plugin hooks are intentionally awaited without making hot-path hooks async.\n if (!Object.hasOwn(this, method)) {\n this[method] = async function (this: PluginManager, ...args: any[]) {\n for (const plugin of this.#pluginsByCallback[method]!) {\n await (plugin[method] as (...args: any[]) => Promise<void> | void)(...args);\n }\n };\n }\n }\n }\n }\n\n get plugins(): readonly Plugin[] {\n return [...this.#plugins];\n }\n\n cloneTo(other: PluginManager) {\n this.#plugins\n .values()\n .map((plugin) => plugin.maybeCloneForNewEm())\n .filter(isDefined)\n .forEach((plugin) => other.addPlugin(plugin));\n }\n\n // Defined as no-op functions initially instead of using optional chaining for performance reasons, see:\n // https://adventures.nodeland.dev/archive/noop-functions-vs-optional-chaining-a-performance/\n\n beforeGetField(entity: Entity, field: string): void {}\n beforeQuery(query: ParsedReadQuery): void {}\n afterQuery(query: ParsedReadQuery, rows: RowData): void {}\n beforeExecute(query: ParsedExecuteQuery): void {}\n beforeSetField(entity: Entity, field: string, newValue: any): void {}\n beforeFind(\n meta: EntityMetadata,\n operation: FindOperation,\n query: ParsedFindQuery,\n settings: {\n limit?: number;\n offset?: number;\n allowMultipleLeftJoins?: boolean;\n optimizeJoinsToExists?: boolean;\n pruneJoins?: boolean;\n keepAliases?: string[];\n },\n ): void {}\n afterFind(meta: EntityMetadata, operation: FindOperation, rows: RowData) {}\n beforeValidate(entities: readonly Entity[]): Promise<void> | void {}\n afterValidate(entities: readonly Entity[]): Promise<void> | void {}\n afterWrite(entityTodos: Record<string, Todo>, joinRowTodos: Record<string, JoinRowTodo>): void {}\n\n canViewEntity(entity: Entity): boolean {\n return true;\n }\n}\n"],"mappings":";;;;AA8FA,MAAM,oBAAoB;CACxB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,qBAAqB,CAAC,kBAAkB,eAAe;AAC7D,MAAM,YAAY,OAAO,KAAK;;;;;;;AAO9B,IAAsB,SAAtB,MAA6B;CAG3B,CAAC,aAAuC,CAAC;CAEzC,qBAAuC,CAEvC;CAEA,IAAI,MAAgC;EAClC,OAAO,KAAK,UAAU,CACnB,OAAO,CAAC,CACR,KAAK,OAAO,GAAG,MAAM,CAAC,CAAC,CACvB,OAAO,SAAS,CAAC,CACjB,QAAQ;CACb;AACF;;;;;;;;AA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C1B;CAEA,QAAQ,OAAsB;EAC5B,KAAK,SACF,OAAO,CAAC,CACR,KAAK,WAAW,OAAO,mBAAmB,CAAC,CAAC,CAC5C,OAAO,SAAS,CAAC,CACjB,SAAS,WAAW,MAAM,UAAU,MAAM,CAAC;CAChD;CAKA,eAAe,QAAgB,OAAqB,CAAC;CACrD,YAAY,OAA8B,CAAC;CAC3C,WAAW,OAAwB,MAAqB,CAAC;CACzD,cAAc,OAAiC,CAAC;CAChD,eAAe,QAAgB,OAAe,UAAqB,CAAC;CACpE,WACE,MACA,WACA,OACA,UAQM,CAAC;CACT,UAAU,MAAsB,WAA0B,MAAe,CAAC;CAC1E,eAAe,UAAmD,CAAC;CACnE,cAAc,UAAmD,CAAC;CAClE,WAAW,aAAmC,cAAiD,CAAC;CAEhG,cAAc,QAAyB;EACrC,OAAO;CACT;AACF"}
package/build/fields.cjs CHANGED
@@ -13,7 +13,7 @@ const require_utils = require("./utils.cjs");
13
13
  * Returns the current value of `fieldName`, marking the entity for read locking if the field is configured.
14
14
  *
15
15
  * Ordinary EMs skip hooks once a field is warm. Visibility-aware EMs
16
- * check every untrusted read and cache only trusted reads, which skip read hooks.
16
+ * check every untrusted read and cache trusted reads separately.
17
17
  *
18
18
  * Install plugins before reading entities; adding one later does not replay cached reads.
19
19
  * Generated getters and direct application calls are protected by default. Only ORM
@@ -27,6 +27,13 @@ function getField(entity, fieldName, isInternal = false) {
27
27
  if ((getFieldReadWord(entity, index >>> 5) & 1 << (index & 31)) !== 0) return instanceData.data[fieldName];
28
28
  return readField(entity, instanceData, fieldName, isInternal, index);
29
29
  }
30
+ /**
31
+ * Checks the caller's access to a derived field before recalculating it in trusted context,
32
+ * without reading or caching its value.
33
+ */
34
+ function checkBeforeGetField(entity, field) {
35
+ runFieldReadHooks(entity, require_BaseEntity.getInstanceData(entity), field);
36
+ }
30
37
  /** Reads stored state for ORM bookkeeping without authorizing or warming a public read. */
31
38
  function getStoredField(entity, fieldName) {
32
39
  const instanceData = require_BaseEntity.getInstanceData(entity);
@@ -151,19 +158,25 @@ function readField(entity, instanceData, fieldName, isInternal, index) {
151
158
  /**
152
159
  * Invokes cold-read hooks without letting a reentrant read authorize the outer read.
153
160
  *
154
- * The active-field guard permits synchronous hook reentrancy without caching its approval.
155
- * The entity's read-word descriptors discard untrusted warm-bit writes from the shared read path.
161
+ * This function is solely for `beforeGetField` calls and the behavior is:
162
+ *
163
+ * - visibility-aware EMs (i.e. EMs with an AuthPlugin.canViewEntity hook) get to "pretend"
164
+ * to set the `__readFields` bit all the time, but really we've rewritten `__readFields` to
165
+ * be a getter that _always returns zero_ for untrusted callers, b/c their auth decision
166
+ * could always change.
167
+ * - ordinary EMs only conditionally set the `__readFields` bit, because for them it's a real
168
+ * bit (not a getter), and trusted callers need to leave it unset, so the plugins that are
169
+ * potentially "early-returning/ignoring all trusted callers" get to see the 1st untrusted call.
156
170
  */
157
171
  function runFieldReadHooks(entity, instanceData, fieldName) {
158
172
  const plugins = require_EntityManager.getEmInternalApi(instanceData.em).pluginManager;
159
173
  if (!plugins.hasHook("beforeGetField")) return true;
160
174
  if (instanceData.activeReadFields?.has(fieldName)) return false;
161
- if (instanceData.trustedReadFields && require_trusted.isInTrustedContext()) return true;
162
175
  const active = instanceData.activeReadFields ??= /* @__PURE__ */ new Set();
163
176
  active.add(fieldName);
164
177
  try {
165
178
  plugins.beforeGetField(entity, fieldName);
166
- return true;
179
+ return instanceData.trustedReadFields !== void 0 || !require_trusted.isInTrustedContext();
167
180
  } catch (error) {
168
181
  if (fieldName === "id") instanceData.idCache = void 0;
169
182
  throw error;
@@ -190,6 +203,7 @@ function setFieldReadWord(entity, word, value) {
190
203
  function readWordName(word) {
191
204
  return word === 0 ? "__readFields" : `__readFields${word}`;
192
205
  }
206
+ exports.checkBeforeGetField = checkBeforeGetField;
193
207
  exports.equal = equal;
194
208
  exports.equalArrays = equalArrays;
195
209
  exports.getField = getField;
@@ -1 +1 @@
1
- {"version":3,"file":"fields.cjs","names":["getInstanceData","fail","getBaseMeta","getMetadata","getEmInternalApi","cleanStringValue","isEntity","maybeResolveReferenceToId","maybeRequireTemporal","isInTrustedContext"],"sources":["../src/fields.ts"],"sourcesContent":["import { getInstanceData } from \"src/BaseEntity.ts\";\nimport { type Entity, isEntity } from \"src/Entity.ts\";\nimport { getEmInternalApi } from \"src/EntityManager.ts\";\nimport { type Field, getBaseMeta, getMetadata } from \"src/EntityMetadata.ts\";\nimport { cleanStringValue, ensureNotDeleted, maybeResolveReferenceToId } from \"src/index.ts\";\nimport type { InstanceData } from \"src/InstanceData.ts\";\nimport { maybeRequireTemporal } from \"src/serde/temporal.ts\";\nimport { isInTrustedContext } from \"src/trusted.ts\";\nimport { fail } from \"src/utils.ts\";\n\ntype ReadWordName = \"__readFields\" | `__readFields${number}`;\ntype EntityReadWords = Entity & Record<ReadWordName, number>;\n\n/**\n * Returns the current value of `fieldName`, marking the entity for read locking if the field is configured.\n *\n * Ordinary EMs skip hooks once a field is warm. Visibility-aware EMs\n * check every untrusted read and cache only trusted reads, which skip read hooks.\n *\n * Install plugins before reading entities; adding one later does not replay cached reads.\n * Generated getters and direct application calls are protected by default. Only ORM\n * housekeeping should pass `isInternal`, not domain logic in hooks, rules, or reactions.\n * The field name is a string because generated getters and ORM internals know its type.\n */\nexport function getField(entity: Entity, fieldName: string, isInternal = false): any {\n const instanceData = getInstanceData(entity);\n const index = instanceData.metadata.fieldReadIndexes[fieldName];\n if (typeof index !== \"number\") fail(`Unknown field ${instanceData.metadata.type}.${fieldName}`);\n // Direct getField calls use the same warm-read fast path as generated getters.\n if ((getFieldReadWord(entity, index >>> 5) & (1 << (index & 31))) !== 0) {\n return instanceData.data[fieldName];\n }\n return readField(entity, instanceData, fieldName, isInternal, index);\n}\n\n/** Reads stored state for ORM bookkeeping without authorizing or warming a public read. */\nexport function getStoredField<T = unknown>(entity: Entity, fieldName: string): T {\n const instanceData = getInstanceData(entity);\n const { data, metadata, rowData, rowIndex } = instanceData;\n if (!(fieldName in data) && !instanceData.isNewEntity) {\n const serde = metadata.allFields[fieldName]?.serde ?? fail(`Missing serde for ${fieldName}`);\n data[fieldName] = serde.fromRow(rowData, rowIndex);\n }\n return data[fieldName] as T;\n}\n\n/** Checks stored deletion state without authorizing or warming a public timestamp read. */\nexport function isSoftDeleted(entity: Entity): boolean {\n const fieldName = getBaseMeta(getMetadata(entity)).timestampFields?.deletedAt;\n return fieldName !== undefined && getStoredField(entity, fieldName) !== undefined;\n}\n\n/** Returns whether `fieldName` is a field/column on `entity` that can be changed. */\nexport function isChangeableField(entity: Entity, fieldName: string): boolean {\n return !!getMetadata(entity).allFields[fieldName]?.serde;\n}\n\n/** Returns whether `fieldName` has been set, even if it's undefined, on `entity`. */\nexport function isFieldSet(entity: Entity, fieldName: string): boolean {\n const { data } = getInstanceData(entity);\n if (fieldName in data) return true;\n // Avoid calling `getField` on new entities because it populates the field as a side effect.\n if (entity.isNewEntity) return false;\n // We may not have converted the database column value into domain values yet.\n getField(entity, fieldName, true);\n return fieldName in data;\n}\n\n/**\n * Sets the current value of `fieldName`, this is an internal method that should\n * only be called by the code-generated setters.\n *\n * We skip any typing like `fieldName: keyof T` because this method should only be\n * called by trusted codegen anyway.\n *\n * Returns `true` if the value was changed, or `false` if it was a noop.\n */\nexport function setField(entity: Entity, fieldName: string, newValue: any): boolean {\n ensureNotDeleted(entity, \"pending\");\n const { em } = entity;\n const api = getEmInternalApi(em);\n const { rm, pluginManager, indexManager, fieldLogger, isLoadedCache } = api;\n\n // If we're flushing, only allow writes from hooks\n api.checkWritesAllowed();\n\n const instanceData = getInstanceData(entity);\n const { data, originalData, flushedData } = instanceData;\n\n // Do string sanitization\n const field = getMetadata(entity).allFields[fieldName];\n if (field.kind === \"primitive\" && field.type === \"string\" && field.sanitize !== false) {\n newValue = cleanStringValue(newValue);\n }\n\n const currentValue = getField(entity, fieldName, true);\n const isReference = field.kind === \"m2o\" || field.kind === \"poly\";\n const currentEqualsNew = fieldValueEquals(field, currentValue, newValue);\n\n // Tell any `#isLoaded` or `#value` caches that they might be stale, but only\n // after we've checked if the current value changed. Also we do it here,\n // before the \"reverting a dirty value to the original\" check below,\n // because caches might have already observed the dirty value, so would\n // still need to refresh.\n if (!currentEqualsNew) isLoadedCache.resetIsLoaded(entity, fieldName);\n\n // Check `config.setTransitions` tables while the change is still synchronous, before we change anything,\n // and record the transition for `em.flush` to run its (async) guards and reactions\n if (field.kind === \"enum\" && !currentEqualsNew) rm.queueTransition(entity, fieldName, currentValue, newValue);\n // Remember every prior reference value so `followReverseHint` can rewalk both original and transient owners.\n if (isReference && !currentEqualsNew) {\n instanceData.rememberReferenceValue(fieldName, currentValue);\n }\n\n // If a `set` occurs during the AsyncReactiveField-loop, copy the last-flushed value to flushedData.\n // Then our `pendingOperation` logic can tell \"do we need another micro-flush?\" separately\n // from our public-facing changed fields logic.\n if (flushedData) {\n if (fieldName in flushedData) {\n // We've already copied the last-micro-flush value into flushedData,\n // are we changing back to that? If so, we won't need another micro-flush.\n if (equalOrSameEntity(flushedData[fieldName], newValue)) {\n delete flushedData[fieldName];\n } else {\n // Otherwise just let data[fieldName] get the even-newer value, and keep\n // flushedData[fieldName] as the last-micro-flushed value.\n }\n } else if (!currentEqualsNew) {\n // This is the 1st rqf-loop change for this field, so let data[fieldName]\n // get the even newer value, but keep the last-micro-flushed value in flushedData.\n flushedData[fieldName] = currentValue;\n }\n }\n\n // \"Un-dirty\" our originalData if newValue is reverting to originalData\n if (fieldName in originalData) {\n if (fieldValueEquals(field, originalData[fieldName], newValue)) {\n indexManager.maybeUpdateFieldIndex(entity, fieldName, currentValue, newValue);\n\n pluginManager.beforeSetField(entity, fieldName, newValue);\n data[fieldName] = newValue;\n if (instanceData.flushHooksCurrent && !(\"derived\" in field && field.derived === \"sync\"))\n instanceData.flushHooksCurrent = false;\n instanceData.markFieldClean(fieldName);\n\n fieldLogger.logSet(entity, fieldName, newValue);\n if (isReference && instanceData.getReferenceHistory(fieldName).length > 0) {\n rm.queueDownstreamReactables(entity, fieldName);\n } else {\n // For normal reverts, the field is clean again, so any pending downstream work can be removed.\n rm.dequeueDownstreamReactables(entity, fieldName);\n }\n\n return true;\n }\n }\n\n // Push this logic into a field serde type abstraction?\n if (currentEqualsNew) {\n // If we're doing `entity.field = undefined`, we'll be equal, but mark ourselves as \"set\"\n // so that defaults know to respect the intent of keeping this field undefined.\n if (!(fieldName in data)) data[fieldName] = undefined;\n return false;\n }\n\n // Only save the currentValue on the 1st change of this field\n if (!(fieldName in originalData)) {\n instanceData.markFieldDirty(fieldName, currentValue);\n }\n fieldLogger.logSet(entity, fieldName, newValue);\n rm.queueDownstreamReactables(entity, fieldName);\n\n indexManager.maybeUpdateFieldIndex(entity, fieldName, currentValue, newValue);\n\n pluginManager.beforeSetField(entity, fieldName, newValue);\n data[fieldName] = newValue;\n // Writing back a synchronous getter after hooks does not change what the hooks already saw.\n if (instanceData.flushHooksCurrent && !(\"derived\" in field && field.derived === \"sync\"))\n instanceData.flushHooksCurrent = false;\n return true;\n}\n\nfunction fieldValueEquals(field: Field, a: unknown, b: unknown): boolean {\n // Primitive scalar sets are the common path, so avoid Date/Temporal/entity checks when both values cannot need them.\n if (field.kind !== \"m2o\" && field.kind !== \"poly\" && isNonObjectValue(a) && isNonObjectValue(b)) return a === b;\n return equalOrSameEntity(a, b);\n}\n\nfunction isNonObjectValue(value: unknown): boolean {\n return value === null || typeof value !== \"object\";\n}\n\nfunction equalOrSameEntity(a: any, b: any): boolean {\n return (\n equal(a, b) ||\n (Array.isArray(a) && Array.isArray(b) && equalArrays(a, b)) ||\n // This is kind of gross, but make sure not to compare two both-new entities\n (((isEntity(a) && !a.isNewEntity) || (isEntity(b) && !b.isNewEntity)) &&\n maybeResolveReferenceToId(a) === maybeResolveReferenceToId(b))\n );\n}\n\nexport function equalArrays(a: any[], b: any[]): boolean {\n if (a.length !== b.length) return false;\n return a.every((_: any, i) => equal(a[i], b[i]));\n}\n\nconst Temporal = maybeRequireTemporal()?.Temporal;\nexport function equal(a: any, b: any): boolean {\n if (a === b) return true;\n if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n if (Temporal) {\n if (a instanceof Temporal.ZonedDateTime && b instanceof Temporal.ZonedDateTime) return a.equals(b);\n if (a instanceof Temporal.PlainDateTime && b instanceof Temporal.PlainDateTime) return a.equals(b);\n if (a instanceof Temporal.PlainDate && b instanceof Temporal.PlainDate) return a.equals(b);\n }\n return false;\n}\n\n/**\n * Performs read callbacks, protection, and lazy conversion before publishing the warm-read bit.\n *\n * Reentrant reads may inspect the value, but only the outer read can publish a warm bit\n * after its hooks succeed.\n */\nfunction readField(\n entity: Entity,\n instanceData: InstanceData,\n fieldName: string,\n isInternal: boolean,\n index: number,\n): any {\n const { em, metadata } = instanceData;\n // Ordinary EMs pay this check only until the field is warm; subsequent reads skip this path.\n const shouldMarkReadField = runFieldReadHooks(entity, instanceData, fieldName);\n\n const field = metadata.allFields[fieldName];\n if (!isInternal && field?.assertUnchanged) em.assertUnchanged(entity);\n // Hooks may replace a cached value, so inspect current storage only after they finish.\n const { data } = instanceData;\n if (!(fieldName in data) && !instanceData.isNewEntity) {\n // We may not have converted the database column value into domain values yet.\n const serde = field?.serde ?? fail(`Missing serde for ${fieldName}`);\n data[fieldName] = serde.fromRow(instanceData.rowData, instanceData.rowIndex);\n }\n // IDs are always assigned into data.id, so even their unassigned reads can stay warm.\n // Other unset new fields stay cold: inserts may supply defaults later, without a read\n // turning into an explicit `undefined` for defaults/isFieldSet.\n if (shouldMarkReadField && (fieldName === \"id\" || fieldName in data) && (!isInternal || !field?.assertUnchanged)) {\n markApplicationReadField(entity, index, true);\n }\n return data[fieldName];\n}\n\n/**\n * Invokes cold-read hooks without letting a reentrant read authorize the outer read.\n *\n * The active-field guard permits synchronous hook reentrancy without caching its approval.\n * The entity's read-word descriptors discard untrusted warm-bit writes from the shared read path.\n */\nfunction runFieldReadHooks(entity: Entity, instanceData: InstanceData, fieldName: string): boolean {\n const plugins = getEmInternalApi(instanceData.em).pluginManager;\n if (!plugins.hasHook(\"beforeGetField\")) return true;\n\n if (instanceData.activeReadFields?.has(fieldName)) return false;\n if (instanceData.trustedReadFields && isInTrustedContext()) return true;\n const active = (instanceData.activeReadFields ??= new Set<string>());\n active.add(fieldName);\n try {\n plugins.beforeGetField(entity, fieldName);\n return true;\n } catch (error) {\n // A reentrant ID getter may have cached a conversion before the outer hook failed.\n if (fieldName === \"id\") instanceData.idCache = undefined;\n throw error;\n } finally {\n active.delete(fieldName);\n }\n}\n\n/** Tests a field bit without allocating the extra words for small entity types. */\nfunction hasReadField(first: number, extra: readonly number[] | undefined, index: number): boolean {\n const word = index < 32 ? first : (extra?.[(index >>> 5) - 1] ?? 0);\n return (word & (1 << (index & 31))) !== 0;\n}\n\n/** Changes the entity's warm-read bit without disturbing other fields in that word. */\nfunction markApplicationReadField(entity: Entity, index: number, read: boolean): void {\n const bit = 1 << (index & 31);\n const word = index >>> 5;\n const value = getFieldReadWord(entity, word);\n setFieldReadWord(entity, word, read ? value | bit : value & ~bit);\n}\n\n/** Reads the same warm-read words used by generated getters. */\nfunction getFieldReadWord(entity: Entity, word: number): number {\n return (entity as EntityReadWords)[readWordName(word)];\n}\n\n/** Updates a warm-read word without exposing an entity API. */\nfunction setFieldReadWord(entity: Entity, word: number, value: number): void {\n (entity as EntityReadWords)[readWordName(word)] = value;\n}\n\n/** Matches the literal names emitted by codegen; only shared reads construct a word name. */\nfunction readWordName(word: number): ReadWordName {\n return word === 0 ? \"__readFields\" : `__readFields${word}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,SAAS,QAAgB,WAAmB,aAAa,OAAY;CACnF,MAAM,eAAeA,mBAAAA,gBAAgB,MAAM;CAC3C,MAAM,QAAQ,aAAa,SAAS,iBAAiB;CACrD,IAAI,OAAO,UAAU,UAAU,cAAA,KAAK,iBAAiB,aAAa,SAAS,KAAK,GAAG,WAAW;CAE9F,KAAK,iBAAiB,QAAQ,UAAU,CAAC,IAAK,MAAM,QAAQ,S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,MAAqB;CACpF,MAAM,MAAM,MAAM,QAAQ;CAC1B,MAAM,OAAO,UAAU;CACvB,MAAM,QAAQ,iBAAiB,QAAQ,IAAI;CAC3C,iBAAiB,QAAQ,MAAM,OAAO,QAAQ,MAAM,QAAQ,CAAC,GAAG;AAClE;;AAGA,SAAS,iBAAiB,QAAgB,MAAsB;CAC9D,OAAQ,OAA2B,aAAa,IAAI;AACtD;;AAGA,SAAS,iBAAiB,QAAgB,MAAc,OAAqB;CAC3E,OAA4B,aAAa,IAAI,KAAK;AACpD;;AAGA,SAAS,aAAa,MAA4B;CAChD,OAAO,SAAS,IAAI,iBAAiB,eAAe;AACtD"}
1
+ {"version":3,"file":"fields.cjs","names":["getInstanceData","fail","getBaseMeta","getMetadata","getEmInternalApi","cleanStringValue","isEntity","maybeResolveReferenceToId","maybeRequireTemporal","isInTrustedContext"],"sources":["../src/fields.ts"],"sourcesContent":["import { getInstanceData } from \"src/BaseEntity.ts\";\nimport { type Entity, isEntity } from \"src/Entity.ts\";\nimport { getEmInternalApi } from \"src/EntityManager.ts\";\nimport { type Field, getBaseMeta, getMetadata } from \"src/EntityMetadata.ts\";\nimport { cleanStringValue, ensureNotDeleted, maybeResolveReferenceToId } from \"src/index.ts\";\nimport type { InstanceData } from \"src/InstanceData.ts\";\nimport { maybeRequireTemporal } from \"src/serde/temporal.ts\";\nimport { isInTrustedContext } from \"src/trusted.ts\";\nimport { fail } from \"src/utils.ts\";\n\ntype ReadWordName = \"__readFields\" | `__readFields${number}`;\ntype EntityReadWords = Entity & Record<ReadWordName, number>;\n\n/**\n * Returns the current value of `fieldName`, marking the entity for read locking if the field is configured.\n *\n * Ordinary EMs skip hooks once a field is warm. Visibility-aware EMs\n * check every untrusted read and cache trusted reads separately.\n *\n * Install plugins before reading entities; adding one later does not replay cached reads.\n * Generated getters and direct application calls are protected by default. Only ORM\n * housekeeping should pass `isInternal`, not domain logic in hooks, rules, or reactions.\n * The field name is a string because generated getters and ORM internals know its type.\n */\nexport function getField(entity: Entity, fieldName: string, isInternal = false): any {\n const instanceData = getInstanceData(entity);\n const index = instanceData.metadata.fieldReadIndexes[fieldName];\n if (typeof index !== \"number\") fail(`Unknown field ${instanceData.metadata.type}.${fieldName}`);\n // Direct getField calls use the same warm-read fast path as generated getters.\n if ((getFieldReadWord(entity, index >>> 5) & (1 << (index & 31))) !== 0) {\n return instanceData.data[fieldName];\n }\n return readField(entity, instanceData, fieldName, isInternal, index);\n}\n\n/**\n * Checks the caller's access to a derived field before recalculating it in trusted context,\n * without reading or caching its value.\n */\nexport function checkBeforeGetField(entity: Entity, field: string): void {\n runFieldReadHooks(entity, getInstanceData(entity), field);\n}\n\n/** Reads stored state for ORM bookkeeping without authorizing or warming a public read. */\nexport function getStoredField<T = unknown>(entity: Entity, fieldName: string): T {\n const instanceData = getInstanceData(entity);\n const { data, metadata, rowData, rowIndex } = instanceData;\n if (!(fieldName in data) && !instanceData.isNewEntity) {\n const serde = metadata.allFields[fieldName]?.serde ?? fail(`Missing serde for ${fieldName}`);\n data[fieldName] = serde.fromRow(rowData, rowIndex);\n }\n return data[fieldName] as T;\n}\n\n/** Checks stored deletion state without authorizing or warming a public timestamp read. */\nexport function isSoftDeleted(entity: Entity): boolean {\n const fieldName = getBaseMeta(getMetadata(entity)).timestampFields?.deletedAt;\n return fieldName !== undefined && getStoredField(entity, fieldName) !== undefined;\n}\n\n/** Returns whether `fieldName` is a field/column on `entity` that can be changed. */\nexport function isChangeableField(entity: Entity, fieldName: string): boolean {\n return !!getMetadata(entity).allFields[fieldName]?.serde;\n}\n\n/** Returns whether `fieldName` has been set, even if it's undefined, on `entity`. */\nexport function isFieldSet(entity: Entity, fieldName: string): boolean {\n const { data } = getInstanceData(entity);\n if (fieldName in data) return true;\n // Avoid calling `getField` on new entities because it populates the field as a side effect.\n if (entity.isNewEntity) return false;\n // We may not have converted the database column value into domain values yet.\n getField(entity, fieldName, true);\n return fieldName in data;\n}\n\n/**\n * Sets the current value of `fieldName`, this is an internal method that should\n * only be called by the code-generated setters.\n *\n * We skip any typing like `fieldName: keyof T` because this method should only be\n * called by trusted codegen anyway.\n *\n * Returns `true` if the value was changed, or `false` if it was a noop.\n */\nexport function setField(entity: Entity, fieldName: string, newValue: any): boolean {\n ensureNotDeleted(entity, \"pending\");\n const { em } = entity;\n const api = getEmInternalApi(em);\n const { rm, pluginManager, indexManager, fieldLogger, isLoadedCache } = api;\n\n // If we're flushing, only allow writes from hooks\n api.checkWritesAllowed();\n\n const instanceData = getInstanceData(entity);\n const { data, originalData, flushedData } = instanceData;\n\n // Do string sanitization\n const field = getMetadata(entity).allFields[fieldName];\n if (field.kind === \"primitive\" && field.type === \"string\" && field.sanitize !== false) {\n newValue = cleanStringValue(newValue);\n }\n\n const currentValue = getField(entity, fieldName, true);\n const isReference = field.kind === \"m2o\" || field.kind === \"poly\";\n const currentEqualsNew = fieldValueEquals(field, currentValue, newValue);\n\n // Tell any `#isLoaded` or `#value` caches that they might be stale, but only\n // after we've checked if the current value changed. Also we do it here,\n // before the \"reverting a dirty value to the original\" check below,\n // because caches might have already observed the dirty value, so would\n // still need to refresh.\n if (!currentEqualsNew) isLoadedCache.resetIsLoaded(entity, fieldName);\n\n // Check `config.setTransitions` tables while the change is still synchronous, before we change anything,\n // and record the transition for `em.flush` to run its (async) guards and reactions\n if (field.kind === \"enum\" && !currentEqualsNew) rm.queueTransition(entity, fieldName, currentValue, newValue);\n // Remember every prior reference value so `followReverseHint` can rewalk both original and transient owners.\n if (isReference && !currentEqualsNew) {\n instanceData.rememberReferenceValue(fieldName, currentValue);\n }\n\n // If a `set` occurs during the AsyncReactiveField-loop, copy the last-flushed value to flushedData.\n // Then our `pendingOperation` logic can tell \"do we need another micro-flush?\" separately\n // from our public-facing changed fields logic.\n if (flushedData) {\n if (fieldName in flushedData) {\n // We've already copied the last-micro-flush value into flushedData,\n // are we changing back to that? If so, we won't need another micro-flush.\n if (equalOrSameEntity(flushedData[fieldName], newValue)) {\n delete flushedData[fieldName];\n } else {\n // Otherwise just let data[fieldName] get the even-newer value, and keep\n // flushedData[fieldName] as the last-micro-flushed value.\n }\n } else if (!currentEqualsNew) {\n // This is the 1st rqf-loop change for this field, so let data[fieldName]\n // get the even newer value, but keep the last-micro-flushed value in flushedData.\n flushedData[fieldName] = currentValue;\n }\n }\n\n // \"Un-dirty\" our originalData if newValue is reverting to originalData\n if (fieldName in originalData) {\n if (fieldValueEquals(field, originalData[fieldName], newValue)) {\n indexManager.maybeUpdateFieldIndex(entity, fieldName, currentValue, newValue);\n\n pluginManager.beforeSetField(entity, fieldName, newValue);\n data[fieldName] = newValue;\n if (instanceData.flushHooksCurrent && !(\"derived\" in field && field.derived === \"sync\"))\n instanceData.flushHooksCurrent = false;\n instanceData.markFieldClean(fieldName);\n\n fieldLogger.logSet(entity, fieldName, newValue);\n if (isReference && instanceData.getReferenceHistory(fieldName).length > 0) {\n rm.queueDownstreamReactables(entity, fieldName);\n } else {\n // For normal reverts, the field is clean again, so any pending downstream work can be removed.\n rm.dequeueDownstreamReactables(entity, fieldName);\n }\n\n return true;\n }\n }\n\n // Push this logic into a field serde type abstraction?\n if (currentEqualsNew) {\n // If we're doing `entity.field = undefined`, we'll be equal, but mark ourselves as \"set\"\n // so that defaults know to respect the intent of keeping this field undefined.\n if (!(fieldName in data)) data[fieldName] = undefined;\n return false;\n }\n\n // Only save the currentValue on the 1st change of this field\n if (!(fieldName in originalData)) {\n instanceData.markFieldDirty(fieldName, currentValue);\n }\n fieldLogger.logSet(entity, fieldName, newValue);\n rm.queueDownstreamReactables(entity, fieldName);\n\n indexManager.maybeUpdateFieldIndex(entity, fieldName, currentValue, newValue);\n\n pluginManager.beforeSetField(entity, fieldName, newValue);\n data[fieldName] = newValue;\n // Writing back a synchronous getter after hooks does not change what the hooks already saw.\n if (instanceData.flushHooksCurrent && !(\"derived\" in field && field.derived === \"sync\"))\n instanceData.flushHooksCurrent = false;\n return true;\n}\n\nfunction fieldValueEquals(field: Field, a: unknown, b: unknown): boolean {\n // Primitive scalar sets are the common path, so avoid Date/Temporal/entity checks when both values cannot need them.\n if (field.kind !== \"m2o\" && field.kind !== \"poly\" && isNonObjectValue(a) && isNonObjectValue(b)) return a === b;\n return equalOrSameEntity(a, b);\n}\n\nfunction isNonObjectValue(value: unknown): boolean {\n return value === null || typeof value !== \"object\";\n}\n\nfunction equalOrSameEntity(a: any, b: any): boolean {\n return (\n equal(a, b) ||\n (Array.isArray(a) && Array.isArray(b) && equalArrays(a, b)) ||\n // This is kind of gross, but make sure not to compare two both-new entities\n (((isEntity(a) && !a.isNewEntity) || (isEntity(b) && !b.isNewEntity)) &&\n maybeResolveReferenceToId(a) === maybeResolveReferenceToId(b))\n );\n}\n\nexport function equalArrays(a: any[], b: any[]): boolean {\n if (a.length !== b.length) return false;\n return a.every((_: any, i) => equal(a[i], b[i]));\n}\n\nconst Temporal = maybeRequireTemporal()?.Temporal;\nexport function equal(a: any, b: any): boolean {\n if (a === b) return true;\n if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n if (Temporal) {\n if (a instanceof Temporal.ZonedDateTime && b instanceof Temporal.ZonedDateTime) return a.equals(b);\n if (a instanceof Temporal.PlainDateTime && b instanceof Temporal.PlainDateTime) return a.equals(b);\n if (a instanceof Temporal.PlainDate && b instanceof Temporal.PlainDate) return a.equals(b);\n }\n return false;\n}\n\n/**\n * Performs read callbacks, protection, and lazy conversion before publishing the warm-read bit.\n *\n * Reentrant reads may inspect the value, but only the outer read can publish a warm bit\n * after its hooks succeed.\n */\nfunction readField(\n entity: Entity,\n instanceData: InstanceData,\n fieldName: string,\n isInternal: boolean,\n index: number,\n): any {\n const { em, metadata } = instanceData;\n // Ordinary EMs pay this check only once, as once its __readFields bit is set, then\n // getField/readField is never called on subsequent getter calls.\n const shouldMarkReadField = runFieldReadHooks(entity, instanceData, fieldName);\n\n const field = metadata.allFields[fieldName];\n if (!isInternal && field?.assertUnchanged) em.assertUnchanged(entity);\n // Hooks may replace a cached value, so inspect current storage only after they finish.\n const { data } = instanceData;\n if (!(fieldName in data) && !instanceData.isNewEntity) {\n // We may not have converted the database column value into domain values yet.\n const serde = field?.serde ?? fail(`Missing serde for ${fieldName}`);\n data[fieldName] = serde.fromRow(instanceData.rowData, instanceData.rowIndex);\n }\n // IDs are always assigned into data.id, so even their unassigned reads can stay warm.\n // Other unset new fields stay cold: inserts may supply defaults later, without a read\n // turning into an explicit `undefined` for defaults/isFieldSet.\n if (shouldMarkReadField && (fieldName === \"id\" || fieldName in data) && (!isInternal || !field?.assertUnchanged)) {\n markApplicationReadField(entity, index, true);\n }\n return data[fieldName];\n}\n\n/**\n * Invokes cold-read hooks without letting a reentrant read authorize the outer read.\n *\n * This function is solely for `beforeGetField` calls and the behavior is:\n *\n * - visibility-aware EMs (i.e. EMs with an AuthPlugin.canViewEntity hook) get to \"pretend\"\n * to set the `__readFields` bit all the time, but really we've rewritten `__readFields` to\n * be a getter that _always returns zero_ for untrusted callers, b/c their auth decision\n * could always change.\n * - ordinary EMs only conditionally set the `__readFields` bit, because for them it's a real\n * bit (not a getter), and trusted callers need to leave it unset, so the plugins that are\n * potentially \"early-returning/ignoring all trusted callers\" get to see the 1st untrusted call.\n */\nfunction runFieldReadHooks(entity: Entity, instanceData: InstanceData, fieldName: string): boolean {\n const plugins = getEmInternalApi(instanceData.em).pluginManager;\n if (!plugins.hasHook(\"beforeGetField\")) return true;\n\n if (instanceData.activeReadFields?.has(fieldName)) return false;\n const active = (instanceData.activeReadFields ??= new Set<string>());\n active.add(fieldName);\n try {\n plugins.beforeGetField(entity, fieldName);\n\n // Decide whether we can set the __readFields bit, see jsdocs above.\n const isVisAwareEm = instanceData.trustedReadFields !== undefined;\n return isVisAwareEm || !isInTrustedContext();\n } catch (error) {\n // A reentrant ID getter may have cached a conversion before the outer hook failed.\n if (fieldName === \"id\") instanceData.idCache = undefined;\n throw error;\n } finally {\n active.delete(fieldName);\n }\n}\n\n/** Tests a field bit without allocating the extra words for small entity types. */\nfunction hasReadField(first: number, extra: readonly number[] | undefined, index: number): boolean {\n const word = index < 32 ? first : (extra?.[(index >>> 5) - 1] ?? 0);\n return (word & (1 << (index & 31))) !== 0;\n}\n\n/** Changes the entity's warm-read bit without disturbing other fields in that word. */\nfunction markApplicationReadField(entity: Entity, index: number, read: boolean): void {\n const bit = 1 << (index & 31);\n const word = index >>> 5;\n const value = getFieldReadWord(entity, word);\n setFieldReadWord(entity, word, read ? value | bit : value & ~bit);\n}\n\n/** Reads the same warm-read words used by generated getters. */\nfunction getFieldReadWord(entity: Entity, word: number): number {\n return (entity as EntityReadWords)[readWordName(word)];\n}\n\n/** Updates a warm-read word without exposing an entity API. */\nfunction setFieldReadWord(entity: Entity, word: number, value: number): void {\n (entity as EntityReadWords)[readWordName(word)] = value;\n}\n\n/** Matches the literal names emitted by codegen; only shared reads construct a word name. */\nfunction readWordName(word: number): ReadWordName {\n return word === 0 ? \"__readFields\" : `__readFields${word}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,SAAS,QAAgB,WAAmB,aAAa,OAAY;CACnF,MAAM,eAAeA,mBAAAA,gBAAgB,MAAM;CAC3C,MAAM,QAAQ,aAAa,SAAS,iBAAiB;CACrD,IAAI,OAAO,UAAU,UAAU,cAAA,KAAK,iBAAiB,aAAa,SAAS,KAAK,GAAG,WAAW;CAE9F,KAAK,iBAAiB,QAAQ,UAAU,CAAC,IAAK,MAAM,QAAQ,SAAU,GACpE,OAAO,aAAa,KAAK;CAE3B,OAAO,UAAU,QAAQ,cAAc,WAAW,YAAY,KAAK;AACrE;;;;;AAMA,SAAgB,oBAAoB,QAAgB,OAAqB;CACvE,kBAAkB,QAAQA,mBAAAA,gBAAgB,MAAM,GAAG,KAAK;AAC1D;;AAGA,SAAgB,eAA4B,QAAgB,WAAsB;CAChF,MAAM,eAAeA,mBAAAA,gBAAgB,MAAM;CAC3C,MAAM,EAAE,MAAM,UAAU,SAAS,aAAa;CAC9C,IAAI,EAAE,aAAa,SAAS,CAAC,aAAa,aAExC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ACtD;;AAGA,SAAS,iBAAiB,QAAgB,MAAc,OAAqB;CAC3E,OAA4B,aAAa,IAAI,KAAK;AACpD;;AAGA,SAAS,aAAa,MAA4B;CAChD,OAAO,SAAS,IAAI,iBAAiB,eAAe;AACtD"}
@@ -3,7 +3,7 @@ import { Entity } from "./Entity.cjs";
3
3
  * Returns the current value of `fieldName`, marking the entity for read locking if the field is configured.
4
4
  *
5
5
  * Ordinary EMs skip hooks once a field is warm. Visibility-aware EMs
6
- * check every untrusted read and cache only trusted reads, which skip read hooks.
6
+ * check every untrusted read and cache trusted reads separately.
7
7
  *
8
8
  * Install plugins before reading entities; adding one later does not replay cached reads.
9
9
  * Generated getters and direct application calls are protected by default. Only ORM
@@ -11,6 +11,11 @@ import { Entity } from "./Entity.cjs";
11
11
  * The field name is a string because generated getters and ORM internals know its type.
12
12
  */
13
13
  export declare function getField(entity: Entity, fieldName: string, isInternal?: boolean): any;
14
+ /**
15
+ * Checks the caller's access to a derived field before recalculating it in trusted context,
16
+ * without reading or caching its value.
17
+ */
18
+ export declare function checkBeforeGetField(entity: Entity, field: string): void;
14
19
  /** Reads stored state for ORM bookkeeping without authorizing or warming a public read. */
15
20
  export declare function getStoredField<T = unknown>(entity: Entity, fieldName: string): T;
16
21
  /** Checks stored deletion state without authorizing or warming a public timestamp read. */
@@ -1 +1 @@
1
- {"version":3,"file":"fields.d.cts","names":[],"sources":["../src/fields.ts"],"mappings":";;;;;;;;;;;;wBAwBgB,SAAS,QAAQ,QAAQ,mBAAmB;;wBAY5C,eAAe,aAAa,QAAQ,QAAQ,oBAAoB;;wBAWhE,cAAc,QAAQ;;wBAMtB,kBAAkB,QAAQ,QAAQ;;wBAKlC,WAAW,QAAQ,QAAQ;;;;;;;;;;wBAmB3B,SAAS,QAAQ,QAAQ,mBAAmB;wBA6H5C,YAAY,UAAU;wBAMtB,MAAM,QAAQ"}
1
+ {"version":3,"file":"fields.d.cts","names":[],"sources":["../src/fields.ts"],"mappings":";;;;;;;;;;;;wBAwBgB,SAAS,QAAQ,QAAQ,mBAAmB;;;;;wBAe5C,oBAAoB,QAAQ,QAAQ;;wBAKpC,eAAe,aAAa,QAAQ,QAAQ,oBAAoB;;wBAWhE,cAAc,QAAQ;;wBAMtB,kBAAkB,QAAQ,QAAQ;;wBAKlC,WAAW,QAAQ,QAAQ;;;;;;;;;;wBAmB3B,SAAS,QAAQ,QAAQ,mBAAmB;wBA6H5C,YAAY,UAAU;wBAMtB,MAAM,QAAQ"}
@@ -3,7 +3,7 @@ import { Entity } from "./Entity.mjs";
3
3
  * Returns the current value of `fieldName`, marking the entity for read locking if the field is configured.
4
4
  *
5
5
  * Ordinary EMs skip hooks once a field is warm. Visibility-aware EMs
6
- * check every untrusted read and cache only trusted reads, which skip read hooks.
6
+ * check every untrusted read and cache trusted reads separately.
7
7
  *
8
8
  * Install plugins before reading entities; adding one later does not replay cached reads.
9
9
  * Generated getters and direct application calls are protected by default. Only ORM
@@ -11,6 +11,11 @@ import { Entity } from "./Entity.mjs";
11
11
  * The field name is a string because generated getters and ORM internals know its type.
12
12
  */
13
13
  export declare function getField(entity: Entity, fieldName: string, isInternal?: boolean): any;
14
+ /**
15
+ * Checks the caller's access to a derived field before recalculating it in trusted context,
16
+ * without reading or caching its value.
17
+ */
18
+ export declare function checkBeforeGetField(entity: Entity, field: string): void;
14
19
  /** Reads stored state for ORM bookkeeping without authorizing or warming a public read. */
15
20
  export declare function getStoredField<T = unknown>(entity: Entity, fieldName: string): T;
16
21
  /** Checks stored deletion state without authorizing or warming a public timestamp read. */
@@ -1 +1 @@
1
- {"version":3,"file":"fields.d.mts","names":[],"sources":["../src/fields.ts"],"mappings":";;;;;;;;;;;;wBAwBgB,SAAS,QAAQ,QAAQ,mBAAmB;;wBAY5C,eAAe,aAAa,QAAQ,QAAQ,oBAAoB;;wBAWhE,cAAc,QAAQ;;wBAMtB,kBAAkB,QAAQ,QAAQ;;wBAKlC,WAAW,QAAQ,QAAQ;;;;;;;;;;wBAmB3B,SAAS,QAAQ,QAAQ,mBAAmB;wBA6H5C,YAAY,UAAU;wBAMtB,MAAM,QAAQ"}
1
+ {"version":3,"file":"fields.d.mts","names":[],"sources":["../src/fields.ts"],"mappings":";;;;;;;;;;;;wBAwBgB,SAAS,QAAQ,QAAQ,mBAAmB;;;;;wBAe5C,oBAAoB,QAAQ,QAAQ;;wBAKpC,eAAe,aAAa,QAAQ,QAAQ,oBAAoB;;wBAWhE,cAAc,QAAQ;;wBAMtB,kBAAkB,QAAQ,QAAQ;;wBAKlC,WAAW,QAAQ,QAAQ;;;;;;;;;;wBAmB3B,SAAS,QAAQ,QAAQ,mBAAmB;wBA6H5C,YAAY,UAAU;wBAMtB,MAAM,QAAQ"}
package/build/fields.js CHANGED
@@ -12,7 +12,7 @@ import { cleanStringValue, fail } from "./utils.js";
12
12
  * Returns the current value of `fieldName`, marking the entity for read locking if the field is configured.
13
13
  *
14
14
  * Ordinary EMs skip hooks once a field is warm. Visibility-aware EMs
15
- * check every untrusted read and cache only trusted reads, which skip read hooks.
15
+ * check every untrusted read and cache trusted reads separately.
16
16
  *
17
17
  * Install plugins before reading entities; adding one later does not replay cached reads.
18
18
  * Generated getters and direct application calls are protected by default. Only ORM
@@ -26,6 +26,13 @@ function getField(entity, fieldName, isInternal = false) {
26
26
  if ((getFieldReadWord(entity, index >>> 5) & 1 << (index & 31)) !== 0) return instanceData.data[fieldName];
27
27
  return readField(entity, instanceData, fieldName, isInternal, index);
28
28
  }
29
+ /**
30
+ * Checks the caller's access to a derived field before recalculating it in trusted context,
31
+ * without reading or caching its value.
32
+ */
33
+ function checkBeforeGetField(entity, field) {
34
+ runFieldReadHooks(entity, getInstanceData(entity), field);
35
+ }
29
36
  /** Reads stored state for ORM bookkeeping without authorizing or warming a public read. */
30
37
  function getStoredField(entity, fieldName) {
31
38
  const instanceData = getInstanceData(entity);
@@ -150,19 +157,25 @@ function readField(entity, instanceData, fieldName, isInternal, index) {
150
157
  /**
151
158
  * Invokes cold-read hooks without letting a reentrant read authorize the outer read.
152
159
  *
153
- * The active-field guard permits synchronous hook reentrancy without caching its approval.
154
- * The entity's read-word descriptors discard untrusted warm-bit writes from the shared read path.
160
+ * This function is solely for `beforeGetField` calls and the behavior is:
161
+ *
162
+ * - visibility-aware EMs (i.e. EMs with an AuthPlugin.canViewEntity hook) get to "pretend"
163
+ * to set the `__readFields` bit all the time, but really we've rewritten `__readFields` to
164
+ * be a getter that _always returns zero_ for untrusted callers, b/c their auth decision
165
+ * could always change.
166
+ * - ordinary EMs only conditionally set the `__readFields` bit, because for them it's a real
167
+ * bit (not a getter), and trusted callers need to leave it unset, so the plugins that are
168
+ * potentially "early-returning/ignoring all trusted callers" get to see the 1st untrusted call.
155
169
  */
156
170
  function runFieldReadHooks(entity, instanceData, fieldName) {
157
171
  const plugins = getEmInternalApi(instanceData.em).pluginManager;
158
172
  if (!plugins.hasHook("beforeGetField")) return true;
159
173
  if (instanceData.activeReadFields?.has(fieldName)) return false;
160
- if (instanceData.trustedReadFields && isInTrustedContext()) return true;
161
174
  const active = instanceData.activeReadFields ??= /* @__PURE__ */ new Set();
162
175
  active.add(fieldName);
163
176
  try {
164
177
  plugins.beforeGetField(entity, fieldName);
165
- return true;
178
+ return instanceData.trustedReadFields !== void 0 || !isInTrustedContext();
166
179
  } catch (error) {
167
180
  if (fieldName === "id") instanceData.idCache = void 0;
168
181
  throw error;
@@ -189,6 +202,6 @@ function setFieldReadWord(entity, word, value) {
189
202
  function readWordName(word) {
190
203
  return word === 0 ? "__readFields" : `__readFields${word}`;
191
204
  }
192
- export { equal, equalArrays, getField, getStoredField, isChangeableField, isFieldSet, isSoftDeleted, setField };
205
+ export { checkBeforeGetField, equal, equalArrays, getField, getStoredField, isChangeableField, isFieldSet, isSoftDeleted, setField };
193
206
 
194
207
  //# sourceMappingURL=fields.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"fields.js","names":[],"sources":["../src/fields.ts"],"sourcesContent":["import { getInstanceData } from \"src/BaseEntity.ts\";\nimport { type Entity, isEntity } from \"src/Entity.ts\";\nimport { getEmInternalApi } from \"src/EntityManager.ts\";\nimport { type Field, getBaseMeta, getMetadata } from \"src/EntityMetadata.ts\";\nimport { cleanStringValue, ensureNotDeleted, maybeResolveReferenceToId } from \"src/index.ts\";\nimport type { InstanceData } from \"src/InstanceData.ts\";\nimport { maybeRequireTemporal } from \"src/serde/temporal.ts\";\nimport { isInTrustedContext } from \"src/trusted.ts\";\nimport { fail } from \"src/utils.ts\";\n\ntype ReadWordName = \"__readFields\" | `__readFields${number}`;\ntype EntityReadWords = Entity & Record<ReadWordName, number>;\n\n/**\n * Returns the current value of `fieldName`, marking the entity for read locking if the field is configured.\n *\n * Ordinary EMs skip hooks once a field is warm. Visibility-aware EMs\n * check every untrusted read and cache only trusted reads, which skip read hooks.\n *\n * Install plugins before reading entities; adding one later does not replay cached reads.\n * Generated getters and direct application calls are protected by default. Only ORM\n * housekeeping should pass `isInternal`, not domain logic in hooks, rules, or reactions.\n * The field name is a string because generated getters and ORM internals know its type.\n */\nexport function getField(entity: Entity, fieldName: string, isInternal = false): any {\n const instanceData = getInstanceData(entity);\n const index = instanceData.metadata.fieldReadIndexes[fieldName];\n if (typeof index !== \"number\") fail(`Unknown field ${instanceData.metadata.type}.${fieldName}`);\n // Direct getField calls use the same warm-read fast path as generated getters.\n if ((getFieldReadWord(entity, index >>> 5) & (1 << (index & 31))) !== 0) {\n return instanceData.data[fieldName];\n }\n return readField(entity, instanceData, fieldName, isInternal, index);\n}\n\n/** Reads stored state for ORM bookkeeping without authorizing or warming a public read. */\nexport function getStoredField<T = unknown>(entity: Entity, fieldName: string): T {\n const instanceData = getInstanceData(entity);\n const { data, metadata, rowData, rowIndex } = instanceData;\n if (!(fieldName in data) && !instanceData.isNewEntity) {\n const serde = metadata.allFields[fieldName]?.serde ?? fail(`Missing serde for ${fieldName}`);\n data[fieldName] = serde.fromRow(rowData, rowIndex);\n }\n return data[fieldName] as T;\n}\n\n/** Checks stored deletion state without authorizing or warming a public timestamp read. */\nexport function isSoftDeleted(entity: Entity): boolean {\n const fieldName = getBaseMeta(getMetadata(entity)).timestampFields?.deletedAt;\n return fieldName !== undefined && getStoredField(entity, fieldName) !== undefined;\n}\n\n/** Returns whether `fieldName` is a field/column on `entity` that can be changed. */\nexport function isChangeableField(entity: Entity, fieldName: string): boolean {\n return !!getMetadata(entity).allFields[fieldName]?.serde;\n}\n\n/** Returns whether `fieldName` has been set, even if it's undefined, on `entity`. */\nexport function isFieldSet(entity: Entity, fieldName: string): boolean {\n const { data } = getInstanceData(entity);\n if (fieldName in data) return true;\n // Avoid calling `getField` on new entities because it populates the field as a side effect.\n if (entity.isNewEntity) return false;\n // We may not have converted the database column value into domain values yet.\n getField(entity, fieldName, true);\n return fieldName in data;\n}\n\n/**\n * Sets the current value of `fieldName`, this is an internal method that should\n * only be called by the code-generated setters.\n *\n * We skip any typing like `fieldName: keyof T` because this method should only be\n * called by trusted codegen anyway.\n *\n * Returns `true` if the value was changed, or `false` if it was a noop.\n */\nexport function setField(entity: Entity, fieldName: string, newValue: any): boolean {\n ensureNotDeleted(entity, \"pending\");\n const { em } = entity;\n const api = getEmInternalApi(em);\n const { rm, pluginManager, indexManager, fieldLogger, isLoadedCache } = api;\n\n // If we're flushing, only allow writes from hooks\n api.checkWritesAllowed();\n\n const instanceData = getInstanceData(entity);\n const { data, originalData, flushedData } = instanceData;\n\n // Do string sanitization\n const field = getMetadata(entity).allFields[fieldName];\n if (field.kind === \"primitive\" && field.type === \"string\" && field.sanitize !== false) {\n newValue = cleanStringValue(newValue);\n }\n\n const currentValue = getField(entity, fieldName, true);\n const isReference = field.kind === \"m2o\" || field.kind === \"poly\";\n const currentEqualsNew = fieldValueEquals(field, currentValue, newValue);\n\n // Tell any `#isLoaded` or `#value` caches that they might be stale, but only\n // after we've checked if the current value changed. Also we do it here,\n // before the \"reverting a dirty value to the original\" check below,\n // because caches might have already observed the dirty value, so would\n // still need to refresh.\n if (!currentEqualsNew) isLoadedCache.resetIsLoaded(entity, fieldName);\n\n // Check `config.setTransitions` tables while the change is still synchronous, before we change anything,\n // and record the transition for `em.flush` to run its (async) guards and reactions\n if (field.kind === \"enum\" && !currentEqualsNew) rm.queueTransition(entity, fieldName, currentValue, newValue);\n // Remember every prior reference value so `followReverseHint` can rewalk both original and transient owners.\n if (isReference && !currentEqualsNew) {\n instanceData.rememberReferenceValue(fieldName, currentValue);\n }\n\n // If a `set` occurs during the AsyncReactiveField-loop, copy the last-flushed value to flushedData.\n // Then our `pendingOperation` logic can tell \"do we need another micro-flush?\" separately\n // from our public-facing changed fields logic.\n if (flushedData) {\n if (fieldName in flushedData) {\n // We've already copied the last-micro-flush value into flushedData,\n // are we changing back to that? If so, we won't need another micro-flush.\n if (equalOrSameEntity(flushedData[fieldName], newValue)) {\n delete flushedData[fieldName];\n } else {\n // Otherwise just let data[fieldName] get the even-newer value, and keep\n // flushedData[fieldName] as the last-micro-flushed value.\n }\n } else if (!currentEqualsNew) {\n // This is the 1st rqf-loop change for this field, so let data[fieldName]\n // get the even newer value, but keep the last-micro-flushed value in flushedData.\n flushedData[fieldName] = currentValue;\n }\n }\n\n // \"Un-dirty\" our originalData if newValue is reverting to originalData\n if (fieldName in originalData) {\n if (fieldValueEquals(field, originalData[fieldName], newValue)) {\n indexManager.maybeUpdateFieldIndex(entity, fieldName, currentValue, newValue);\n\n pluginManager.beforeSetField(entity, fieldName, newValue);\n data[fieldName] = newValue;\n if (instanceData.flushHooksCurrent && !(\"derived\" in field && field.derived === \"sync\"))\n instanceData.flushHooksCurrent = false;\n instanceData.markFieldClean(fieldName);\n\n fieldLogger.logSet(entity, fieldName, newValue);\n if (isReference && instanceData.getReferenceHistory(fieldName).length > 0) {\n rm.queueDownstreamReactables(entity, fieldName);\n } else {\n // For normal reverts, the field is clean again, so any pending downstream work can be removed.\n rm.dequeueDownstreamReactables(entity, fieldName);\n }\n\n return true;\n }\n }\n\n // Push this logic into a field serde type abstraction?\n if (currentEqualsNew) {\n // If we're doing `entity.field = undefined`, we'll be equal, but mark ourselves as \"set\"\n // so that defaults know to respect the intent of keeping this field undefined.\n if (!(fieldName in data)) data[fieldName] = undefined;\n return false;\n }\n\n // Only save the currentValue on the 1st change of this field\n if (!(fieldName in originalData)) {\n instanceData.markFieldDirty(fieldName, currentValue);\n }\n fieldLogger.logSet(entity, fieldName, newValue);\n rm.queueDownstreamReactables(entity, fieldName);\n\n indexManager.maybeUpdateFieldIndex(entity, fieldName, currentValue, newValue);\n\n pluginManager.beforeSetField(entity, fieldName, newValue);\n data[fieldName] = newValue;\n // Writing back a synchronous getter after hooks does not change what the hooks already saw.\n if (instanceData.flushHooksCurrent && !(\"derived\" in field && field.derived === \"sync\"))\n instanceData.flushHooksCurrent = false;\n return true;\n}\n\nfunction fieldValueEquals(field: Field, a: unknown, b: unknown): boolean {\n // Primitive scalar sets are the common path, so avoid Date/Temporal/entity checks when both values cannot need them.\n if (field.kind !== \"m2o\" && field.kind !== \"poly\" && isNonObjectValue(a) && isNonObjectValue(b)) return a === b;\n return equalOrSameEntity(a, b);\n}\n\nfunction isNonObjectValue(value: unknown): boolean {\n return value === null || typeof value !== \"object\";\n}\n\nfunction equalOrSameEntity(a: any, b: any): boolean {\n return (\n equal(a, b) ||\n (Array.isArray(a) && Array.isArray(b) && equalArrays(a, b)) ||\n // This is kind of gross, but make sure not to compare two both-new entities\n (((isEntity(a) && !a.isNewEntity) || (isEntity(b) && !b.isNewEntity)) &&\n maybeResolveReferenceToId(a) === maybeResolveReferenceToId(b))\n );\n}\n\nexport function equalArrays(a: any[], b: any[]): boolean {\n if (a.length !== b.length) return false;\n return a.every((_: any, i) => equal(a[i], b[i]));\n}\n\nconst Temporal = maybeRequireTemporal()?.Temporal;\nexport function equal(a: any, b: any): boolean {\n if (a === b) return true;\n if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n if (Temporal) {\n if (a instanceof Temporal.ZonedDateTime && b instanceof Temporal.ZonedDateTime) return a.equals(b);\n if (a instanceof Temporal.PlainDateTime && b instanceof Temporal.PlainDateTime) return a.equals(b);\n if (a instanceof Temporal.PlainDate && b instanceof Temporal.PlainDate) return a.equals(b);\n }\n return false;\n}\n\n/**\n * Performs read callbacks, protection, and lazy conversion before publishing the warm-read bit.\n *\n * Reentrant reads may inspect the value, but only the outer read can publish a warm bit\n * after its hooks succeed.\n */\nfunction readField(\n entity: Entity,\n instanceData: InstanceData,\n fieldName: string,\n isInternal: boolean,\n index: number,\n): any {\n const { em, metadata } = instanceData;\n // Ordinary EMs pay this check only until the field is warm; subsequent reads skip this path.\n const shouldMarkReadField = runFieldReadHooks(entity, instanceData, fieldName);\n\n const field = metadata.allFields[fieldName];\n if (!isInternal && field?.assertUnchanged) em.assertUnchanged(entity);\n // Hooks may replace a cached value, so inspect current storage only after they finish.\n const { data } = instanceData;\n if (!(fieldName in data) && !instanceData.isNewEntity) {\n // We may not have converted the database column value into domain values yet.\n const serde = field?.serde ?? fail(`Missing serde for ${fieldName}`);\n data[fieldName] = serde.fromRow(instanceData.rowData, instanceData.rowIndex);\n }\n // IDs are always assigned into data.id, so even their unassigned reads can stay warm.\n // Other unset new fields stay cold: inserts may supply defaults later, without a read\n // turning into an explicit `undefined` for defaults/isFieldSet.\n if (shouldMarkReadField && (fieldName === \"id\" || fieldName in data) && (!isInternal || !field?.assertUnchanged)) {\n markApplicationReadField(entity, index, true);\n }\n return data[fieldName];\n}\n\n/**\n * Invokes cold-read hooks without letting a reentrant read authorize the outer read.\n *\n * The active-field guard permits synchronous hook reentrancy without caching its approval.\n * The entity's read-word descriptors discard untrusted warm-bit writes from the shared read path.\n */\nfunction runFieldReadHooks(entity: Entity, instanceData: InstanceData, fieldName: string): boolean {\n const plugins = getEmInternalApi(instanceData.em).pluginManager;\n if (!plugins.hasHook(\"beforeGetField\")) return true;\n\n if (instanceData.activeReadFields?.has(fieldName)) return false;\n if (instanceData.trustedReadFields && isInTrustedContext()) return true;\n const active = (instanceData.activeReadFields ??= new Set<string>());\n active.add(fieldName);\n try {\n plugins.beforeGetField(entity, fieldName);\n return true;\n } catch (error) {\n // A reentrant ID getter may have cached a conversion before the outer hook failed.\n if (fieldName === \"id\") instanceData.idCache = undefined;\n throw error;\n } finally {\n active.delete(fieldName);\n }\n}\n\n/** Tests a field bit without allocating the extra words for small entity types. */\nfunction hasReadField(first: number, extra: readonly number[] | undefined, index: number): boolean {\n const word = index < 32 ? first : (extra?.[(index >>> 5) - 1] ?? 0);\n return (word & (1 << (index & 31))) !== 0;\n}\n\n/** Changes the entity's warm-read bit without disturbing other fields in that word. */\nfunction markApplicationReadField(entity: Entity, index: number, read: boolean): void {\n const bit = 1 << (index & 31);\n const word = index >>> 5;\n const value = getFieldReadWord(entity, word);\n setFieldReadWord(entity, word, read ? value | bit : value & ~bit);\n}\n\n/** Reads the same warm-read words used by generated getters. */\nfunction getFieldReadWord(entity: Entity, word: number): number {\n return (entity as EntityReadWords)[readWordName(word)];\n}\n\n/** Updates a warm-read word without exposing an entity API. */\nfunction setFieldReadWord(entity: Entity, word: number, value: number): void {\n (entity as EntityReadWords)[readWordName(word)] = value;\n}\n\n/** Matches the literal names emitted by codegen; only shared reads construct a word name. */\nfunction readWordName(word: number): ReadWordName {\n return word === 0 ? \"__readFields\" : `__readFields${word}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,SAAS,QAAgB,WAAmB,aAAa,OAAY;CACnF,MAAM,eAAe,gBAAgB,MAAM;CAC3C,MAAM,QAAQ,aAAa,SAAS,iBAAiB;CACrD,IAAI,OAAO,UAAU,UAAU,KAAK,iBAAiB,aAAa,SAAS,KAAK,GAAG,WAAW;CAE9F,KAAK,iBAAiB,QAAQ,UAAU,CAAC,IAAK,MAAM,QAAQ,SAAU,GACpE,OAAO,aAAa,KAAK;CAE3B,OAAO,UAAU,QAAQ,cAAc,WAAW,YAAY,KAAK;AACrE;;AAGA,SAAgB,eAA4B,QAAgB,WAAsB;CAChF,MAAM,eAAe,gBAAgB,MAAM;CAC3C,MAAM,EAAE,MA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,SAAS,aAAa,MAA4B;CAChD,OAAO,SAAS,IAAI,iBAAiB,eAAe;AACtD"}
1
+ {"version":3,"file":"fields.js","names":[],"sources":["../src/fields.ts"],"sourcesContent":["import { getInstanceData } from \"src/BaseEntity.ts\";\nimport { type Entity, isEntity } from \"src/Entity.ts\";\nimport { getEmInternalApi } from \"src/EntityManager.ts\";\nimport { type Field, getBaseMeta, getMetadata } from \"src/EntityMetadata.ts\";\nimport { cleanStringValue, ensureNotDeleted, maybeResolveReferenceToId } from \"src/index.ts\";\nimport type { InstanceData } from \"src/InstanceData.ts\";\nimport { maybeRequireTemporal } from \"src/serde/temporal.ts\";\nimport { isInTrustedContext } from \"src/trusted.ts\";\nimport { fail } from \"src/utils.ts\";\n\ntype ReadWordName = \"__readFields\" | `__readFields${number}`;\ntype EntityReadWords = Entity & Record<ReadWordName, number>;\n\n/**\n * Returns the current value of `fieldName`, marking the entity for read locking if the field is configured.\n *\n * Ordinary EMs skip hooks once a field is warm. Visibility-aware EMs\n * check every untrusted read and cache trusted reads separately.\n *\n * Install plugins before reading entities; adding one later does not replay cached reads.\n * Generated getters and direct application calls are protected by default. Only ORM\n * housekeeping should pass `isInternal`, not domain logic in hooks, rules, or reactions.\n * The field name is a string because generated getters and ORM internals know its type.\n */\nexport function getField(entity: Entity, fieldName: string, isInternal = false): any {\n const instanceData = getInstanceData(entity);\n const index = instanceData.metadata.fieldReadIndexes[fieldName];\n if (typeof index !== \"number\") fail(`Unknown field ${instanceData.metadata.type}.${fieldName}`);\n // Direct getField calls use the same warm-read fast path as generated getters.\n if ((getFieldReadWord(entity, index >>> 5) & (1 << (index & 31))) !== 0) {\n return instanceData.data[fieldName];\n }\n return readField(entity, instanceData, fieldName, isInternal, index);\n}\n\n/**\n * Checks the caller's access to a derived field before recalculating it in trusted context,\n * without reading or caching its value.\n */\nexport function checkBeforeGetField(entity: Entity, field: string): void {\n runFieldReadHooks(entity, getInstanceData(entity), field);\n}\n\n/** Reads stored state for ORM bookkeeping without authorizing or warming a public read. */\nexport function getStoredField<T = unknown>(entity: Entity, fieldName: string): T {\n const instanceData = getInstanceData(entity);\n const { data, metadata, rowData, rowIndex } = instanceData;\n if (!(fieldName in data) && !instanceData.isNewEntity) {\n const serde = metadata.allFields[fieldName]?.serde ?? fail(`Missing serde for ${fieldName}`);\n data[fieldName] = serde.fromRow(rowData, rowIndex);\n }\n return data[fieldName] as T;\n}\n\n/** Checks stored deletion state without authorizing or warming a public timestamp read. */\nexport function isSoftDeleted(entity: Entity): boolean {\n const fieldName = getBaseMeta(getMetadata(entity)).timestampFields?.deletedAt;\n return fieldName !== undefined && getStoredField(entity, fieldName) !== undefined;\n}\n\n/** Returns whether `fieldName` is a field/column on `entity` that can be changed. */\nexport function isChangeableField(entity: Entity, fieldName: string): boolean {\n return !!getMetadata(entity).allFields[fieldName]?.serde;\n}\n\n/** Returns whether `fieldName` has been set, even if it's undefined, on `entity`. */\nexport function isFieldSet(entity: Entity, fieldName: string): boolean {\n const { data } = getInstanceData(entity);\n if (fieldName in data) return true;\n // Avoid calling `getField` on new entities because it populates the field as a side effect.\n if (entity.isNewEntity) return false;\n // We may not have converted the database column value into domain values yet.\n getField(entity, fieldName, true);\n return fieldName in data;\n}\n\n/**\n * Sets the current value of `fieldName`, this is an internal method that should\n * only be called by the code-generated setters.\n *\n * We skip any typing like `fieldName: keyof T` because this method should only be\n * called by trusted codegen anyway.\n *\n * Returns `true` if the value was changed, or `false` if it was a noop.\n */\nexport function setField(entity: Entity, fieldName: string, newValue: any): boolean {\n ensureNotDeleted(entity, \"pending\");\n const { em } = entity;\n const api = getEmInternalApi(em);\n const { rm, pluginManager, indexManager, fieldLogger, isLoadedCache } = api;\n\n // If we're flushing, only allow writes from hooks\n api.checkWritesAllowed();\n\n const instanceData = getInstanceData(entity);\n const { data, originalData, flushedData } = instanceData;\n\n // Do string sanitization\n const field = getMetadata(entity).allFields[fieldName];\n if (field.kind === \"primitive\" && field.type === \"string\" && field.sanitize !== false) {\n newValue = cleanStringValue(newValue);\n }\n\n const currentValue = getField(entity, fieldName, true);\n const isReference = field.kind === \"m2o\" || field.kind === \"poly\";\n const currentEqualsNew = fieldValueEquals(field, currentValue, newValue);\n\n // Tell any `#isLoaded` or `#value` caches that they might be stale, but only\n // after we've checked if the current value changed. Also we do it here,\n // before the \"reverting a dirty value to the original\" check below,\n // because caches might have already observed the dirty value, so would\n // still need to refresh.\n if (!currentEqualsNew) isLoadedCache.resetIsLoaded(entity, fieldName);\n\n // Check `config.setTransitions` tables while the change is still synchronous, before we change anything,\n // and record the transition for `em.flush` to run its (async) guards and reactions\n if (field.kind === \"enum\" && !currentEqualsNew) rm.queueTransition(entity, fieldName, currentValue, newValue);\n // Remember every prior reference value so `followReverseHint` can rewalk both original and transient owners.\n if (isReference && !currentEqualsNew) {\n instanceData.rememberReferenceValue(fieldName, currentValue);\n }\n\n // If a `set` occurs during the AsyncReactiveField-loop, copy the last-flushed value to flushedData.\n // Then our `pendingOperation` logic can tell \"do we need another micro-flush?\" separately\n // from our public-facing changed fields logic.\n if (flushedData) {\n if (fieldName in flushedData) {\n // We've already copied the last-micro-flush value into flushedData,\n // are we changing back to that? If so, we won't need another micro-flush.\n if (equalOrSameEntity(flushedData[fieldName], newValue)) {\n delete flushedData[fieldName];\n } else {\n // Otherwise just let data[fieldName] get the even-newer value, and keep\n // flushedData[fieldName] as the last-micro-flushed value.\n }\n } else if (!currentEqualsNew) {\n // This is the 1st rqf-loop change for this field, so let data[fieldName]\n // get the even newer value, but keep the last-micro-flushed value in flushedData.\n flushedData[fieldName] = currentValue;\n }\n }\n\n // \"Un-dirty\" our originalData if newValue is reverting to originalData\n if (fieldName in originalData) {\n if (fieldValueEquals(field, originalData[fieldName], newValue)) {\n indexManager.maybeUpdateFieldIndex(entity, fieldName, currentValue, newValue);\n\n pluginManager.beforeSetField(entity, fieldName, newValue);\n data[fieldName] = newValue;\n if (instanceData.flushHooksCurrent && !(\"derived\" in field && field.derived === \"sync\"))\n instanceData.flushHooksCurrent = false;\n instanceData.markFieldClean(fieldName);\n\n fieldLogger.logSet(entity, fieldName, newValue);\n if (isReference && instanceData.getReferenceHistory(fieldName).length > 0) {\n rm.queueDownstreamReactables(entity, fieldName);\n } else {\n // For normal reverts, the field is clean again, so any pending downstream work can be removed.\n rm.dequeueDownstreamReactables(entity, fieldName);\n }\n\n return true;\n }\n }\n\n // Push this logic into a field serde type abstraction?\n if (currentEqualsNew) {\n // If we're doing `entity.field = undefined`, we'll be equal, but mark ourselves as \"set\"\n // so that defaults know to respect the intent of keeping this field undefined.\n if (!(fieldName in data)) data[fieldName] = undefined;\n return false;\n }\n\n // Only save the currentValue on the 1st change of this field\n if (!(fieldName in originalData)) {\n instanceData.markFieldDirty(fieldName, currentValue);\n }\n fieldLogger.logSet(entity, fieldName, newValue);\n rm.queueDownstreamReactables(entity, fieldName);\n\n indexManager.maybeUpdateFieldIndex(entity, fieldName, currentValue, newValue);\n\n pluginManager.beforeSetField(entity, fieldName, newValue);\n data[fieldName] = newValue;\n // Writing back a synchronous getter after hooks does not change what the hooks already saw.\n if (instanceData.flushHooksCurrent && !(\"derived\" in field && field.derived === \"sync\"))\n instanceData.flushHooksCurrent = false;\n return true;\n}\n\nfunction fieldValueEquals(field: Field, a: unknown, b: unknown): boolean {\n // Primitive scalar sets are the common path, so avoid Date/Temporal/entity checks when both values cannot need them.\n if (field.kind !== \"m2o\" && field.kind !== \"poly\" && isNonObjectValue(a) && isNonObjectValue(b)) return a === b;\n return equalOrSameEntity(a, b);\n}\n\nfunction isNonObjectValue(value: unknown): boolean {\n return value === null || typeof value !== \"object\";\n}\n\nfunction equalOrSameEntity(a: any, b: any): boolean {\n return (\n equal(a, b) ||\n (Array.isArray(a) && Array.isArray(b) && equalArrays(a, b)) ||\n // This is kind of gross, but make sure not to compare two both-new entities\n (((isEntity(a) && !a.isNewEntity) || (isEntity(b) && !b.isNewEntity)) &&\n maybeResolveReferenceToId(a) === maybeResolveReferenceToId(b))\n );\n}\n\nexport function equalArrays(a: any[], b: any[]): boolean {\n if (a.length !== b.length) return false;\n return a.every((_: any, i) => equal(a[i], b[i]));\n}\n\nconst Temporal = maybeRequireTemporal()?.Temporal;\nexport function equal(a: any, b: any): boolean {\n if (a === b) return true;\n if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n if (Temporal) {\n if (a instanceof Temporal.ZonedDateTime && b instanceof Temporal.ZonedDateTime) return a.equals(b);\n if (a instanceof Temporal.PlainDateTime && b instanceof Temporal.PlainDateTime) return a.equals(b);\n if (a instanceof Temporal.PlainDate && b instanceof Temporal.PlainDate) return a.equals(b);\n }\n return false;\n}\n\n/**\n * Performs read callbacks, protection, and lazy conversion before publishing the warm-read bit.\n *\n * Reentrant reads may inspect the value, but only the outer read can publish a warm bit\n * after its hooks succeed.\n */\nfunction readField(\n entity: Entity,\n instanceData: InstanceData,\n fieldName: string,\n isInternal: boolean,\n index: number,\n): any {\n const { em, metadata } = instanceData;\n // Ordinary EMs pay this check only once, as once its __readFields bit is set, then\n // getField/readField is never called on subsequent getter calls.\n const shouldMarkReadField = runFieldReadHooks(entity, instanceData, fieldName);\n\n const field = metadata.allFields[fieldName];\n if (!isInternal && field?.assertUnchanged) em.assertUnchanged(entity);\n // Hooks may replace a cached value, so inspect current storage only after they finish.\n const { data } = instanceData;\n if (!(fieldName in data) && !instanceData.isNewEntity) {\n // We may not have converted the database column value into domain values yet.\n const serde = field?.serde ?? fail(`Missing serde for ${fieldName}`);\n data[fieldName] = serde.fromRow(instanceData.rowData, instanceData.rowIndex);\n }\n // IDs are always assigned into data.id, so even their unassigned reads can stay warm.\n // Other unset new fields stay cold: inserts may supply defaults later, without a read\n // turning into an explicit `undefined` for defaults/isFieldSet.\n if (shouldMarkReadField && (fieldName === \"id\" || fieldName in data) && (!isInternal || !field?.assertUnchanged)) {\n markApplicationReadField(entity, index, true);\n }\n return data[fieldName];\n}\n\n/**\n * Invokes cold-read hooks without letting a reentrant read authorize the outer read.\n *\n * This function is solely for `beforeGetField` calls and the behavior is:\n *\n * - visibility-aware EMs (i.e. EMs with an AuthPlugin.canViewEntity hook) get to \"pretend\"\n * to set the `__readFields` bit all the time, but really we've rewritten `__readFields` to\n * be a getter that _always returns zero_ for untrusted callers, b/c their auth decision\n * could always change.\n * - ordinary EMs only conditionally set the `__readFields` bit, because for them it's a real\n * bit (not a getter), and trusted callers need to leave it unset, so the plugins that are\n * potentially \"early-returning/ignoring all trusted callers\" get to see the 1st untrusted call.\n */\nfunction runFieldReadHooks(entity: Entity, instanceData: InstanceData, fieldName: string): boolean {\n const plugins = getEmInternalApi(instanceData.em).pluginManager;\n if (!plugins.hasHook(\"beforeGetField\")) return true;\n\n if (instanceData.activeReadFields?.has(fieldName)) return false;\n const active = (instanceData.activeReadFields ??= new Set<string>());\n active.add(fieldName);\n try {\n plugins.beforeGetField(entity, fieldName);\n\n // Decide whether we can set the __readFields bit, see jsdocs above.\n const isVisAwareEm = instanceData.trustedReadFields !== undefined;\n return isVisAwareEm || !isInTrustedContext();\n } catch (error) {\n // A reentrant ID getter may have cached a conversion before the outer hook failed.\n if (fieldName === \"id\") instanceData.idCache = undefined;\n throw error;\n } finally {\n active.delete(fieldName);\n }\n}\n\n/** Tests a field bit without allocating the extra words for small entity types. */\nfunction hasReadField(first: number, extra: readonly number[] | undefined, index: number): boolean {\n const word = index < 32 ? first : (extra?.[(index >>> 5) - 1] ?? 0);\n return (word & (1 << (index & 31))) !== 0;\n}\n\n/** Changes the entity's warm-read bit without disturbing other fields in that word. */\nfunction markApplicationReadField(entity: Entity, index: number, read: boolean): void {\n const bit = 1 << (index & 31);\n const word = index >>> 5;\n const value = getFieldReadWord(entity, word);\n setFieldReadWord(entity, word, read ? value | bit : value & ~bit);\n}\n\n/** Reads the same warm-read words used by generated getters. */\nfunction getFieldReadWord(entity: Entity, word: number): number {\n return (entity as EntityReadWords)[readWordName(word)];\n}\n\n/** Updates a warm-read word without exposing an entity API. */\nfunction setFieldReadWord(entity: Entity, word: number, value: number): void {\n (entity as EntityReadWords)[readWordName(word)] = value;\n}\n\n/** Matches the literal names emitted by codegen; only shared reads construct a word name. */\nfunction readWordName(word: number): ReadWordName {\n return word === 0 ? \"__readFields\" : `__readFields${word}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,SAAS,QAAgB,WAAmB,aAAa,OAAY;CACnF,MAAM,eAAe,gBAAgB,MAAM;CAC3C,MAAM,QAAQ,aAAa,SAAS,iBAAiB;CACrD,IAAI,OAAO,UAAU,UAAU,KAAK,iBAAiB,aAAa,SAAS,KAAK,GAAG,WAAW;CAE9F,KAAK,iBAAiB,QAAQ,UAAU,CAAC,IAAK,MAAM,QAAQ,SAAU,GACpE,OAAO,aAAa,KAAK;CAE3B,OAAO,UAAU,QAAQ,cAAc,WAAW,YAAY,KAAK;AACrE;;;;;AAMA,SAAgB,oBAAoB,QAAgB,OAAqB;CACvE,kBAAkB,QAAQ,gBAAgB,MAAM,GAAG,KAAK;AAC1D;;AAGA,SAAgB,eAA4B,QAAgB,WAAsB;CAChF,MAAM,eAAe,gBAAgB,MAAM;CAC3C,MAAM,EAAE,MAAM,UAAU,SAAS,aAAa;CAC9C,IAAI,EAAE,aAAa,SAAS,CAAC,aAAa,aAExC,KAAK,cADS,SAAS,UAAU,UAAU,EAAE,SAAS,KAAK,qBAAqB,WAAW,EAAA,CACnE,QAAQ,SAAS,QAAQ;CAEnD,OAAO,KAAK;AACd;;AAGA,SAAgB,cAAc,QAAyB;CACrD,MAAM,YAAY,YAAY,YAAY,MAAM,CAAC,CAAC,CAAC,iBAAiB;CACpE,OAAO,cAAc,KAAA,KAAa,eAAe,QAAQ,SAAS,MAAM,KAAA;AAC1E;;AAGA,SAAgB,kBAAkB,QAAgB,WAA4B;CAC5E,OAAO,CAAC,CAAC,YAAY,MAAM,CAAC,CAAC,UAAU,UAAU,EAAE;AACrD;;AAGA,SAAgB,WAAW,QAAgB,WAA4B;CACrE,MAAM,EAAE,SAAS,gBAAgB,MAAM;CACvC,IAAI,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,kBAAkB,IAAI,SAAS,GAAG,OAAO;CAC1D,MAAM,SAAU,aAAa,qCAAqB,IAAI,IAAY;CAClE,OAAO,IAAI,SAAS;CACpB,IAAI;EACF,QAAQ,eAAe,QAAQ,SAAS;EAIxC,OADqB,aAAa,sBAAsB,KAAA,KACjC,CAAC,mBAAmB;CAC7C,SAAS,OAAO;EAEd,IAAI,cAAc,MAAM,aAAa,UAAU,KAAA;EAC/C,MAAM;CACR,UAAU;EACR,OAAO,OAAO,SAAS;CACzB;AACF;;AASA,SAAS,yBAAyB,QAAgB,OAAe,MAAqB;CACpF,MAAM,MAAM,MAAM,QAAQ;CAC1B,MAAM,OAAO,UAAU;CACvB,MAAM,QAAQ,iBAAiB,QAAQ,IAAI;CAC3C,iBAAiB,QAAQ,MAAM,OAAO,QAAQ,MAAM,QAAQ,CAAC,GAAG;AAClE;;AAGA,SAAS,iBAAiB,QAAgB,MAAsB;CAC9D,OAAQ,OAA2B,aAAa,IAAI;AACtD;;AAGA,SAAS,iBAAiB,QAAgB,MAAc,OAAqB;CAC3E,OAA4B,aAAa,IAAI,KAAK;AACpD;;AAGA,SAAS,aAAa,MAA4B;CAChD,OAAO,SAAS,IAAI,iBAAiB,eAAe;AACtD"}
@@ -1,17 +1,19 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  require("../Entity.cjs");
3
3
  const require_EntityManager = require("../EntityManager.cjs");
4
- const require_normalizeHints = require("../normalizeHints.cjs");
5
4
  const require_EntityMetadata = require("../EntityMetadata.cjs");
6
5
  const require_fields = require("../fields.cjs");
6
+ const require_normalizeHints = require("../normalizeHints.cjs");
7
7
  require("../index.cjs");
8
- const require_loading_loadHints = require("../loading/loadHints.cjs");
9
8
  const require_metrics_EntityMetrics = require("../metrics/EntityMetrics.cjs");
10
9
  const require_newEntity = require("../newEntity.cjs");
10
+ const require_loading_loadHints = require("../loading/loadHints.cjs");
11
11
  const require_reactivity_reactiveHints = require("../reactivity/reactiveHints.cjs");
12
12
  const require_relations_AbstractPropertyImpl = require("./AbstractPropertyImpl.cjs");
13
13
  const require_relations_PropertySymbols = require("./PropertySymbols.cjs");
14
+ const require_trusted = require("../trusted.cjs");
14
15
  const require_utils = require("../utils.cjs");
16
+ const require_relations_relationVisibility = require("./relationVisibility.cjs");
15
17
  // src/relations/AsyncReactiveField.ts
16
18
  /**
17
19
  * An `AsyncReactiveField` is a value that is derived from a SQL query, similar to
@@ -28,7 +30,7 @@ function hasAsyncReactiveField(loadHint, reactiveHint, fn) {
28
30
  let evaluation;
29
31
  return require_newEntity.lazyField((entity, fieldName) => {
30
32
  evaluation ??= new require_metrics_EntityMetrics.EvaluationSlot(`${require_EntityMetadata.getMetadata(entity).type}.${fieldName}`);
31
- return new AsyncReactiveFieldImpl(entity, fieldName, loadHint, reactiveHint, fn, evaluation);
33
+ return new (require_relations_relationVisibility.hasReactiveReadHook(entity) ? PluginAsyncReactiveField : AsyncReactiveFieldImpl)(entity, fieldName, loadHint, reactiveHint, fn, evaluation);
32
34
  });
33
35
  }
34
36
  var AsyncReactiveFieldImpl = class extends require_relations_AbstractPropertyImpl.AbstractPropertyImpl {
@@ -111,6 +113,15 @@ var AsyncReactiveFieldImpl = class extends require_relations_AbstractPropertyImp
111
113
  }
112
114
  [require_relations_PropertySymbols.PropertyT] = void 0;
113
115
  };
116
+ var PluginAsyncReactiveField = class extends AsyncReactiveFieldImpl {
117
+ async load(opts) {
118
+ require_fields.checkBeforeGetField(this.entity, this.fieldName);
119
+ return require_trusted.runInTrustedContext(() => super.load(opts));
120
+ }
121
+ get isLoaded() {
122
+ return require_trusted.runInTrustedContext(() => super.isLoaded);
123
+ }
124
+ };
114
125
  /** Type guard utility for determining if an entity field is an AsyncReactiveField. */
115
126
  function isAsyncReactiveField(maybe) {
116
127
  return maybe instanceof AsyncReactiveFieldImpl;