@appling/codegen-ash 0.1.5 → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +7 -3
- package/out/actors.js +3 -9
- package/out/api.js +10 -11
- package/out/application.js +10 -11
- package/out/behavior.js +22 -31
- package/out/elixir.d.ts +3 -1
- package/out/elixir.js +9 -4
- package/out/index.js +17 -16
- package/out/migrations.js +5 -5
- package/out/naming.d.ts +2 -0
- package/out/naming.js +5 -0
- package/out/pages.js +19 -63
- package/out/roles.js +9 -36
- package/out/scenario-tests.js +6 -19
- package/out/tests.js +3 -5
- package/out/vendors.js +6 -21
- package/package.json +7 -6
- package/templates/access/actor-check.ex.njk +6 -0
- package/templates/access/actor-struct.ex.njk +9 -0
- package/templates/access/check.ex.njk +14 -0
- package/templates/access/oban-bypass.ex.njk +4 -0
- package/templates/access/policy.ex.njk +19 -0
- package/templates/access/role-check.ex.njk +15 -0
- package/templates/api/router.ex.njk +4 -0
- package/templates/api/routes.ex.njk +7 -0
- package/templates/application/query.ex.njk +28 -0
- package/templates/behavior/action.ex.njk +23 -0
- package/templates/behavior/state-machine.ex.njk +4 -0
- package/templates/behavior/transitions.ex.njk +4 -0
- package/templates/behavior/trigger-read.ex.njk +4 -0
- package/templates/behavior/trigger.ex.njk +10 -0
- package/templates/config/env-key.njk +4 -0
- package/templates/config/env.example.njk +2 -0
- package/templates/config/runtime-key.exs.njk +7 -0
- package/templates/config/runtime.exs.njk +2 -0
- package/templates/migrations/migration.exs.njk +7 -0
- package/templates/migrations/statement.exs.njk +12 -0
- package/templates/pages/live.ex.njk +92 -0
- package/templates/resources/embedded.ex.njk +18 -0
- package/templates/resources/sections.ex.njk +31 -0
- package/templates/tests/cases.exs.njk +16 -0
- package/templates/tests/module.exs.njk +6 -0
- package/templates/tests/scenario.exs.njk +14 -0
- package/templates/tests/scenarios.exs.njk +14 -0
package/LICENSE
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
MIT License
|
|
2
2
|
|
|
3
|
-
Copyright (c) 2026 Alexandros Fotiadis
|
|
3
|
+
Copyright (c) 2026 Alexandros Fotiadis, alexandros.fotiadis@techthos.net
|
|
4
4
|
|
|
5
5
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
6
|
of this software and associated documentation files (the "Software"), to deal
|
package/README.md
CHANGED
|
@@ -12,7 +12,7 @@ Appling code generation extension for [Ash](https://ash-hq.org) on Elixir. It tu
|
|
|
12
12
|
|
|
13
13
|
The project is created next to the output folder with `mix igniter.new <name>`, so the project name (the `name` option, or by default the output folder's name) must be the output folder's name.
|
|
14
14
|
|
|
15
|
-
Requires Elixir 1.17 or later and the `igniter_new` archive (`mix archive.install hex igniter_new`).
|
|
15
|
+
Requires Elixir 1.17 or later and the `igniter_new` archive (`mix archive.install hex igniter_new`). Models with pages also need the `phx_new` archive (`mix archive.install hex phx_new`).
|
|
16
16
|
|
|
17
17
|
## What it generates
|
|
18
18
|
|
|
@@ -39,8 +39,8 @@ Requires Elixir 1.17 or later and the `igniter_new` archive (`mix archive.instal
|
|
|
39
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 |
|
|
40
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 |
|
|
41
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 |
|
|
42
|
-
| `describe` | `@moduledoc` of resources
|
|
43
|
-
| `does` | a registry task |
|
|
42
|
+
| `describe` | `@moduledoc` of enums, resources, embedded resources and LiveViews, `description` of attributes, read actions and JSON:API routes |
|
|
43
|
+
| `holds`, `does`, `handles`, `serves`, `shows` | a registry task, and like `describe` on enums, resources, embedded resources, queries, REST interfaces and pages |
|
|
44
44
|
| 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 |
|
|
45
45
|
| `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 |
|
|
46
46
|
|
|
@@ -52,6 +52,10 @@ Machines, scheduled jobs and REST interfaces add `ash_state_machine`, `ash_oban`
|
|
|
52
52
|
|
|
53
53
|
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`.
|
|
54
54
|
|
|
55
|
+
## Templates
|
|
56
|
+
|
|
57
|
+
The generated code comes from the Nunjucks templates in `templates/` of this package, one per element kind. Override one with a file at the same path in `.appling/templates/ash/` of your project; see [Templates](https://www.appling.tools/docs/codegen/templates/).
|
|
58
|
+
|
|
55
59
|
## License
|
|
56
60
|
|
|
57
61
|
MIT
|
package/out/actors.js
CHANGED
|
@@ -92,14 +92,8 @@ export function actorFieldSteps(field, context) {
|
|
|
92
92
|
function struct(actor, home, context) {
|
|
93
93
|
const keys = fieldsOf(actor, context).filter(f => !f.data.derived).map(f => {
|
|
94
94
|
const value = f.data.default ? constant(f.data.default, context.node) : undefined;
|
|
95
|
-
return `${lastOf(f.qn)}${relationTarget(f, context) ? '_id' : ''}:
|
|
95
|
+
return { name: `${lastOf(f.qn)}${relationTarget(f, context) ? '_id' : ''}`, value: value ?? 'nil' };
|
|
96
96
|
});
|
|
97
|
-
const roles = rolesOf(home).map(r => `:${snake(lastOf(r))}`)
|
|
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');
|
|
97
|
+
const roles = rolesOf(home).map(r => `:${snake(lastOf(r))}`);
|
|
98
|
+
return `${context.render('access/actor-struct.ex.njk', { module: home.module, kind: actor.data.kind, name: lastOf(actor.qn), keys, roles })}\n`;
|
|
105
99
|
}
|
package/out/api.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { lastOf } from './elixir.js';
|
|
2
|
-
import { app, children, fileOf, moduleName, pascal, patch, snake, task, typeModule } from './naming.js';
|
|
1
|
+
import { descriptionOf, lastOf } from './elixir.js';
|
|
2
|
+
import { app, children, fileOf, moduleName, pascal, patch, sectionLines, snake, task, typeModule } from './naming.js';
|
|
3
3
|
import { hasPages } from './pages.js';
|
|
4
4
|
import { addExtension, addToSection } from './resource.js';
|
|
5
5
|
import { vendorTasks } from './vendors.js';
|
|
@@ -20,7 +20,7 @@ export function interfaceSteps(api, context) {
|
|
|
20
20
|
tasks.push(task(`expose ${endpoint.data.verb} ${endpoint.data.path} -> ${lastOf(endpoint.data.target)}`));
|
|
21
21
|
continue;
|
|
22
22
|
}
|
|
23
|
-
routes.set(route.resource, [...(routes.get(route.resource) ?? []), route
|
|
23
|
+
routes.set(route.resource, [...(routes.get(route.resource) ?? []), route]);
|
|
24
24
|
if (route.note)
|
|
25
25
|
tasks.push(task(route.note));
|
|
26
26
|
}
|
|
@@ -40,15 +40,15 @@ export function interfaceSteps(api, context) {
|
|
|
40
40
|
{
|
|
41
41
|
kind: 'template', phase: 2, file: `lib/${app(context)}/api_router.ex`, write: existing => existing
|
|
42
42
|
? existing.replace(/domains: \[([^\]]*)\]/, (all, list) => list.includes(domain) ? all : `domains: [${list}, ${domain}]`)
|
|
43
|
-
:
|
|
43
|
+
: `${context.render('api/router.ex.njk', { module: router, domain })}\n`
|
|
44
44
|
},
|
|
45
45
|
patch(`lib/${app(context)}/application.ex`, existing => existing.includes('Bandit')
|
|
46
46
|
? existing
|
|
47
47
|
: existing.replace(/children = \[\n/, `children = [\n {Bandit, plug: ${router}, port: 4000},\n`))
|
|
48
48
|
];
|
|
49
|
-
const resourceSteps = [...routes].flatMap(([resource,
|
|
49
|
+
const resourceSteps = [...routes].flatMap(([resource, list]) => [
|
|
50
50
|
patch(fileOf(resource, context), existing => existing.includes('\n json_api do\n') ? existing : addToSection(addExtension(existing, 'AshJsonApi.Resource'), 'json_api', [`type ${JSON.stringify(snake(lastOf(resource.qn)))}`])),
|
|
51
|
-
patch(domainFile(api, context), existing => addToSection(addExtension(existing, 'AshJsonApi.Domain'), 'json_api',
|
|
51
|
+
patch(domainFile(api, context), existing => addToSection(addExtension(existing, 'AshJsonApi.Domain'), 'json_api', sectionLines(context, 'api/routes.ex.njk', { resource: typeModule(resource, context), routes: list, description: descriptionOf(api) }), 'routes'))
|
|
52
52
|
]);
|
|
53
53
|
return [
|
|
54
54
|
...resourceSteps,
|
|
@@ -56,19 +56,18 @@ export function interfaceSteps(api, context) {
|
|
|
56
56
|
...tasks
|
|
57
57
|
];
|
|
58
58
|
}
|
|
59
|
-
/** The route
|
|
59
|
+
/** The route of one endpoint, relative to "/" of its resource. */
|
|
60
60
|
function endpointRoute(endpoint, context) {
|
|
61
61
|
const target = context.node(endpoint.data.target);
|
|
62
62
|
const verb = endpoint.data.verb;
|
|
63
63
|
const path = endpoint.data.path.replace(/\{id\}/g, ':id').replace(/\{(\w+)\}/g, ':$1');
|
|
64
64
|
if (verb === 'GET' && target.kind === 'Query') {
|
|
65
|
-
const fields = (endpoint.data.picks ?? []).map(
|
|
66
|
-
|
|
67
|
-
return { resource: context.node(target.data.entity), line: `index :${snake(lastOf(target.qn))}, ${options.join(', ')}` };
|
|
65
|
+
const fields = (endpoint.data.picks ?? []).map(lastOf);
|
|
66
|
+
return { resource: context.node(target.data.entity), verb: 'index', action: snake(lastOf(target.qn)), path, fields };
|
|
68
67
|
}
|
|
69
68
|
if (['POST', 'PUT', 'PATCH'].includes(verb) && target.kind === 'Action' && target.data.entity && path.includes(':id')) {
|
|
70
69
|
const note = verb === 'PATCH' ? undefined : `${verb} ${endpoint.data.path} is served as PATCH, the JSON:API method for update actions`;
|
|
71
|
-
return { resource: context.node(target.data.entity),
|
|
70
|
+
return { resource: context.node(target.data.entity), verb: 'patch', action: snake(lastOf(target.qn)), path, fields: [], note };
|
|
72
71
|
}
|
|
73
72
|
return undefined;
|
|
74
73
|
}
|
package/out/application.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ashExpr, lastOf } from './elixir.js';
|
|
2
|
-
import { attributeType, children, fileOf, patch, snake, task, TYPES } from './naming.js';
|
|
1
|
+
import { ashExpr, descriptionOf, lastOf } from './elixir.js';
|
|
2
|
+
import { attributeType, children, fileOf, patch, sectionLines, snake, task, TYPES } from './naming.js';
|
|
3
3
|
import { addToSection } from './resource.js';
|
|
4
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) {
|
|
@@ -8,15 +8,14 @@ export function querySteps(query, context) {
|
|
|
8
8
|
// A filter that does not translate reads nothing until it is written, so routes and pages can name the action.
|
|
9
9
|
const filter = query.data.filter && !translated ? 'false' : translated;
|
|
10
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`)] : [];
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
];
|
|
11
|
+
const lines = sectionLines(context, 'application/query.ex.njk', {
|
|
12
|
+
name: snake(lastOf(query.qn)),
|
|
13
|
+
description: descriptionOf(query),
|
|
14
|
+
arguments: children(query, context, 'Param').map(input => ({ name: lastOf(input.qn), type: argumentType(input.data.type, context), optional: input.data.type.optional })),
|
|
15
|
+
filter,
|
|
16
|
+
sorts: (query.data.sorts ?? []).map(s => ({ field: lastOf(s.field), direction: s.direction ?? 'asc' })),
|
|
17
|
+
pageSize: query.data.pageSize
|
|
18
|
+
});
|
|
20
19
|
return [patch(fileOf(entity, context), existing => addToSection(existing, 'actions', lines)), ...tasks];
|
|
21
20
|
}
|
|
22
21
|
/** The Ash type of a read action argument; an input that names a record of an entity takes its id. */
|
package/out/behavior.js
CHANGED
|
@@ -3,7 +3,7 @@ import { addAuthorizer, addExtension, addToSection, prependToSection } from './r
|
|
|
3
3
|
import { enforced } from './roles.js';
|
|
4
4
|
import { coveredByScenario } from './scenario-tests.js';
|
|
5
5
|
import { preconditionTests } from './model-tests.js';
|
|
6
|
-
import { attributeType, children, fileOf, patch, snake, storedAttributes, task, typeModule } from './naming.js';
|
|
6
|
+
import { attributeType, children, fileOf, patch, sectionLines, snake, storedAttributes, task, typeModule } from './naming.js';
|
|
7
7
|
/**
|
|
8
8
|
* An action on an entity becomes an update action of its resource: arguments, precondition validations, changes and
|
|
9
9
|
* its state transition. An action that deletes its record (`delete self`) without a transition becomes a destroy action.
|
|
@@ -15,42 +15,43 @@ export function actionSteps(action, context) {
|
|
|
15
15
|
const tasks = [];
|
|
16
16
|
const transitions = context.graph.nodes.filter(n => n.kind === 'Transition' && n.data.action === action.qn);
|
|
17
17
|
const destroy = !transitions.length && children(action, context).find(c => c.kind === 'DeleteEffect' && c.data.self);
|
|
18
|
-
const
|
|
19
|
-
for (const input of children(action, context, 'Param')) {
|
|
18
|
+
const args = children(action, context, 'Param').map(input => {
|
|
20
19
|
const type = input.data.type;
|
|
21
|
-
|
|
22
|
-
}
|
|
20
|
+
return { name: lastOf(input.qn), type: type.many ? `{:array, ${attributeType(type, context, true)}}` : attributeType(type, context, true), optional: type.optional };
|
|
21
|
+
});
|
|
22
|
+
const validations = [];
|
|
23
23
|
const stored = storedAttributes(entity, context);
|
|
24
24
|
const preconditions = (action.data.preconditions ?? []);
|
|
25
25
|
preconditions.forEach((precondition, i) => {
|
|
26
26
|
const rule = validation(precondition.condition, stored, context.node);
|
|
27
27
|
const message = precondition.error ? lastOf(precondition.error) : action.props.preconditions[i];
|
|
28
28
|
if (rule)
|
|
29
|
-
|
|
29
|
+
validations.push({ rule, message });
|
|
30
30
|
else
|
|
31
31
|
tasks.push(task(`check the precondition ${action.props.preconditions[i]} in ${lastOf(action.qn)}`));
|
|
32
32
|
});
|
|
33
33
|
for (const transition of transitions.filter(t => t.data.guard)) {
|
|
34
34
|
const rule = validation(transition.data.guard, stored, context.node);
|
|
35
35
|
if (rule && transitions.length === 1)
|
|
36
|
-
|
|
36
|
+
validations.push({ rule, message: 'invalid transition' });
|
|
37
37
|
else
|
|
38
38
|
tasks.push(task(`check the guard ${transition.props.guard} of ${lastOf(transition.qn)}`));
|
|
39
39
|
}
|
|
40
|
+
const changes = [];
|
|
40
41
|
const effects = [...children(action, context), ...transitions.flatMap(t => children(t, context))].filter(c => c.kind.endsWith('Effect') && c !== destroy);
|
|
41
42
|
for (const effect of effects) {
|
|
42
43
|
const change = effectChange(effect, context);
|
|
43
44
|
if (change)
|
|
44
|
-
|
|
45
|
+
changes.push(change);
|
|
45
46
|
else
|
|
46
47
|
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'}`));
|
|
47
48
|
}
|
|
48
49
|
const targets = [...new Set(transitions.map(t => t.data.to))];
|
|
49
|
-
if (targets.length
|
|
50
|
-
lines.push(` change transition_state(:${targets[0]})`);
|
|
51
|
-
else if (targets.length > 1)
|
|
50
|
+
if (targets.length > 1)
|
|
52
51
|
tasks.push(task(`pick the target state of ${lastOf(action.qn)} among ${targets.join(', ')}`));
|
|
53
|
-
lines
|
|
52
|
+
const lines = sectionLines(context, 'behavior/action.ex.njk', {
|
|
53
|
+
type: destroy ? 'destroy' : 'update', name: snake(lastOf(action.qn)), arguments: args, validations, changes, state: targets.length === 1 ? targets[0] : undefined
|
|
54
|
+
});
|
|
54
55
|
if (action.data.consistency === 'eventual')
|
|
55
56
|
tasks.push(task(`run ${lastOf(action.qn)} with eventual consistency, for example through AshOban`));
|
|
56
57
|
// A scenario that runs the action replaces its guessed precondition tests.
|
|
@@ -81,14 +82,13 @@ export function machineSteps(machine, context) {
|
|
|
81
82
|
const initial = field.data.default?.name ?? literals[0];
|
|
82
83
|
const transitions = children(machine, context, 'Transition');
|
|
83
84
|
const byEvent = Map.groupBy(transitions.filter(t => t.data.event), t => t.data.event);
|
|
84
|
-
const settings =
|
|
85
|
-
const lines = transitions.
|
|
86
|
-
|
|
87
|
-
return `transition :${action}, from: [${t.data.from.map(s => `:${s}`).join(', ')}], to: :${t.data.to}`;
|
|
85
|
+
const settings = sectionLines(context, 'behavior/state-machine.ex.njk', { initial, field: lastOf(field.qn) });
|
|
86
|
+
const lines = sectionLines(context, 'behavior/transitions.ex.njk', {
|
|
87
|
+
transitions: transitions.map(t => ({ action: snake(lastOf((t.data.action ?? t.data.event))), from: t.data.from, to: t.data.to }))
|
|
88
88
|
});
|
|
89
89
|
const eventActions = [...byEvent].flatMap(([event, list]) => {
|
|
90
90
|
const targets = [...new Set(list.map(t => t.data.to))];
|
|
91
|
-
return targets.length === 1 ? [
|
|
91
|
+
return targets.length === 1 ? [sectionLines(context, 'behavior/action.ex.njk', { type: 'update', name: snake(lastOf(event)), arguments: [], validations: [], changes: [], state: targets[0] })] : [];
|
|
92
92
|
});
|
|
93
93
|
return [
|
|
94
94
|
patch(fileOf(entity, context), existing => {
|
|
@@ -113,20 +113,11 @@ export function jobSteps(job, context) {
|
|
|
113
113
|
const module = typeModule(entity, context);
|
|
114
114
|
const pascal = lastOf(job.qn);
|
|
115
115
|
const queue = `${snake(lastOf(entity.qn))}_${name}`;
|
|
116
|
-
const lines =
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
` where expr(${where})`,
|
|
122
|
-
` scheduler_cron ${JSON.stringify(job.data.schedule)}`,
|
|
123
|
-
` worker_module_name ${module}.AshOban.Worker.${pascal}`,
|
|
124
|
-
` scheduler_module_name ${module}.AshOban.Scheduler.${pascal}`,
|
|
125
|
-
'end'
|
|
126
|
-
];
|
|
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'];
|
|
116
|
+
const lines = sectionLines(context, 'behavior/trigger.ex.njk', {
|
|
117
|
+
name, action: snake(lastOf(action.qn)), queue, where, schedule: job.data.schedule, module, job: pascal
|
|
118
|
+
});
|
|
119
|
+
const read = sectionLines(context, 'behavior/trigger-read.ex.njk', { name });
|
|
120
|
+
const bypass = sectionLines(context, 'access/oban-bypass.ex.njk', {});
|
|
130
121
|
const authorize = (text) => !enforced(context) || text.includes(bypass[0]) ? text : addAuthorizer(prependToSection(text, 'policies', bypass));
|
|
131
122
|
return [
|
|
132
123
|
patch(fileOf(entity, context), existing => authorize(addToSection(addToSection(addExtension(existing, 'AshOban'), 'actions', read), 'oban', lines, 'triggers'))),
|
package/out/elixir.d.ts
CHANGED
|
@@ -12,8 +12,10 @@ export declare function parentOf(qn: string): string;
|
|
|
12
12
|
export declare function lastOf(qn: string): string;
|
|
13
13
|
/** An Elixir string literal, without interpolation. */
|
|
14
14
|
export declare function elixirString(text: string): string;
|
|
15
|
-
/** The `@moduledoc` lines of a node's `describe` and
|
|
15
|
+
/** The `@moduledoc` lines of a node's `describe` text and annotation, a heredoc when they span lines; none without a text. */
|
|
16
16
|
export declare function moduledoc(node: GraphNode): string;
|
|
17
|
+
/** A node's `describe` text and annotation as an Elixir string, for a `description` option; none without a text. */
|
|
18
|
+
export declare function descriptionOf(node: GraphNode): string | undefined;
|
|
17
19
|
/** Puts the node's `@moduledoc` first in the module. */
|
|
18
20
|
export declare function withModuledoc(text: string, node: GraphNode): string;
|
|
19
21
|
export {};
|
package/out/elixir.js
CHANGED
|
@@ -197,18 +197,23 @@ export function lastOf(qn) {
|
|
|
197
197
|
export function elixirString(text) {
|
|
198
198
|
return `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/#\{/g, '\\#{').replace(/\n/g, '\\n')}"`;
|
|
199
199
|
}
|
|
200
|
-
/** The `@moduledoc` lines of a node's `describe` and
|
|
200
|
+
/** The `@moduledoc` lines of a node's `describe` text and annotation, a heredoc when they span lines; none without a text. */
|
|
201
201
|
export function moduledoc(node) {
|
|
202
202
|
const text = aboutOf(node);
|
|
203
203
|
if (!text)
|
|
204
204
|
return '';
|
|
205
205
|
if (!text.includes('\n'))
|
|
206
|
-
return ` @moduledoc ${elixirString(text)}
|
|
206
|
+
return ` @moduledoc ${elixirString(text)}`;
|
|
207
207
|
const body = text.replace(/\\/g, '\\\\').replace(/#\{/g, '\\#{').replace(/"""/g, '\\"""').split('\n').map(l => l ? ` ${l}` : '').join('\n');
|
|
208
|
-
return ` @moduledoc """\n${body}\n """
|
|
208
|
+
return ` @moduledoc """\n${body}\n """`;
|
|
209
|
+
}
|
|
210
|
+
/** A node's `describe` text and annotation as an Elixir string, for a `description` option; none without a text. */
|
|
211
|
+
export function descriptionOf(node) {
|
|
212
|
+
const text = aboutOf(node);
|
|
213
|
+
return text && elixirString(text);
|
|
209
214
|
}
|
|
210
215
|
/** Puts the node's `@moduledoc` first in the module. */
|
|
211
216
|
export function withModuledoc(text, node) {
|
|
212
217
|
const doc = moduledoc(node);
|
|
213
|
-
return doc ? text.replace(/^(defmodule [^\n]* do\n)/, head => head
|
|
218
|
+
return doc ? text.replace(/^(defmodule [^\n]* do\n)/, head => `${head}${doc}\n\n`) : text;
|
|
214
219
|
}
|
package/out/index.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { fileURLToPath } from 'node:url';
|
|
1
2
|
import { interfaceSteps } from './api.js';
|
|
2
3
|
import { projectionFieldSteps, querySteps } from './application.js';
|
|
3
4
|
import { actionSteps, jobSteps, machineSteps } from './behavior.js';
|
|
4
|
-
import { elixirString, lastOf, parentOf, withModuledoc } from './elixir.js';
|
|
5
|
+
import { elixirString, lastOf, moduledoc, parentOf, withModuledoc } from './elixir.js';
|
|
5
6
|
import { migrationSteps } from './migrations.js';
|
|
6
7
|
import { hasPages, navigationSteps, pageSteps } from './pages.js';
|
|
7
8
|
import { actorAttributeSpecs, actorFieldSteps, actorSteps, constrainRoles, homeAt, homeFields } from './actors.js';
|
|
@@ -14,6 +15,7 @@ import { externalKeySteps, secretPlaceholders } from './vendors.js';
|
|
|
14
15
|
import { app, attributeType, calculation, fieldPolicyOf, fieldsOf, fileOf, mix, moduleName, patch, relationTarget, leftToCode, task, typeModule } from './naming.js';
|
|
15
16
|
const extension = {
|
|
16
17
|
name: '@appling/codegen-ash',
|
|
18
|
+
templates: fileURLToPath(new URL('../templates', import.meta.url)),
|
|
17
19
|
test: ['mix', 'test'],
|
|
18
20
|
syncExclude: ['deps/**', '_build/**', 'priv/repo/migrations/**', 'priv/resource_snapshots/**', 'priv/static/**', 'mix.lock'],
|
|
19
21
|
migrate: migrationSteps,
|
|
@@ -40,7 +42,10 @@ const extension = {
|
|
|
40
42
|
steps(node, context) {
|
|
41
43
|
switch (node.kind) {
|
|
42
44
|
case 'Module': return [mix(['ash.gen.domain', moduleName(node.qn, context)])];
|
|
43
|
-
case 'Enum': return [
|
|
45
|
+
case 'Enum': return [
|
|
46
|
+
mix(['ash.gen.enum', typeModule(node, context), context.children(node.qn).map(l => lastOf(l.qn)).join(',')]),
|
|
47
|
+
...(moduledoc(node) ? [patch(fileOf(node, context), existing => withModuledoc(existing, node))] : [])
|
|
48
|
+
];
|
|
44
49
|
case 'ValueType': return [{ kind: 'template', file: fileOf(node, context), write: () => embedded(node, context) }];
|
|
45
50
|
case 'Entity': return entitySteps(node, context);
|
|
46
51
|
case 'EnumLiteral': return [];
|
|
@@ -149,24 +154,20 @@ function patchResource(text, entity, context) {
|
|
|
149
154
|
text = text.replace(new RegExp(`(\\n([ \\t]*)attribute :${lastOf(field.qn)}, [^\\n]* do\\n)`), (_, head, indent) => `${head}${indent} description ${elixirString(field.data.describe)}\n`);
|
|
150
155
|
}
|
|
151
156
|
text = withModuledoc(text, entity);
|
|
152
|
-
const
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
157
|
+
const sections = context.render('resources/sections.ex.njk', {
|
|
158
|
+
identities: fields.filter(f => (f.data.modifiers ?? []).includes('unique')).map(f => lastOf(f.qn)),
|
|
159
|
+
calculations: [...fields.flatMap(f => calculation(f, context) ?? []), ...roleCalculations(entity, context)],
|
|
160
|
+
validations: context.children(entity.qn).filter(n => n.kind === 'Invariant').flatMap(n => {
|
|
156
161
|
const rule = check(n, context);
|
|
157
|
-
return rule ? [
|
|
158
|
-
})
|
|
159
|
-
|
|
160
|
-
return closeResource(
|
|
161
|
-
}
|
|
162
|
-
function block(name, lines) {
|
|
163
|
-
return lines.length ? `\n ${name} do\n${lines.map(l => ` ${l}\n`).join('')} end\n` : '';
|
|
162
|
+
return rule ? [{ rule, message: n.data.label }] : [];
|
|
163
|
+
})
|
|
164
|
+
});
|
|
165
|
+
return closeResource(sections ? text.replace(/\nend\n?$/, `\n\n${sections}\nend\n`) : text, entity, context);
|
|
164
166
|
}
|
|
165
167
|
function embedded(node, context) {
|
|
166
168
|
const attributes = fieldsOf(node, context).filter(f => !f.data.derived).map(f => {
|
|
167
169
|
const type = f.data.type;
|
|
168
|
-
|
|
169
|
-
return ` attribute :${lastOf(f.qn)}, ${elixirType}, allow_nil?: ${type.optional ? 'true' : 'false'}, public?: true\n`;
|
|
170
|
+
return { name: lastOf(f.qn), type: type.many ? `{:array, ${attributeType(type, context, true)}}` : attributeType(type, context, true), optional: type.optional };
|
|
170
171
|
});
|
|
171
|
-
return
|
|
172
|
+
return `${context.render('resources/embedded.ex.njk', { module: typeModule(node, context), moduledoc: moduledoc(node), attributes })}\n`;
|
|
172
173
|
}
|
package/out/migrations.js
CHANGED
|
@@ -25,27 +25,27 @@ export function migrationSteps(change, context, files) {
|
|
|
25
25
|
let statement;
|
|
26
26
|
if (change.kind === 'rename') {
|
|
27
27
|
patch = text => text.replace(atom, `:${change.newName}`);
|
|
28
|
-
statement =
|
|
28
|
+
statement = { newName: change.newName };
|
|
29
29
|
}
|
|
30
30
|
else if (change.kind === 'retype') {
|
|
31
31
|
const type = element.data.type;
|
|
32
32
|
patch = text => text.replace(new RegExp(`(\\n\\s+attribute :${old}, )[^,\\n]+( do|,)`), `$1${elixirType(type, context)}$2`);
|
|
33
|
-
statement =
|
|
33
|
+
statement = { type: column(type, context) };
|
|
34
34
|
}
|
|
35
35
|
else {
|
|
36
36
|
patch = text => text
|
|
37
37
|
.replace(new RegExp(`\\n\\s+attribute :${old}, [^\\n]* do\\n[\\s\\S]*?\\n\\s+end\\n`), '\n')
|
|
38
38
|
.replace(new RegExp(`\\n\\s+attribute :${old}, [^\\n]*\\n`), '\n')
|
|
39
39
|
.replace(new RegExp(`(, )?:${old}\\b(, )?`, 'g'), (_, before, after) => (before && after ? ', ' : ''));
|
|
40
|
-
statement =
|
|
40
|
+
statement = {};
|
|
41
41
|
}
|
|
42
42
|
const migration = `priv/repo/migrations/${change.stamp}_appling_${change.block}.exs`;
|
|
43
43
|
const module = `${pascal(app(context))}.Repo.Migrations.Appling${pascal(change.block)}`;
|
|
44
44
|
return [
|
|
45
45
|
{ kind: 'template', file: resource, write: existing => patch(existing) },
|
|
46
46
|
{
|
|
47
|
-
kind: 'template', file: migration, write: existing => (existing
|
|
48
|
-
|
|
47
|
+
kind: 'template', file: migration, write: existing => (existing ?? `${context.render('migrations/migration.exs.njk', { module })}\n`)
|
|
48
|
+
.replace(/\n end\nend\n$/, `\n${context.render('migrations/statement.exs.njk', { kind: change.kind, table, column: old, ...statement })}\n end\nend\n`)
|
|
49
49
|
},
|
|
50
50
|
{ kind: 'command', run: ['mix', 'ash_postgres.generate_migrations', '--snapshots-only'], phase: 1 },
|
|
51
51
|
task(`update the code that uses ${change.target} after the ${change.kind}${change.newName ? ` to ${change.newName}` : ''}; resources and migrations are done`)
|
package/out/naming.d.ts
CHANGED
|
@@ -10,6 +10,8 @@ export declare function typeModule(node: GraphNode, context: MapContext): string
|
|
|
10
10
|
export declare function fileOf(node: GraphNode, context: MapContext): string;
|
|
11
11
|
export declare function pascal(name: string): string;
|
|
12
12
|
export declare function snake(name: string): string;
|
|
13
|
+
/** The lines of a rendered template, for a DSL section; none when it renders nothing. */
|
|
14
|
+
export declare function sectionLines(context: MapContext, template: string, data: object): string[];
|
|
13
15
|
export declare function mix(args: string[]): CommandStep;
|
|
14
16
|
export declare function task(what: string): Step;
|
|
15
17
|
/** A registry task the model leaves to the code by design (`docs/concept.md` section 8): it does not lower the coverage. */
|
package/out/naming.js
CHANGED
|
@@ -34,6 +34,11 @@ export function pascal(name) {
|
|
|
34
34
|
export function snake(name) {
|
|
35
35
|
return name.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase();
|
|
36
36
|
}
|
|
37
|
+
/** The lines of a rendered template, for a DSL section; none when it renders nothing. */
|
|
38
|
+
export function sectionLines(context, template, data) {
|
|
39
|
+
const text = context.render(template, data);
|
|
40
|
+
return text ? text.split('\n') : [];
|
|
41
|
+
}
|
|
37
42
|
export function mix(args) {
|
|
38
43
|
return { kind: 'command', run: ['mix', ...args, '--yes'] };
|
|
39
44
|
}
|
package/out/pages.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ashExpr, lastOf } from './elixir.js';
|
|
1
|
+
import { ashExpr, lastOf, moduledoc } from './elixir.js';
|
|
2
2
|
import { app, calculation, children, pascal, patch, snake, task, typeModule, TYPES } from './naming.js';
|
|
3
3
|
/** Whether the model has pages, which makes the generated project a Phoenix application. */
|
|
4
4
|
export function hasPages(context) {
|
|
@@ -17,8 +17,7 @@ export function pageSteps(page, context) {
|
|
|
17
17
|
const name = `${lastOf(page.qn)}Live`;
|
|
18
18
|
const route = String(page.data.route).replace(/\{(\w+)\}/g, ':$1');
|
|
19
19
|
const byId = route.includes(':id');
|
|
20
|
-
const
|
|
21
|
-
const markup = [];
|
|
20
|
+
const components = [];
|
|
22
21
|
const events = new Map();
|
|
23
22
|
let params = false;
|
|
24
23
|
page.data.components.forEach((component, i) => {
|
|
@@ -28,10 +27,11 @@ export function pageSteps(page, context) {
|
|
|
28
27
|
if (!ok)
|
|
29
28
|
tasks.push(task(`offer ${lastOf(action.qn)} on ${lastOf(page.qn)}; it needs inputs, so it needs a form`));
|
|
30
29
|
return ok;
|
|
30
|
+
}).map(action => {
|
|
31
|
+
const event = `run_${snake(lastOf(action.qn))}`;
|
|
32
|
+
events.set(event, { kind: 'run', event, resource: typeModule(context.node(action.data.entity), context), action: snake(lastOf(action.qn)), label: lastOf(action.qn) });
|
|
33
|
+
return { event, label: lastOf(action.qn) };
|
|
31
34
|
});
|
|
32
|
-
for (const action of actions)
|
|
33
|
-
events.set(`run_${snake(lastOf(action.qn))}`, runEvent(action, context));
|
|
34
|
-
const buttons = (record) => actions.map(a => `<.button phx-click="run_${snake(lastOf(a.qn))}" phx-value-id={${record}.id}>${lastOf(a.qn)}</.button>`).join(' ');
|
|
35
35
|
if (component.$type === 'ListView') {
|
|
36
36
|
const query = context.node(component.query);
|
|
37
37
|
const entity = context.node(query.data.entity);
|
|
@@ -45,8 +45,7 @@ export function pageSteps(page, context) {
|
|
|
45
45
|
const read = inputs.length
|
|
46
46
|
? `Ash.read!(Ash.Query.for_read(${typeModule(entity, context)}, :${snake(lastOf(query.qn))}, Map.take(socket.assigns.params, [${inputs.join(', ')}]))${options})`
|
|
47
47
|
: `Ash.read!(${typeModule(entity, context)}, action: :${snake(lastOf(query.qn))}${options})`;
|
|
48
|
-
|
|
49
|
-
markup.push(`<.table id="${id.replace('_', '-')}" rows={@${id}}>`, ...columns.map(c => ` <:col :let={row} label=${JSON.stringify(c.label)}>{to_string(row.${c.field})}</:col>`), ...(actions.length ? [` <:action :let={row}>${buttons('row')}</:action>`] : []), '</.table>');
|
|
48
|
+
components.push({ type: 'list', id, domId: id.replace('_', '-'), load: query.data.pageSize ? `${read}.results` : read, columns, actions });
|
|
50
49
|
}
|
|
51
50
|
else if (component.$type === 'DetailView') {
|
|
52
51
|
if (!byId) {
|
|
@@ -56,8 +55,7 @@ export function pageSteps(page, context) {
|
|
|
56
55
|
const entity = sourceEntity(component.projection, context);
|
|
57
56
|
const columns = columnsOf(component.projection, component.picks, context, tasks);
|
|
58
57
|
const load = columns.filter(c => c.load).map(c => `:${c.field}`);
|
|
59
|
-
|
|
60
|
-
markup.push('<.list>', ...columns.map(c => ` <:item title=${JSON.stringify(c.label)}>{to_string(@${id}.${c.field})}</:item>`), '</.list>', ...(actions.length ? [buttons(`@${id}`)] : []));
|
|
58
|
+
components.push({ type: 'detail', id, load: `Ash.get!(${typeModule(entity, context)}, socket.assigns.id${load.length ? `, load: [${load.join(', ')}]` : ''})`, columns, actions });
|
|
61
59
|
}
|
|
62
60
|
else if (component.$type === 'FormView') {
|
|
63
61
|
const action = context.node(component.submits);
|
|
@@ -67,70 +65,28 @@ export function pageSteps(page, context) {
|
|
|
67
65
|
return;
|
|
68
66
|
}
|
|
69
67
|
const event = `submit_${snake(lastOf(action.qn))}`;
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
`
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
' end',
|
|
77
|
-
'end'
|
|
78
|
-
].join('\n'));
|
|
79
|
-
markup.push(`<.form for={@${id}} phx-submit="${event}">`, ...children(action, context, 'Param').map(p => ` <.input field={@${id}[:${lastOf(p.qn)}]} label=${JSON.stringify(title(lastOf(p.qn)))} />`), ` <.button>${lastOf(action.qn)}</.button>`, '</.form>');
|
|
68
|
+
events.set(event, { kind: 'submit', event, id, label: lastOf(action.qn) });
|
|
69
|
+
components.push({
|
|
70
|
+
type: 'form', id, event, label: lastOf(action.qn),
|
|
71
|
+
load: `AshPhoenix.Form.for_update(Ash.get!(${typeModule(entity, context)}, socket.assigns.id), :${snake(lastOf(action.qn))}) |> to_form()`,
|
|
72
|
+
inputs: children(action, context, 'Param').map(p => ({ name: lastOf(p.qn), label: title(lastOf(p.qn)) }))
|
|
73
|
+
});
|
|
80
74
|
}
|
|
81
75
|
});
|
|
82
|
-
const
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
` use ${web(context)}, :live_view`,
|
|
86
|
-
'',
|
|
87
|
-
' @impl true',
|
|
88
|
-
` def mount(${params ? 'params' : byId ? '%{"id" => id}' : '_params'}, _session, socket) do`,
|
|
89
|
-
` {:ok, socket |> assign(:page_title, ${JSON.stringify(title(lastOf(page.qn)))})${params ? ' |> assign(:params, params)' : ''}${byId ? ` |> assign(:id, ${params ? 'params["id"]' : 'id'})` : ''} |> load()}`,
|
|
90
|
-
' end',
|
|
91
|
-
'',
|
|
92
|
-
' defp load(socket) do',
|
|
93
|
-
' socket',
|
|
94
|
-
...assigns.map(a => ` ${a}`),
|
|
95
|
-
' end',
|
|
96
|
-
...[...events.values()].flatMap(handler => ['', ' @impl true', ...handler.split('\n').map(l => ` ${l}`)]),
|
|
97
|
-
'',
|
|
98
|
-
' @impl true',
|
|
99
|
-
' def render(assigns) do',
|
|
100
|
-
' ~H"""',
|
|
101
|
-
' <Layouts.app flash={@flash}>',
|
|
102
|
-
...(nav ? [` ${nav}`] : []),
|
|
103
|
-
` <.header>${title(lastOf(page.qn))}</.header>`,
|
|
104
|
-
...markup.map(l => ` ${l}`),
|
|
105
|
-
' </Layouts.app>',
|
|
106
|
-
' """',
|
|
107
|
-
' end',
|
|
108
|
-
'end',
|
|
109
|
-
''
|
|
110
|
-
].join('\n');
|
|
76
|
+
const code = context.render('pages/live.ex.njk', {
|
|
77
|
+
web: web(context), name, moduledoc: moduledoc(page), title: title(lastOf(page.qn)), params, byId, components, events: [...events.values()], nav: navigationLinks(page.module, context)
|
|
78
|
+
});
|
|
111
79
|
return [
|
|
112
|
-
{ kind: 'template', file: `lib/${app(context)}_web/live/${snake(lastOf(page.qn))}_live.ex`, write: () => code
|
|
80
|
+
{ kind: 'template', file: `lib/${app(context)}_web/live/${snake(lastOf(page.qn))}_live.ex`, write: () => `${code}\n`, phase: 2 },
|
|
113
81
|
patch(`lib/${app(context)}_web/router.ex`, existing => existing.includes(`live "${route}", ${name}`) ? existing
|
|
114
82
|
: existing.replace(/(\n(\s*)get "\/", PageController, :home\n)/, `$1$2live "${route}", ${name}\n`)),
|
|
115
83
|
...tasks
|
|
116
84
|
];
|
|
117
85
|
}
|
|
118
|
-
function runEvent(action, context) {
|
|
119
|
-
const entity = context.node(action.data.entity);
|
|
120
|
-
return [
|
|
121
|
-
`def handle_event("run_${snake(lastOf(action.qn))}", %{"id" => id}, socket) do`,
|
|
122
|
-
` case Ash.update(Ash.get!(${typeModule(entity, context)}, id), %{}, action: :${snake(lastOf(action.qn))}) do`,
|
|
123
|
-
` {:ok, _} -> {:noreply, socket |> put_flash(:info, ${JSON.stringify(`${lastOf(action.qn)} done.`)}) |> load()}`,
|
|
124
|
-
` {:error, error} -> {:noreply, put_flash(socket, :error, ${JSON.stringify(`${lastOf(action.qn)} failed: `)} <> Exception.message(error))}`,
|
|
125
|
-
' end',
|
|
126
|
-
'end'
|
|
127
|
-
].join('\n');
|
|
128
|
-
}
|
|
129
86
|
/** The navigation of the module as links; items to pages that need an id are left out. */
|
|
130
87
|
function navigationLinks(module, context) {
|
|
131
88
|
const items = context.graph.nodes.filter(n => n.kind === 'Navigation' && n.module === module).flatMap(n => (n.data.items ?? []));
|
|
132
|
-
|
|
133
|
-
return links.length ? `<nav class="flex gap-4 mb-6">${links.join(' ')}</nav>` : undefined;
|
|
89
|
+
return items.filter(i => !String(context.node(i.page)?.data.route ?? '').includes('{')).map(i => ({ route: String(context.node(i.page).data.route), label: i.label }));
|
|
134
90
|
}
|
|
135
91
|
export function navigationSteps(navigation, context) {
|
|
136
92
|
return (navigation.data.items ?? [])
|