@appling/codegen-ash 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -18,7 +18,7 @@ Requires Elixir 1.17 or later and the `igniter_new` archive (`mix archive.instal
18
18
 
19
19
  | Model | Ash |
20
20
  |---|---|
21
- | project | `mix igniter.new <name> --install ash,ash_postgres` |
21
+ | project | `mix igniter.new <name> --install ash,ash_postgres`, plus `simple_sat` when the model has policies |
22
22
  | `module` | `mix ash.gen.domain <App>.<Module>` |
23
23
  | `enum` | `mix ash.gen.enum` |
24
24
  | `value` | an embedded resource |
@@ -31,12 +31,17 @@ Requires Elixir 1.17 or later and the `igniter_new` archive (`mix archive.instal
31
31
  | `action` on an entity | an update action: arguments for inputs, validations for preconditions and guards, `set_attribute` or `atomic_update` changes, and `transition_state` |
32
32
  | `machine` | an AshStateMachine section; transitions on an event get an update action named after the event |
33
33
  | scheduled `job` | an AshOban trigger with `where` and `scheduler_cron`; `now - duration("720h")` becomes `ago(720, :hour)` |
34
- | `query` | a read action with filter, sort and offset pagination |
34
+ | `query` | a read action with its inputs as arguments, filter, sort and offset pagination; a filter that does not translate reads nothing (`filter expr(false)`) until written |
35
35
  | computed projection field | a calculation on the source resource |
36
- | `role` | an `Ash.Policy.SimpleCheck` per role on the resource actors are bound to with `is` (a private `roles` attribute and a calculation per role condition); policies that only name roles become `authorize_if` lines with `Ash.Policy.Authorizer` |
36
+ | `actor` | bound with `is`: the entity's resource holds its fields and a private `roles` attribute limited to the roles its actors carry; a `human` actor without `is`: a resource of its own with its fields and `roles`; a `system` or `service` actor without `is`: a struct whose `roles` are its roles; `actor.is(Actor)` becomes a check matching its record |
37
+ | `role` | an `Ash.Policy.SimpleCheck` `<App>.<Module>.Checks.<Role>` with one clause per actor record that carries the role; the roles a condition names call their checks, the rest of the condition is a calculation `:<role>?` on the actor resource |
38
+ | `tenant` | attribute multitenancy (`strategy :attribute`) on every resource with a relationship to the tenant's entity, `global? true` on actor resources; `tenant` in expressions becomes `^tenant()` |
39
+ | `policy` | `Ash.Policy.Authorizer` policies: `action_type(...)` or `always()` for entity policies, `field_policy` for `fields` (plus a catch-all `field_policy :*`; a calculation it names is public, a derived field without one waits for its calculation task), `action(:name)` for actions and queries; each `\|\|` branch becomes `authorize_if`, a branch with `&&` becomes `forbid_unless` checks followed by `authorize_if`; conditions become `expr` checks with `^actor(...)` and records compared by id. Once the model has a policy, every resource lists the authorizer and denies what no policy covers (a resource without policies gets `policy always()` with `forbid_if always()`), an untranslated condition forbids until written, and resources with jobs get an AshOban bypass |
37
40
  | `interface rest` | AshJsonApi routes on the domain (`index` for queries with `default_fields` from picks, `patch` for update actions), served by Phoenix under `/api/json` when the model has pages, otherwise by a JSON:API router that Bandit serves on port 4000 |
38
41
  | `page`, `navigation`, `messages` | Phoenix LiveViews with lists, details, AshPhoenix forms and action buttons, navigation links and column labels; models with pages need the `phx_new` archive |
39
- | rules | skipped ExUnit tests in `test/<app>/<module>/<resource>_test.exs` for invariants, policies, transitions and preconditions; writing their bodies is a registry task |
42
+ | `does` | `@moduledoc` of resources and embedded resources, `description` of attributes, and a registry task |
43
+ | rules | skipped ExUnit tests in `test/<app>/<module>/<resource>_test.exs` for invariants, policies, transitions and preconditions; invariants that become validations get changeset test bodies where the simulator proves a valid and a violating input, transitions get update changeset bodies on a record struct (AshStateMachine's state check, no database), preconditions that become validations get update changeset bodies asserting their message where the simulator proves them false on that struct, entity policies get `Ash.can?` bodies on an actor struct for actors their `actor.is(...)` checks decide, writing every other body is a registry task |
44
+ | `scenario` | an ExUnit test in `test/<app>/<module>/scenarios_test.exs` with a database sandbox: the given rows through `Ash.Seed.seed!` (samples for required attributes), the actor seeded or built with its roles, the call through `Ash.update` on the action's update action, and asserts for the checks, `fails` and `refused` (`Ash.Error.Forbidden`); a scenario the generated project cannot pass yet (use cases, lists of entities, events, untranslated validations or policies) is a skipped test and a registry task. Actions and transitions a scenario runs get no guessed precondition or transition tests |
40
45
 
41
46
  The project ends with `mix ash.codegen initial_resources`, so migrations and resource snapshots start with the generated resources.
42
47
 
@@ -44,7 +49,7 @@ The project ends with `mix ash.codegen initial_resources`, so migrations and res
44
49
 
45
50
  Machines, scheduled jobs and REST interfaces add `ash_state_machine`, `ash_oban`, and `ash_json_api` with `bandit` to the project.
46
51
 
47
- What cannot be translated becomes a registry task: many to many relationships, calculations over embedded lists, invariants and preconditions over calculations or other resources, policies that say more than which roles may act, events (Ash notifiers), externals and use cases (generic actions or Reactor), effects that create rows or emit events, jobs on events, authentication, rate limits and CORS.
52
+ What cannot be translated becomes a registry task: many to many relationships, calculations over embedded lists, invariants and preconditions over calculations or other resources, policies with more than one `&&` branch and field policies that follow relationships (both deny until written), writes of field policies, policies of use cases and of actions without an entity, resources that reach the tenant only through relationships, events (Ash notifiers), externals and use cases (generic actions or Reactor), effects that create rows, emit events, loop or change related records (an action that only deletes its own record becomes a destroy action), jobs on events, authentication, rate limits and CORS, webhook endpoints and the vendor side setup (registering webhooks, issuing tokens with a role claim). Settings and secrets of externals are read from the environment in `config/runtime.exs` (a missing secret stops the app through `System.fetch_env!`) and listed in `.env.example`.
48
53
 
49
54
  ## License
50
55
 
@@ -0,0 +1,38 @@
1
+ import type { MapContext, Step } from '@appling/codegen';
2
+ import type { GraphNode } from '@appling/model';
3
+ /**
4
+ * Where an actor lives in the generated project. An actor bound with `is` is a record of its entity's resource; a
5
+ * human actor without `is` gets a resource of its own; a system or service actor without `is` is a plain struct
6
+ * whose `roles` are the roles it declares.
7
+ */
8
+ export interface ActorHome {
9
+ /** The entity, or the actor itself for an actor without `is`. */
10
+ node: GraphNode;
11
+ module: string;
12
+ /** Whether the home is an Ash resource (with a stored `roles` attribute), not a struct. */
13
+ resource: boolean;
14
+ /** The actors living in this home. */
15
+ actors: GraphNode[];
16
+ }
17
+ export declare function homeOf(actor: GraphNode, context: MapContext): ActorHome;
18
+ /** Every home, once each. */
19
+ export declare function homes(context: MapContext): ActorHome[];
20
+ /** The home whose node is this entity or actor, if actors live there. */
21
+ export declare function homeAt(node: GraphNode, context: MapContext): ActorHome | undefined;
22
+ /** The roles the actors of a home carry, as qualified names in declaration order. */
23
+ export declare function rolesOf(home: ActorHome): string[];
24
+ /** The fields an actor's record holds: the entity's fields plus the fields of every actor bound to it. */
25
+ export declare function homeFields(home: ActorHome, context: MapContext): GraphNode[];
26
+ /** The `--attribute` specs of the fields of the bound actors and the private `roles` of an entity that actors are bound to. */
27
+ export declare function actorAttributeSpecs(entity: GraphNode, context: MapContext): string[];
28
+ export declare function attributeSpecs(fields: GraphNode[], context: MapContext): string[];
29
+ /** Limits the stored `roles` of an actor resource to the roles its actors carry, empty by default. */
30
+ export declare function constrainRoles(text: string, home: ActorHome): string;
31
+ /**
32
+ * An actor without `is`: a human one becomes a resource of its own with its fields and the private `roles`, a
33
+ * system or service one a struct. An actor bound with `is` lives in its entity's resource, which already has
34
+ * its fields and roles.
35
+ */
36
+ export declare function actorSteps(actor: GraphNode, context: MapContext, patchResource: (text: string, node: GraphNode, context: MapContext) => string): Step[];
37
+ /** A field of an actor: a column or relationship of the actor's resource, or a key of its struct. */
38
+ export declare function actorFieldSteps(field: GraphNode, context: MapContext): Step[];
package/out/actors.js ADDED
@@ -0,0 +1,105 @@
1
+ import { constant, lastOf, parentOf } from './elixir.js';
2
+ import { attributeType, calculation, fieldsOf, fileOf, mix, moduleName, patch, relationTarget, snake, task, typeModule } from './naming.js';
3
+ export function homeOf(actor, context) {
4
+ const entity = actor.data.entity ? context.node(actor.data.entity) : undefined;
5
+ const node = entity ?? actor;
6
+ return {
7
+ node, module: typeModule(node, context), resource: !!entity || actor.data.kind === 'human',
8
+ actors: entity ? context.graph.nodes.filter(n => n.kind === 'Actor' && n.data.entity === entity.qn) : [actor]
9
+ };
10
+ }
11
+ /** Every home, once each. */
12
+ export function homes(context) {
13
+ const seen = new Map();
14
+ for (const actor of context.graph.nodes.filter(n => n.kind === 'Actor')) {
15
+ const home = homeOf(actor, context);
16
+ if (!seen.has(home.node.qn))
17
+ seen.set(home.node.qn, home);
18
+ }
19
+ return [...seen.values()];
20
+ }
21
+ /** The home whose node is this entity or actor, if actors live there. */
22
+ export function homeAt(node, context) {
23
+ return homes(context).find(h => h.node.qn === node.qn);
24
+ }
25
+ /** The roles the actors of a home carry, as qualified names in declaration order. */
26
+ export function rolesOf(home) {
27
+ return [...new Set(home.actors.flatMap(a => (a.data.roles ?? [])))];
28
+ }
29
+ /** The fields an actor's record holds: the entity's fields plus the fields of every actor bound to it. */
30
+ export function homeFields(home, context) {
31
+ const own = home.node.kind === 'Entity' ? fieldsOf(home.node, context) : [];
32
+ return [...own, ...home.actors.flatMap(a => fieldsOf(a, context))];
33
+ }
34
+ /** The `--attribute` specs of the fields of the bound actors and the private `roles` of an entity that actors are bound to. */
35
+ export function actorAttributeSpecs(entity, context) {
36
+ const home = homeAt(entity, context);
37
+ if (!home)
38
+ return [];
39
+ return [...home.actors.flatMap(a => attributeSpecs(fieldsOf(a, context), context)), 'roles:atom:array'];
40
+ }
41
+ export function attributeSpecs(fields, context) {
42
+ return fields.filter(f => !f.data.derived && !relationTarget(f, context)).map(f => {
43
+ const type = f.data.type;
44
+ return [lastOf(f.qn), attributeType(type, context), ...(type.many ? ['array'] : []), ...(type.optional ? [] : ['required']), 'public'].join(':');
45
+ });
46
+ }
47
+ /** Limits the stored `roles` of an actor resource to the roles its actors carry, empty by default. */
48
+ export function constrainRoles(text, home) {
49
+ const roles = rolesOf(home).map(r => `:${snake(lastOf(r))}`).join(', ');
50
+ return text.replace(/(\n([ \t]*)attribute :roles, [^\n]* do\n)/, `$1$2 default []\n$2 constraints items: [one_of: [${roles}]]\n`);
51
+ }
52
+ /**
53
+ * An actor without `is`: a human one becomes a resource of its own with its fields and the private `roles`, a
54
+ * system or service one a struct. An actor bound with `is` lives in its entity's resource, which already has
55
+ * its fields and roles.
56
+ */
57
+ export function actorSteps(actor, context, patchResource) {
58
+ const home = homeOf(actor, context);
59
+ if (home.node.kind === 'Entity')
60
+ return [];
61
+ const fields = fieldsOf(actor, context);
62
+ if (!home.resource)
63
+ return [{ kind: 'template', file: fileOf(actor, context), write: () => struct(actor, home, context) }];
64
+ const specs = [...attributeSpecs(fields, context), 'roles:atom:array'];
65
+ return [
66
+ mix(['ash.gen.resource', home.module, '--domain', moduleName(actor.module, context),
67
+ '--default-actions', 'read,create,update,destroy', '--uuid-primary-key', 'id', '--attribute', specs.join(','),
68
+ '--extend', 'postgres', '--timestamps']),
69
+ patch(fileOf(actor, context), existing => patchResource(existing, actor, context))
70
+ ];
71
+ }
72
+ /** A field of an actor: a column or relationship of the actor's resource, or a key of its struct. */
73
+ export function actorFieldSteps(field, context) {
74
+ const home = homeOf(context.node(parentOf(field.qn)), context);
75
+ const type = field.data.type;
76
+ const target = relationTarget(field, context);
77
+ if (!home.resource)
78
+ return field.data.derived ? [task(`compute ${lastOf(field.qn)} = ${field.props.derived} in ${home.module}`)] : [];
79
+ if (target && type.many)
80
+ return [task(`model the many to many relationship ${lastOf(field.qn)} to ${target.qn}`)];
81
+ if (target) {
82
+ const spec = ['belongs_to', lastOf(field.qn), typeModule(target, context), ...(type.optional ? [] : ['required'])].join(':');
83
+ return [{ ...mix(['ash.gen.resource', home.module, '--relationship', spec]), phase: 1 }];
84
+ }
85
+ const tasks = [];
86
+ if (field.data.derived && !calculation(field, context))
87
+ tasks.push(task(`add the calculation ${lastOf(field.qn)} = ${field.props.derived} to ${home.module}`));
88
+ if (field.data.default && !field.data.derived && constant(field.data.default, context.node) === undefined)
89
+ tasks.push(task(`set the default of ${lastOf(field.qn)} to ${field.props.default}`));
90
+ return tasks;
91
+ }
92
+ function struct(actor, home, context) {
93
+ const keys = fieldsOf(actor, context).filter(f => !f.data.derived).map(f => {
94
+ const value = f.data.default ? constant(f.data.default, context.node) : undefined;
95
+ return `${lastOf(f.qn)}${relationTarget(f, context) ? '_id' : ''}: ${value ?? 'nil'}`;
96
+ });
97
+ const roles = rolesOf(home).map(r => `:${snake(lastOf(r))}`).join(', ');
98
+ return [
99
+ `defmodule ${home.module} do`,
100
+ ` @moduledoc ${JSON.stringify(`The ${actor.data.kind} actor ${lastOf(actor.qn)}. Pass %${home.module}{} as the actor.`)}`,
101
+ ` defstruct [${[...keys, `roles: [${roles}]`].join(', ')}]`,
102
+ 'end',
103
+ ''
104
+ ].join('\n');
105
+ }
package/out/api.js CHANGED
@@ -2,11 +2,14 @@ import { lastOf } from './elixir.js';
2
2
  import { app, children, fileOf, moduleName, pascal, patch, snake, task, typeModule } from './naming.js';
3
3
  import { hasPages } from './pages.js';
4
4
  import { addExtension, addToSection } from './resource.js';
5
+ import { vendorTasks } from './vendors.js';
5
6
  /**
6
7
  * A REST interface becomes AshJsonApi routes on the domain, served by a JSON:API router that Bandit
7
8
  * starts with the application, without Phoenix.
8
9
  */
9
10
  export function interfaceSteps(api, context) {
11
+ if (api.data.protocol === 'webhook')
12
+ return vendorTasks(api, context);
10
13
  if (api.data.protocol !== 'rest')
11
14
  return undefined;
12
15
  const tasks = [];
@@ -22,7 +25,7 @@ export function interfaceSteps(api, context) {
22
25
  tasks.push(task(route.note));
23
26
  }
24
27
  if (api.data.auth)
25
- tasks.push(task(`authenticate ${lastOf(api.qn)} with ${api.data.auth}, for example with AshAuthentication`));
28
+ tasks.push(task(`authenticate ${lastOf(api.qn)} with ${api.data.auth}, for example with AshAuthentication`), ...vendorTasks(api, context));
26
29
  if (api.data.rateLimit)
27
30
  tasks.push(task(`limit ${lastOf(api.qn)} to ${api.data.rateLimit} requests per ${api.data.rateUnit}`));
28
31
  if (api.data.origins?.length)
@@ -1,6 +1,6 @@
1
1
  import type { MapContext, Step } from '@appling/codegen';
2
2
  import type { GraphNode } from '@appling/model';
3
- /** A query becomes a read action of its entity's resource with filter, sort and pagination. */
3
+ /** A query becomes a read action of its entity's resource with its inputs as arguments, filter, sort and pagination. */
4
4
  export declare function querySteps(query: GraphNode, context: MapContext): Step[];
5
5
  /** Computed projection fields become calculations on the source resource; plain fields are its attributes already. */
6
6
  export declare function projectionFieldSteps(field: GraphNode, context: MapContext): Step[];
@@ -1,21 +1,28 @@
1
1
  import { ashExpr, lastOf } from './elixir.js';
2
- import { fileOf, patch, snake, task, TYPES } from './naming.js';
2
+ import { attributeType, children, fileOf, patch, snake, task, TYPES } from './naming.js';
3
3
  import { addToSection } from './resource.js';
4
- /** A query becomes a read action of its entity's resource with filter, sort and pagination. */
4
+ /** A query becomes a read action of its entity's resource with its inputs as arguments, filter, sort and pagination. */
5
5
  export function querySteps(query, context) {
6
6
  const entity = context.node(query.data.entity);
7
- const filter = query.data.filter ? ashExpr(query.data.filter, context.node) : undefined;
8
- if (query.data.filter && !filter)
9
- return [task(`filter the read action ${snake(lastOf(query.qn))} by ${query.props.filter}`)];
7
+ const translated = query.data.filter ? ashExpr(query.data.filter, context.node) : undefined;
8
+ // A filter that does not translate reads nothing until it is written, so routes and pages can name the action.
9
+ const filter = query.data.filter && !translated ? 'false' : translated;
10
+ const tasks = query.data.filter && !translated ? [task(`filter the read action ${snake(lastOf(query.qn))} by ${query.props.filter}; it reads nothing until then`)] : [];
10
11
  const sorts = (query.data.sorts ?? []).map(s => `${lastOf(s.field)}: :${s.direction ?? 'asc'}`);
11
12
  const lines = [
12
13
  `read :${snake(lastOf(query.qn))} do`,
14
+ ...children(query, context, 'Param').map(input => ` argument :${lastOf(input.qn)}, ${argumentType(input.data.type, context)}, allow_nil?: ${input.data.type.optional ? 'true' : 'false'}`),
13
15
  ...(filter ? [` filter expr(${filter})`] : []),
14
16
  ...(sorts.length ? [` prepare build(sort: [${sorts.join(', ')}])`] : []),
15
17
  ...(query.data.pageSize ? [` pagination offset?: true, default_limit: ${query.data.pageSize}, required?: false`] : []),
16
18
  'end'
17
19
  ];
18
- return [patch(fileOf(entity, context), existing => addToSection(existing, 'actions', lines))];
20
+ return [patch(fileOf(entity, context), existing => addToSection(existing, 'actions', lines)), ...tasks];
21
+ }
22
+ /** The Ash type of a read action argument; an input that names a record of an entity takes its id. */
23
+ function argumentType(type, context) {
24
+ const base = type.decl && context.node(type.decl)?.kind === 'Entity' ? ':uuid' : attributeType(type, context, true);
25
+ return type.many ? `{:array, ${base}}` : base;
19
26
  }
20
27
  /** Computed projection fields become calculations on the source resource; plain fields are its attributes already. */
21
28
  export function projectionFieldSteps(field, context) {
package/out/behavior.d.ts CHANGED
@@ -1,7 +1,11 @@
1
1
  import type { MapContext, Step } from '@appling/codegen';
2
2
  import type { GraphNode } from '@appling/model';
3
- /** An action on an entity becomes an update action of its resource: arguments, precondition validations, changes and its state transition. */
3
+ /**
4
+ * An action on an entity becomes an update action of its resource: arguments, precondition validations, changes and
5
+ * its state transition. An action that deletes its record (`delete self`) without a transition becomes a destroy action.
6
+ */
4
7
  export declare function actionSteps(action: GraphNode, context: MapContext): Step[];
8
+ export declare function effectChange(effect: GraphNode, context: MapContext): string | undefined;
5
9
  /**
6
10
  * A machine becomes an AshStateMachine section on the resource of its state field. Transitions on an event
7
11
  * get an update action named after the event, which the event's publisher has to call.
package/out/behavior.js CHANGED
@@ -1,14 +1,21 @@
1
1
  import { ashExpr, constant, lastOf, parentOf, validation } from './elixir.js';
2
- import { addExtension, addToSection } from './resource.js';
3
- import { testSteps } from './tests.js';
2
+ import { addAuthorizer, addExtension, addToSection, prependToSection } from './resource.js';
3
+ import { enforced } from './roles.js';
4
+ import { coveredByScenario } from './scenario-tests.js';
5
+ import { preconditionTests } from './model-tests.js';
4
6
  import { attributeType, children, fileOf, patch, snake, storedAttributes, task, typeModule } from './naming.js';
5
- /** An action on an entity becomes an update action of its resource: arguments, precondition validations, changes and its state transition. */
7
+ /**
8
+ * An action on an entity becomes an update action of its resource: arguments, precondition validations, changes and
9
+ * its state transition. An action that deletes its record (`delete self`) without a transition becomes a destroy action.
10
+ */
6
11
  export function actionSteps(action, context) {
7
12
  const entity = action.data.entity ? context.node(action.data.entity) : undefined;
8
13
  if (!entity)
9
14
  return [task(`implement ${lastOf(action.qn)} as a generic action`)];
10
15
  const tasks = [];
11
- const lines = [`update :${snake(lastOf(action.qn))} do`, ' require_atomic? false'];
16
+ const transitions = context.graph.nodes.filter(n => n.kind === 'Transition' && n.data.action === action.qn);
17
+ const destroy = !transitions.length && children(action, context).find(c => c.kind === 'DeleteEffect' && c.data.self);
18
+ const lines = [`${destroy ? 'destroy' : 'update'} :${snake(lastOf(action.qn))} do`, ' require_atomic? false'];
12
19
  for (const input of children(action, context, 'Param')) {
13
20
  const type = input.data.type;
14
21
  lines.push(` argument :${lastOf(input.qn)}, ${type.many ? `{:array, ${attributeType(type, context, true)}}` : attributeType(type, context, true)}, allow_nil?: ${type.optional ? 'true' : 'false'}`);
@@ -23,7 +30,6 @@ export function actionSteps(action, context) {
23
30
  else
24
31
  tasks.push(task(`check the precondition ${action.props.preconditions[i]} in ${lastOf(action.qn)}`));
25
32
  });
26
- const transitions = context.graph.nodes.filter(n => n.kind === 'Transition' && n.data.action === action.qn);
27
33
  for (const transition of transitions.filter(t => t.data.guard)) {
28
34
  const rule = validation(transition.data.guard, stored, context.node);
29
35
  if (rule && transitions.length === 1)
@@ -31,13 +37,13 @@ export function actionSteps(action, context) {
31
37
  else
32
38
  tasks.push(task(`check the guard ${transition.props.guard} of ${lastOf(transition.qn)}`));
33
39
  }
34
- const effects = [...children(action, context), ...transitions.flatMap(t => children(t, context))].filter(c => c.kind.endsWith('Effect'));
40
+ const effects = [...children(action, context), ...transitions.flatMap(t => children(t, context))].filter(c => c.kind.endsWith('Effect') && c !== destroy);
35
41
  for (const effect of effects) {
36
42
  const change = effectChange(effect, context);
37
43
  if (change)
38
44
  lines.push(` change ${change}`);
39
45
  else
40
- tasks.push(task(`apply the effect ${lastOf(effect.qn)} in ${lastOf(action.qn)}, for example with an Ash notifier or a change`));
46
+ tasks.push(task(`apply the effect ${lastOf(effect.qn)} in ${lastOf(action.qn)}, for example with ${effect.kind === 'EmitEffect' || effect.kind === 'SetEffect' ? 'an Ash notifier or a change' : 'an after_action change that writes the related records'}`));
41
47
  }
42
48
  const targets = [...new Set(transitions.map(t => t.data.to))];
43
49
  if (targets.length === 1)
@@ -47,10 +53,11 @@ export function actionSteps(action, context) {
47
53
  lines.push('end');
48
54
  if (action.data.consistency === 'eventual')
49
55
  tasks.push(task(`run ${lastOf(action.qn)} with eventual consistency, for example through AshOban`));
50
- const tests = preconditions.length ? testSteps(action, entity, `action ${snake(lastOf(action.qn))} precondition`, preconditions.map((_, i) => `${i + 1} is enforced`), context) : [];
56
+ // A scenario that runs the action replaces its guessed precondition tests.
57
+ const tests = preconditions.length && !coveredByScenario(action.qn, context) ? preconditionTests(action, entity, context) : [];
51
58
  return [patch(fileOf(entity, context), existing => addToSection(existing, 'actions', lines)), ...tasks, ...tests];
52
59
  }
53
- function effectChange(effect, context) {
60
+ export function effectChange(effect, context) {
54
61
  if (effect.kind !== 'SetEffect')
55
62
  return undefined;
56
63
  const field = lastOf(effect.data.field);
@@ -118,8 +125,11 @@ export function jobSteps(job, context) {
118
125
  'end'
119
126
  ];
120
127
  const read = [`read :${name}_targets do`, ' pagination keyset?: true, required?: false', 'end'];
128
+ // Jobs run as the system, as in the model: AshOban's scheduler and worker pass the policies of the resource.
129
+ const bypass = ['bypass AshOban.Checks.AshObanInteraction do', ' authorize_if always()', 'end'];
130
+ const authorize = (text) => !enforced(context) || text.includes(bypass[0]) ? text : addAuthorizer(prependToSection(text, 'policies', bypass));
121
131
  return [
122
- patch(fileOf(entity, context), existing => addToSection(addToSection(addExtension(existing, 'AshOban'), 'actions', read), 'oban', lines, 'triggers')),
132
+ patch(fileOf(entity, context), existing => authorize(addToSection(addToSection(addExtension(existing, 'AshOban'), 'actions', read), 'oban', lines, 'triggers'))),
123
133
  patch('config/config.exs', existing => existing.replace(/queues: \[([^\]]*)\]/, (all, list) => list.includes(`${queue}:`) ? all : `queues: [${list}, ${queue}: 10]`))
124
134
  ];
125
135
  }
package/out/elixir.d.ts CHANGED
@@ -2,10 +2,18 @@ import type { ExprData, GraphNode } from '@appling/model';
2
2
  type Lookup = (qn: string) => GraphNode | undefined;
3
3
  /** Translates an expression to the body of an Ash `expr(...)`, or returns undefined when Ash expressions cannot say it. */
4
4
  export declare function ashExpr(expr: ExprData, node: Lookup): string | undefined;
5
+ /** Whether an expression is the bare name `actor`. */
6
+ export declare function isActor(expr: ExprData | undefined): boolean;
5
7
  /** Translates a condition over stored attributes to an Ash builtin validation, or undefined. */
6
8
  export declare function validation(expr: ExprData, stored: Set<string>, node: Lookup): string | undefined;
7
9
  /** A literal or enum value as an Elixir constant. */
8
10
  export declare function constant(expr: ExprData, node: Lookup): string | undefined;
9
11
  export declare function parentOf(qn: string): string;
10
12
  export declare function lastOf(qn: string): string;
13
+ /** An Elixir string literal, without interpolation. */
14
+ export declare function elixirString(text: string): string;
15
+ /** The `@moduledoc` lines of a node's `does` text, a heredoc when it spans lines; none without a text. */
16
+ export declare function moduledoc(node: GraphNode): string;
17
+ /** Puts the node's `@moduledoc` first in the module. */
18
+ export declare function withModuledoc(text: string, node: GraphNode): string;
11
19
  export {};
package/out/elixir.js CHANGED
@@ -18,6 +18,15 @@ export function ashExpr(expr, node) {
18
18
  const shift = relativeTime(expr);
19
19
  if (shift)
20
20
  return shift;
21
+ if (expr.op === '==' || expr.op === '!=') {
22
+ // A query input compared with null, as an optional input's filter writes it: `since == null`.
23
+ const input = [expr.left, expr.right].find(e => isInput(e, node));
24
+ if (input && [expr.left, expr.right].some(e => e.$type === 'NullExpr'))
25
+ return `${expr.op === '!=' ? 'not ' : ''}is_nil(^arg(:${input.name}))`;
26
+ const references = [referenceId(expr.left, node), referenceId(expr.right, node)];
27
+ if (references.some(r => r && r !== 'nil') && references.every(Boolean))
28
+ return `${references[0]} ${expr.op} ${references[1]}`;
29
+ }
21
30
  const [left, right] = [sub(expr.left), sub(expr.right)];
22
31
  return left && right && `${wrap(left)} ${OPERATORS[expr.op] ?? expr.op} ${wrap(right)}`;
23
32
  }
@@ -33,16 +42,74 @@ export function ashExpr(expr, node) {
33
42
  return `:${expr.name}`;
34
43
  if (target?.kind === 'Param')
35
44
  return `^arg(:${expr.name})`;
36
- return target?.kind === 'Field' && node(parentOf(target.qn))?.kind === 'Entity' ? expr.name : undefined;
45
+ if (target?.kind === 'Tenant')
46
+ return '^tenant()';
47
+ return target && isRecordField(target, node) ? expr.name : undefined;
37
48
  }
38
49
  case 'MemberExpr': {
39
- const receiver = !expr.call && sub(expr.receiver);
40
50
  const target = expr.target ? node(expr.target) : undefined;
51
+ if (isActor(expr.receiver) && !expr.call)
52
+ return target && isRecordField(target, node) ? `^actor(:${expr.member})` : undefined;
53
+ const receiver = !expr.call && sub(expr.receiver);
41
54
  return receiver && target?.kind === 'Field' && node(parentOf(target.qn))?.kind === 'Entity' ? `${receiver}.${expr.member}` : undefined;
42
55
  }
43
56
  default: return undefined;
44
57
  }
45
58
  }
59
+ /** Whether an expression is the bare name `actor`. */
60
+ export function isActor(expr) {
61
+ return expr?.$type === 'NameExpr' && expr.name === 'actor' && !expr.target && !expr.call;
62
+ }
63
+ /** A field of an entity or of an actor, which the actor's resource or struct holds. */
64
+ function isRecordField(target, node) {
65
+ const owner = node(parentOf(target.qn))?.kind;
66
+ return target.kind === 'Field' && (owner === 'Entity' || owner === 'Actor');
67
+ }
68
+ /**
69
+ * A side of a comparison between records as the id Ash compares: `customer` becomes `customer_id`, `buyer.company`
70
+ * `buyer.company_id`, `actor.account` `^actor(:account_id)`, `actor` `^actor(:id)`, `this` `id`, `tenant` `^tenant()`
71
+ * and `null` `nil`. Undefined for anything that is not a record.
72
+ */
73
+ function referenceId(expr, node) {
74
+ if (expr.$type === 'NullExpr')
75
+ return 'nil';
76
+ if (isActor(expr))
77
+ return '^actor(:id)';
78
+ if (expr.$type === 'NameExpr' && !expr.call) {
79
+ if (expr.name === 'this' && !expr.target)
80
+ return 'id';
81
+ const target = expr.target ? node(expr.target) : undefined;
82
+ if (target?.kind === 'Tenant')
83
+ return '^tenant()';
84
+ // An input that names a record, such as `of: Customer` of a query, is the record's id.
85
+ if (target?.kind === 'Param' && isRecordType(target, node))
86
+ return `^arg(:${expr.name})`;
87
+ return target && isRelation(target, node) ? `${expr.name}_id` : undefined;
88
+ }
89
+ if (expr.$type === 'MemberExpr' && !expr.call) {
90
+ const target = expr.target ? node(expr.target) : undefined;
91
+ if (!target || !isRelation(target, node))
92
+ return undefined;
93
+ if (isActor(expr.receiver))
94
+ return `^actor(:${expr.member}_id)`;
95
+ const receiver = ashExpr(expr.receiver, node);
96
+ return receiver && `${receiver}.${expr.member}_id`;
97
+ }
98
+ return undefined;
99
+ }
100
+ /** A single valued field whose type is an entity, a `belongs_to` relationship. */
101
+ function isRelation(target, node) {
102
+ return isRecordField(target, node) && isRecordType(target, node);
103
+ }
104
+ /** A field or input that holds one record of an entity. */
105
+ function isRecordType(target, node) {
106
+ const type = target.data.type;
107
+ return !!type?.decl && !type.many && node(type.decl)?.kind === 'Entity';
108
+ }
109
+ /** The bare name of an input, such as a query input. */
110
+ function isInput(expr, node) {
111
+ return expr.$type === 'NameExpr' && !expr.call && !!expr.target && node(expr.target)?.kind === 'Param';
112
+ }
46
113
  /** Translates a condition over stored attributes to an Ash builtin validation, or undefined. */
47
114
  export function validation(expr, stored, node) {
48
115
  const field = (e) => e?.$type === 'NameExpr' && !e.call && e.target && stored.has(e.target) ? e.name : undefined;
@@ -101,7 +168,20 @@ function relativeTime(expr) {
101
168
  return `${expr.op === '-' ? 'ago' : 'from_now'}(${match[1]}, :${UNITS[match[2]]})`;
102
169
  }
103
170
  function wrap(code) {
104
- return /^[\w.:]+(\(.*\))?$/.test(code) || /^".*"$/.test(code) || /^\[.*\]$/.test(code) ? code : `(${code})`;
171
+ const call = /^\^?[\w.:]+(\(.*\))?$/.exec(code);
172
+ // `is_nil(a) or (b)` looks like one call to the pattern; the call's parenthesis has to close at the end.
173
+ return (call && (!call[1] || closesAtEnd(call[1]))) || /^".*"$/.test(code) || /^\[.*\]$/.test(code) ? code : `(${code})`;
174
+ }
175
+ /** Whether the parenthesis that opens the text closes only at its end. */
176
+ function closesAtEnd(text) {
177
+ let depth = 0;
178
+ for (let i = 0; i < text.length; i++) {
179
+ if (text[i] === '(')
180
+ depth++;
181
+ else if (text[i] === ')' && --depth === 0)
182
+ return i === text.length - 1;
183
+ }
184
+ return false;
105
185
  }
106
186
  function joined(parts, combine) {
107
187
  return parts.every(p => p !== undefined) ? combine(parts) : undefined;
@@ -112,3 +192,22 @@ export function parentOf(qn) {
112
192
  export function lastOf(qn) {
113
193
  return qn.slice(qn.lastIndexOf('.') + 1);
114
194
  }
195
+ /** An Elixir string literal, without interpolation. */
196
+ export function elixirString(text) {
197
+ return `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/#\{/g, '\\#{').replace(/\n/g, '\\n')}"`;
198
+ }
199
+ /** The `@moduledoc` lines of a node's `does` text, a heredoc when it spans lines; none without a text. */
200
+ export function moduledoc(node) {
201
+ const text = node.data.does;
202
+ if (typeof text !== 'string' || !text.trim())
203
+ return '';
204
+ if (!text.includes('\n'))
205
+ return ` @moduledoc ${elixirString(text)}\n\n`;
206
+ const body = text.replace(/\\/g, '\\\\').replace(/#\{/g, '\\#{').replace(/"""/g, '\\"""').split('\n').map(l => l ? ` ${l}` : '').join('\n');
207
+ return ` @moduledoc """\n${body}\n """\n\n`;
208
+ }
209
+ /** Puts the node's `@moduledoc` first in the module. */
210
+ export function withModuledoc(text, node) {
211
+ const doc = moduledoc(node);
212
+ return doc ? text.replace(/^(defmodule [^\n]* do\n)/, head => head + doc) : text;
213
+ }