@appling/codegen-ash 0.0.0-stage → 0.1.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alexandros Fotiadis
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,50 @@
1
- # Temporary Holding Version
1
+ # @appling/codegen-ash
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Appling code generation extension for [Ash](https://ash-hq.org) on Elixir. It turns an Appling model into a draft Ash project with AshPostgres, using Ash's own generators through [Igniter](https://hexdocs.pm/igniter).
4
+
5
+ ```json
6
+ {
7
+ "generate": [
8
+ { "extension": "@appling/codegen-ash", "out": "build/shop" }
9
+ ]
10
+ }
11
+ ```
12
+
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
+
15
+ Requires Elixir 1.17 or later and the `igniter_new` archive (`mix archive.install hex igniter_new`).
16
+
17
+ ## What it generates
18
+
19
+ | Model | Ash |
20
+ |---|---|
21
+ | project | `mix igniter.new <name> --install ash,ash_postgres` |
22
+ | `module` | `mix ash.gen.domain <App>.<Module>` |
23
+ | `enum` | `mix ash.gen.enum` |
24
+ | `value` | an embedded resource |
25
+ | `entity` | `mix ash.gen.resource` with a UUID primary key, default actions, timestamps and the Postgres data layer |
26
+ | field types | `:string`, `:integer`, `:decimal`, `:boolean`, `:date`, `:utc_datetime_usec`, `:duration`, `:uuid`; enums and value types by module; lists as arrays |
27
+ | entity field | a `belongs_to` relationship, added after all resources exist |
28
+ | `unique`, `?`, `default` | an identity, `allow_nil?`, `default` |
29
+ | derived field | a calculation with an Ash expression |
30
+ | `invariant` | a validation built from `compare`, `attribute_equals`, `attribute_in`, `present`, `all`, `any` and `negate` |
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
+ | `machine` | an AshStateMachine section; transitions on an event get an update action named after the event |
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 |
35
+ | computed projection field | a calculation on the source resource |
36
+ | `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 |
37
+ | `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 |
38
+ | rules | skipped ExUnit tests in `test/<app>/<module>/<resource>_test.exs` for invariants, policies, transitions and preconditions; writing their bodies is a registry task |
39
+
40
+ The project ends with `mix ash.codegen initial_resources`, so migrations and resource snapshots start with the generated resources.
41
+
42
+ `appling generate --migrate` changes the attribute in the resource, writes an Ecto migration that renames, modifies or removes the column, and updates the resource snapshots with `mix ash_postgres.generate_migrations --snapshots-only`, so later `mix ash.codegen` runs do not see a rename as a drop and an add. Renamed entities and enum values become registry tasks.
43
+
44
+ Machines, scheduled jobs and REST interfaces add `ash_state_machine`, `ash_oban`, and `ash_json_api` with `bandit` to the project.
45
+
46
+ 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, 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.
47
+
48
+ ## License
49
+
50
+ MIT
package/out/api.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import type { MapContext, Step } from '@appling/codegen';
2
+ import type { GraphNode } from '@appling/model';
3
+ /**
4
+ * A REST interface becomes AshJsonApi routes on the domain, served by a JSON:API router that Bandit
5
+ * starts with the application, without Phoenix.
6
+ */
7
+ export declare function interfaceSteps(api: GraphNode, context: MapContext): Step[] | undefined;
package/out/api.js ADDED
@@ -0,0 +1,74 @@
1
+ import { lastOf } from './elixir.js';
2
+ import { app, children, fileOf, moduleName, pascal, patch, snake, task, typeModule } from './naming.js';
3
+ import { hasPages } from './pages.js';
4
+ import { addExtension, addToSection } from './resource.js';
5
+ /**
6
+ * A REST interface becomes AshJsonApi routes on the domain, served by a JSON:API router that Bandit
7
+ * starts with the application, without Phoenix.
8
+ */
9
+ export function interfaceSteps(api, context) {
10
+ if (api.data.protocol !== 'rest')
11
+ return undefined;
12
+ const tasks = [];
13
+ const routes = new Map();
14
+ for (const endpoint of children(api, context, 'Endpoint')) {
15
+ const route = endpointRoute(endpoint, context);
16
+ if (!route) {
17
+ tasks.push(task(`expose ${endpoint.data.verb} ${endpoint.data.path} -> ${lastOf(endpoint.data.target)}`));
18
+ continue;
19
+ }
20
+ routes.set(route.resource, [...(routes.get(route.resource) ?? []), route.line]);
21
+ if (route.note)
22
+ tasks.push(task(route.note));
23
+ }
24
+ if (api.data.auth)
25
+ tasks.push(task(`authenticate ${lastOf(api.qn)} with ${api.data.auth}, for example with AshAuthentication`));
26
+ if (api.data.rateLimit)
27
+ tasks.push(task(`limit ${lastOf(api.qn)} to ${api.data.rateLimit} requests per ${api.data.rateUnit}`));
28
+ if (api.data.origins?.length)
29
+ tasks.push(task(`allow the CORS origins ${api.data.origins.join(', ')} for ${lastOf(api.qn)}`));
30
+ if (!routes.size)
31
+ return tasks;
32
+ const domain = moduleName(api.module, context);
33
+ const router = `${pascal(app(context))}.ApiRouter`;
34
+ const serve = hasPages(context)
35
+ ? [patch(`lib/${app(context)}_web/ash_json_api_router.ex`, existing => existing.replace(/domains: \[([^\]]*)\]/, (all, list) => list.includes(domain) ? all : `domains: [${[list.trim(), domain].filter(Boolean).join(', ')}]`))]
36
+ : [
37
+ {
38
+ kind: 'template', phase: 2, file: `lib/${app(context)}/api_router.ex`, write: existing => existing
39
+ ? existing.replace(/domains: \[([^\]]*)\]/, (all, list) => list.includes(domain) ? all : `domains: [${list}, ${domain}]`)
40
+ : `defmodule ${router} do\n use AshJsonApi.Router, domains: [${domain}], open_api: "/open_api"\nend\n`
41
+ },
42
+ patch(`lib/${app(context)}/application.ex`, existing => existing.includes('Bandit')
43
+ ? existing
44
+ : existing.replace(/children = \[\n/, `children = [\n {Bandit, plug: ${router}, port: 4000},\n`))
45
+ ];
46
+ const resourceSteps = [...routes].flatMap(([resource, lines]) => [
47
+ 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)))}`])),
48
+ patch(domainFile(api, context), existing => addToSection(addExtension(existing, 'AshJsonApi.Domain'), 'json_api', [`base_route "/", ${typeModule(resource, context)} do`, ...lines.map(l => ` ${l}`), 'end'], 'routes'))
49
+ ]);
50
+ return [
51
+ ...resourceSteps,
52
+ ...serve,
53
+ ...tasks
54
+ ];
55
+ }
56
+ /** The route line for one endpoint, relative to "/" of its resource. */
57
+ function endpointRoute(endpoint, context) {
58
+ const target = context.node(endpoint.data.target);
59
+ const verb = endpoint.data.verb;
60
+ const path = endpoint.data.path.replace(/\{id\}/g, ':id').replace(/\{(\w+)\}/g, ':$1');
61
+ if (verb === 'GET' && target.kind === 'Query') {
62
+ const fields = (endpoint.data.picks ?? []).map(p => `:${lastOf(p)}`);
63
+ const options = [`route: ${JSON.stringify(path)}`, ...(fields.length ? [`default_fields: [${fields.join(', ')}]`] : [])];
64
+ return { resource: context.node(target.data.entity), line: `index :${snake(lastOf(target.qn))}, ${options.join(', ')}` };
65
+ }
66
+ if (['POST', 'PUT', 'PATCH'].includes(verb) && target.kind === 'Action' && target.data.entity && path.includes(':id')) {
67
+ const note = verb === 'PATCH' ? undefined : `${verb} ${endpoint.data.path} is served as PATCH, the JSON:API method for update actions`;
68
+ return { resource: context.node(target.data.entity), line: `patch :${snake(lastOf(target.qn))}, route: ${JSON.stringify(path)}`, note };
69
+ }
70
+ return undefined;
71
+ }
72
+ function domainFile(api, context) {
73
+ return ['lib', app(context), ...api.module.split('.').slice(0, -1).map(snake), `${snake(lastOf(api.module))}.ex`].join('/');
74
+ }
@@ -0,0 +1,6 @@
1
+ import type { MapContext, Step } from '@appling/codegen';
2
+ import type { GraphNode } from '@appling/model';
3
+ /** A query becomes a read action of its entity's resource with filter, sort and pagination. */
4
+ export declare function querySteps(query: GraphNode, context: MapContext): Step[];
5
+ /** Computed projection fields become calculations on the source resource; plain fields are its attributes already. */
6
+ export declare function projectionFieldSteps(field: GraphNode, context: MapContext): Step[];
@@ -0,0 +1,33 @@
1
+ import { ashExpr, lastOf } from './elixir.js';
2
+ import { fileOf, patch, snake, task, TYPES } from './naming.js';
3
+ import { addToSection } from './resource.js';
4
+ /** A query becomes a read action of its entity's resource with filter, sort and pagination. */
5
+ export function querySteps(query, context) {
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}`)];
10
+ const sorts = (query.data.sorts ?? []).map(s => `${lastOf(s.field)}: :${s.direction ?? 'asc'}`);
11
+ const lines = [
12
+ `read :${snake(lastOf(query.qn))} do`,
13
+ ...(filter ? [` filter expr(${filter})`] : []),
14
+ ...(sorts.length ? [` prepare build(sort: [${sorts.join(', ')}])`] : []),
15
+ ...(query.data.pageSize ? [` pagination offset?: true, default_limit: ${query.data.pageSize}, required?: false`] : []),
16
+ 'end'
17
+ ];
18
+ return [patch(fileOf(entity, context), existing => addToSection(existing, 'actions', lines))];
19
+ }
20
+ /** Computed projection fields become calculations on the source resource; plain fields are its attributes already. */
21
+ export function projectionFieldSteps(field, context) {
22
+ const value = field.data.value;
23
+ if (!value)
24
+ return [];
25
+ const projection = context.node(field.qn.slice(0, field.qn.lastIndexOf('.')));
26
+ const source = context.node(projection.data.source);
27
+ const entity = source.kind === 'Query' ? context.node(source.data.entity) : source;
28
+ const body = ashExpr(value, context.node);
29
+ const type = TYPES[value.type.replace(/\?$/, '')];
30
+ if (!body || !type)
31
+ return [task(`add the calculation ${lastOf(field.qn)} = ${field.props.value} to ${lastOf(entity.qn)}`)];
32
+ return [patch(fileOf(entity, context), existing => addToSection(existing, 'calculations', [`calculate :${lastOf(field.qn)}, :${type}, expr(${body})`]))];
33
+ }
@@ -0,0 +1,11 @@
1
+ import type { MapContext, Step } from '@appling/codegen';
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. */
4
+ export declare function actionSteps(action: GraphNode, context: MapContext): Step[];
5
+ /**
6
+ * A machine becomes an AshStateMachine section on the resource of its state field. Transitions on an event
7
+ * get an update action named after the event, which the event's publisher has to call.
8
+ */
9
+ export declare function machineSteps(machine: GraphNode, context: MapContext): Step[];
10
+ /** A scheduled job becomes an AshOban trigger that runs the action for every matching row. */
11
+ export declare function jobSteps(job: GraphNode, context: MapContext): Step[];
@@ -0,0 +1,125 @@
1
+ import { ashExpr, constant, lastOf, parentOf, validation } from './elixir.js';
2
+ import { addExtension, addToSection } from './resource.js';
3
+ import { testSteps } from './tests.js';
4
+ 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. */
6
+ export function actionSteps(action, context) {
7
+ const entity = action.data.entity ? context.node(action.data.entity) : undefined;
8
+ if (!entity)
9
+ return [task(`implement ${lastOf(action.qn)} as a generic action`)];
10
+ const tasks = [];
11
+ const lines = [`update :${snake(lastOf(action.qn))} do`, ' require_atomic? false'];
12
+ for (const input of children(action, context, 'Param')) {
13
+ const type = input.data.type;
14
+ lines.push(` argument :${lastOf(input.qn)}, ${type.many ? `{:array, ${attributeType(type, context, true)}}` : attributeType(type, context, true)}, allow_nil?: ${type.optional ? 'true' : 'false'}`);
15
+ }
16
+ const stored = storedAttributes(entity, context);
17
+ const preconditions = (action.data.preconditions ?? []);
18
+ preconditions.forEach((precondition, i) => {
19
+ const rule = validation(precondition.condition, stored, context.node);
20
+ const message = precondition.error ? lastOf(precondition.error) : action.props.preconditions[i];
21
+ if (rule)
22
+ lines.push(` validate ${rule}, message: ${JSON.stringify(message)}`);
23
+ else
24
+ tasks.push(task(`check the precondition ${action.props.preconditions[i]} in ${lastOf(action.qn)}`));
25
+ });
26
+ const transitions = context.graph.nodes.filter(n => n.kind === 'Transition' && n.data.action === action.qn);
27
+ for (const transition of transitions.filter(t => t.data.guard)) {
28
+ const rule = validation(transition.data.guard, stored, context.node);
29
+ if (rule && transitions.length === 1)
30
+ lines.push(` validate ${rule}, message: "invalid transition"`);
31
+ else
32
+ tasks.push(task(`check the guard ${transition.props.guard} of ${lastOf(transition.qn)}`));
33
+ }
34
+ const effects = [...children(action, context), ...transitions.flatMap(t => children(t, context))].filter(c => c.kind.endsWith('Effect'));
35
+ for (const effect of effects) {
36
+ const change = effectChange(effect, context);
37
+ if (change)
38
+ lines.push(` change ${change}`);
39
+ else
40
+ tasks.push(task(`apply the effect ${lastOf(effect.qn)} in ${lastOf(action.qn)}, for example with an Ash notifier or a change`));
41
+ }
42
+ const targets = [...new Set(transitions.map(t => t.data.to))];
43
+ if (targets.length === 1)
44
+ lines.push(` change transition_state(:${targets[0]})`);
45
+ else if (targets.length > 1)
46
+ tasks.push(task(`pick the target state of ${lastOf(action.qn)} among ${targets.join(', ')}`));
47
+ lines.push('end');
48
+ if (action.data.consistency === 'eventual')
49
+ 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) : [];
51
+ return [patch(fileOf(entity, context), existing => addToSection(existing, 'actions', lines)), ...tasks, ...tests];
52
+ }
53
+ function effectChange(effect, context) {
54
+ if (effect.kind !== 'SetEffect')
55
+ return undefined;
56
+ const field = lastOf(effect.data.field);
57
+ const value = effect.data.value;
58
+ if (value.$type === 'NameExpr' && value.name === 'now' && !value.target)
59
+ return `set_attribute(:${field}, &DateTime.utc_now/0)`;
60
+ const literal = constant(value, context.node);
61
+ if (literal !== undefined)
62
+ return `set_attribute(:${field}, ${literal})`;
63
+ const expression = ashExpr(value, context.node);
64
+ return expression && `atomic_update(:${field}, expr(${expression}))`;
65
+ }
66
+ /**
67
+ * A machine becomes an AshStateMachine section on the resource of its state field. Transitions on an event
68
+ * get an update action named after the event, which the event's publisher has to call.
69
+ */
70
+ export function machineSteps(machine, context) {
71
+ const field = context.node(machine.data.field);
72
+ const entity = context.node(parentOf(field.qn));
73
+ const literals = context.children(field.data.type.decl).map(l => lastOf(l.qn));
74
+ const initial = field.data.default?.name ?? literals[0];
75
+ const transitions = children(machine, context, 'Transition');
76
+ const byEvent = Map.groupBy(transitions.filter(t => t.data.event), t => t.data.event);
77
+ const settings = [`initial_states [:${initial}]`, `default_initial_state :${initial}`, `state_attribute :${lastOf(field.qn)}`];
78
+ const lines = transitions.map(t => {
79
+ const action = snake(lastOf((t.data.action ?? t.data.event)));
80
+ return `transition :${action}, from: [${t.data.from.map(s => `:${s}`).join(', ')}], to: :${t.data.to}`;
81
+ });
82
+ const eventActions = [...byEvent].flatMap(([event, list]) => {
83
+ const targets = [...new Set(list.map(t => t.data.to))];
84
+ return targets.length === 1 ? [[`update :${snake(lastOf(event))} do`, ' require_atomic? false', ` change transition_state(:${targets[0]})`, 'end']] : [];
85
+ });
86
+ return [
87
+ patch(fileOf(entity, context), existing => {
88
+ let text = addToSection(addToSection(addExtension(existing, 'AshStateMachine'), 'state_machine', settings), 'state_machine', lines, 'transitions');
89
+ for (const action of eventActions)
90
+ text = addToSection(text, 'actions', action);
91
+ return text;
92
+ }),
93
+ ...[...byEvent.keys()].map(event => task(`call ${typeModule(entity, context)} :${snake(lastOf(event))} when ${lastOf(event)} happens`))
94
+ ];
95
+ }
96
+ /** A scheduled job becomes an AshOban trigger that runs the action for every matching row. */
97
+ export function jobSteps(job, context) {
98
+ const action = context.node(job.data.action);
99
+ const entity = action.data.entity ? context.node(action.data.entity) : undefined;
100
+ if (!entity || !job.data.schedule)
101
+ return [task(`run ${lastOf(action.qn)} ${job.data.schedule ? `on the schedule ${job.data.schedule}` : `when ${lastOf(job.data.event)} happens`}`)];
102
+ const where = job.data.filter ? ashExpr(job.data.filter, context.node) : 'true';
103
+ if (!where)
104
+ return [task(`run ${lastOf(action.qn)} on the schedule ${job.data.schedule} where ${job.props.filter}`)];
105
+ const name = snake(lastOf(job.qn));
106
+ const module = typeModule(entity, context);
107
+ const pascal = lastOf(job.qn);
108
+ const queue = `${snake(lastOf(entity.qn))}_${name}`;
109
+ const lines = [
110
+ `trigger :${name} do`,
111
+ ` action :${snake(lastOf(action.qn))}`,
112
+ ` read_action :${name}_targets`,
113
+ ` queue :${queue}`,
114
+ ` where expr(${where})`,
115
+ ` scheduler_cron ${JSON.stringify(job.data.schedule)}`,
116
+ ` worker_module_name ${module}.AshOban.Worker.${pascal}`,
117
+ ` scheduler_module_name ${module}.AshOban.Scheduler.${pascal}`,
118
+ 'end'
119
+ ];
120
+ const read = [`read :${name}_targets do`, ' pagination keyset?: true, required?: false', 'end'];
121
+ return [
122
+ patch(fileOf(entity, context), existing => addToSection(addToSection(addExtension(existing, 'AshOban'), 'actions', read), 'oban', lines, 'triggers')),
123
+ patch('config/config.exs', existing => existing.replace(/queues: \[([^\]]*)\]/, (all, list) => list.includes(`${queue}:`) ? all : `queues: [${list}, ${queue}: 10]`))
124
+ ];
125
+ }
@@ -0,0 +1,11 @@
1
+ import type { ExprData, GraphNode } from '@appling/model';
2
+ type Lookup = (qn: string) => GraphNode | undefined;
3
+ /** Translates an expression to the body of an Ash `expr(...)`, or returns undefined when Ash expressions cannot say it. */
4
+ export declare function ashExpr(expr: ExprData, node: Lookup): string | undefined;
5
+ /** Translates a condition over stored attributes to an Ash builtin validation, or undefined. */
6
+ export declare function validation(expr: ExprData, stored: Set<string>, node: Lookup): string | undefined;
7
+ /** A literal or enum value as an Elixir constant. */
8
+ export declare function constant(expr: ExprData, node: Lookup): string | undefined;
9
+ export declare function parentOf(qn: string): string;
10
+ export declare function lastOf(qn: string): string;
11
+ export {};
package/out/elixir.js ADDED
@@ -0,0 +1,114 @@
1
+ const OPERATORS = { '&&': 'and', '||': 'or' };
2
+ const COMPARE = { '<': 'less_than', '<=': 'less_than_or_equal_to', '>': 'greater_than', '>=': 'greater_than_or_equal_to' };
3
+ const FLIPPED = { '<': '>', '<=': '>=', '>': '<', '>=': '<=', '==': '==', '!=': '!=' };
4
+ /** Translates an expression to the body of an Ash `expr(...)`, or returns undefined when Ash expressions cannot say it. */
5
+ export function ashExpr(expr, node) {
6
+ const sub = (e) => ashExpr(e, node);
7
+ switch (expr.$type) {
8
+ case 'StringExpr':
9
+ case 'NumberExpr':
10
+ case 'BoolExpr':
11
+ case 'NullExpr': return constant(expr, node);
12
+ case 'ListExpr': return joined((expr.items ?? []).map(sub), items => `[${items.join(', ')}]`);
13
+ case 'UnaryExpr': {
14
+ const operand = sub(expr.operand);
15
+ return operand && (expr.op === '!' ? `not ${wrap(operand)}` : `-${wrap(operand)}`);
16
+ }
17
+ case 'BinaryExpr': {
18
+ const shift = relativeTime(expr);
19
+ if (shift)
20
+ return shift;
21
+ const [left, right] = [sub(expr.left), sub(expr.right)];
22
+ return left && right && `${wrap(left)} ${OPERATORS[expr.op] ?? expr.op} ${wrap(right)}`;
23
+ }
24
+ case 'NameExpr': {
25
+ if (expr.call) {
26
+ const arg = expr.name === 'has' && expr.args?.[0] && sub(expr.args[0]);
27
+ return arg ? `not is_nil(${arg})` : undefined;
28
+ }
29
+ if (expr.name === 'now' && !expr.target)
30
+ return 'now()';
31
+ const target = expr.target ? node(expr.target) : undefined;
32
+ if (target?.kind === 'EnumLiteral')
33
+ return `:${expr.name}`;
34
+ if (target?.kind === 'Param')
35
+ return `^arg(:${expr.name})`;
36
+ return target?.kind === 'Field' && node(parentOf(target.qn))?.kind === 'Entity' ? expr.name : undefined;
37
+ }
38
+ case 'MemberExpr': {
39
+ const receiver = !expr.call && sub(expr.receiver);
40
+ const target = expr.target ? node(expr.target) : undefined;
41
+ return receiver && target?.kind === 'Field' && node(parentOf(target.qn))?.kind === 'Entity' ? `${receiver}.${expr.member}` : undefined;
42
+ }
43
+ default: return undefined;
44
+ }
45
+ }
46
+ /** Translates a condition over stored attributes to an Ash builtin validation, or undefined. */
47
+ export function validation(expr, stored, node) {
48
+ const field = (e) => e?.$type === 'NameExpr' && !e.call && e.target && stored.has(e.target) ? e.name : undefined;
49
+ const sub = (e) => validation(e, stored, node);
50
+ if (expr.$type === 'BinaryExpr' && (expr.op === '&&' || expr.op === '||')) {
51
+ const [left, right] = [sub(expr.left), sub(expr.right)];
52
+ return left && right && `${expr.op === '&&' ? 'all' : 'any'}([${left}, ${right}])`;
53
+ }
54
+ if (expr.$type === 'UnaryExpr' && expr.op === '!') {
55
+ const operand = sub(expr.operand);
56
+ return operand && `negate(${operand})`;
57
+ }
58
+ if (expr.$type === 'NameExpr' && expr.call && expr.name === 'has' && field(expr.args?.[0]))
59
+ return `present(:${field(expr.args[0])})`;
60
+ if (expr.$type !== 'BinaryExpr')
61
+ return undefined;
62
+ if (expr.op === 'in') {
63
+ const values = expr.right?.$type === 'ListExpr' ? joined(expr.right.items.map(i => constant(i, node)), v => v.join(', ')) : undefined;
64
+ return field(expr.left) && values !== undefined ? `attribute_in(:${field(expr.left)}, [${values}])` : undefined;
65
+ }
66
+ const [name, other, op] = field(expr.left) ? [field(expr.left), expr.right, expr.op] : field(expr.right) ? [field(expr.right), expr.left, FLIPPED[expr.op]] : [];
67
+ if (!name || !other || !op)
68
+ return undefined;
69
+ const otherField = field(other);
70
+ const value = otherField ? `:${otherField}` : constant(other, node);
71
+ if (value === undefined)
72
+ return undefined;
73
+ if (op in COMPARE)
74
+ return `compare(:${name}, ${COMPARE[op]}: ${value})`;
75
+ if (otherField)
76
+ return undefined;
77
+ if (value === 'nil')
78
+ return op === '==' ? `absent(:${name})` : `present(:${name})`;
79
+ return op === '==' ? `attribute_equals(:${name}, ${value})` : op === '!=' ? `attribute_does_not_equal(:${name}, ${value})` : undefined;
80
+ }
81
+ /** A literal or enum value as an Elixir constant. */
82
+ export function constant(expr, node) {
83
+ switch (expr.$type) {
84
+ case 'StringExpr': return JSON.stringify(expr.value);
85
+ case 'NumberExpr': return String(expr.value);
86
+ case 'BoolExpr': return String(expr.value);
87
+ case 'NullExpr': return 'nil';
88
+ case 'NameExpr': return !expr.call && expr.target && node(expr.target)?.kind === 'EnumLiteral' ? `:${expr.name}` : undefined;
89
+ default: return undefined;
90
+ }
91
+ }
92
+ const UNITS = { d: 'day', h: 'hour', m: 'minute', s: 'second' };
93
+ /** `now - duration("720h")` and `now + duration(...)` as Ash's `ago(720, :hour)` and `from_now(...)`. */
94
+ function relativeTime(expr) {
95
+ const [left, right] = [expr.left, expr.right];
96
+ const isNow = left.$type === 'NameExpr' && left.name === 'now' && !left.target && !left.call;
97
+ const arg = right.$type === 'NameExpr' && right.call && right.name === 'duration' ? right.args?.[0] : undefined;
98
+ const match = arg?.$type === 'StringExpr' ? /^(\d+)(d|h|m|s)$/.exec(String(arg.value)) : null;
99
+ if (!isNow || !match || (expr.op !== '-' && expr.op !== '+'))
100
+ return undefined;
101
+ return `${expr.op === '-' ? 'ago' : 'from_now'}(${match[1]}, :${UNITS[match[2]]})`;
102
+ }
103
+ function wrap(code) {
104
+ return /^[\w.:]+(\(.*\))?$/.test(code) || /^".*"$/.test(code) || /^\[.*\]$/.test(code) ? code : `(${code})`;
105
+ }
106
+ function joined(parts, combine) {
107
+ return parts.every(p => p !== undefined) ? combine(parts) : undefined;
108
+ }
109
+ export function parentOf(qn) {
110
+ return qn.slice(0, qn.lastIndexOf('.'));
111
+ }
112
+ export function lastOf(qn) {
113
+ return qn.slice(qn.lastIndexOf('.') + 1);
114
+ }
package/out/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ import type { CodegenExtension } from '@appling/codegen';
2
+ declare const extension: CodegenExtension;
3
+ export default extension;
package/out/index.js ADDED
@@ -0,0 +1,164 @@
1
+ import { interfaceSteps } from './api.js';
2
+ import { projectionFieldSteps, querySteps } from './application.js';
3
+ import { actionSteps, jobSteps, machineSteps } from './behavior.js';
4
+ import { constant, lastOf, parentOf, validation } from './elixir.js';
5
+ import { migrationSteps } from './migrations.js';
6
+ import { hasPages, navigationSteps, pageSteps } from './pages.js';
7
+ import { testSteps } from './tests.js';
8
+ import { app, attributeType, calculation, fieldsOf, fileOf, mix, moduleName, patch, relationTarget, storedAttributes, task, typeModule } from './naming.js';
9
+ const extension = {
10
+ name: '@appling/codegen-ash',
11
+ test: ['mix', 'test'],
12
+ syncExclude: ['deps/**', '_build/**', 'priv/repo/migrations/**', 'priv/resource_snapshots/**', 'priv/static/**', 'mix.lock'],
13
+ migrate: migrationSteps,
14
+ prerequisites: [
15
+ { name: 'Elixir', command: ['mix', '--version'], expect: /Mix 1\.(1[7-9]|[2-9]\d)/, hint: 'install Elixir 1.17 or later' },
16
+ { name: 'igniter_new', command: ['mix', 'help', 'igniter.new'], hint: 'run "mix archive.install hex igniter_new"' },
17
+ { name: 'phx_new', command: ['mix', 'help', 'phx.new'], hint: 'run "mix archive.install hex phx_new"; models with pages become Phoenix applications', needed: graph => graph.nodes.some(n => n.kind === 'Page') }
18
+ ],
19
+ setup: context => {
20
+ const has = (kind, test = () => true) => context.graph.nodes.some(n => n.kind === kind && test(n));
21
+ const pages = hasPages(context);
22
+ const api = has('Interface', i => i.data.protocol === 'rest');
23
+ const install = [
24
+ 'ash', 'ash_postgres', ...(pages ? ['ash_phoenix'] : []), ...(has('Machine') ? ['ash_state_machine'] : []),
25
+ ...(has('Job', j => !!j.data.schedule) ? ['ash_oban'] : []), ...(pages && api ? ['ash_json_api'] : [])
26
+ ];
27
+ return [
28
+ { kind: 'command', run: ['mix', 'igniter.new', app(context), ...(pages ? ['--with', 'phx.new', '--with-args=--no-install'] : []), '--install', install.join(','), '--yes', '--no-git'], cwd: '..', creates: ['mix.exs', 'lib/'] },
29
+ ...(api && !pages ? [mix(['igniter.install', 'ash_json_api,bandit'])] : []),
30
+ { kind: 'command', run: ['mix', 'ash.codegen', 'initial_resources'], phase: 3 }
31
+ ];
32
+ },
33
+ steps(node, context) {
34
+ switch (node.kind) {
35
+ case 'Module': return [mix(['ash.gen.domain', moduleName(node.qn, context)])];
36
+ case 'Enum': return [mix(['ash.gen.enum', typeModule(node, context), context.children(node.qn).map(l => lastOf(l.qn)).join(',')])];
37
+ case 'ValueType': return [{ kind: 'template', file: fileOf(node, context), write: () => embedded(node, context) }];
38
+ case 'Entity': return entitySteps(node, context);
39
+ case 'EnumLiteral': return [];
40
+ case 'Field': return fieldSteps(node, context);
41
+ case 'Invariant': return [
42
+ ...(check(node, context) ? [] : [task(`enforce the invariant "${node.data.label}": ${node.props.condition}`)]),
43
+ ...testSteps(node, owner(node, context), `invariant ${node.data.label}`, ['holds for valid records', 'rejects violations'], context)
44
+ ];
45
+ case 'Policy': return [
46
+ task(`add an Ash policy to ${parentOf(node.qn)} for ${node.data.operations?.join(', ') ?? 'any action'}: ${node.props.condition}`),
47
+ ...(context.node(parentOf(node.qn)).kind === 'Entity'
48
+ ? testSteps(node, owner(node, context), lastOf(node.qn), ['allows permitted actors', 'denies other actors'], context)
49
+ : [])
50
+ ];
51
+ case 'Transition': return transitionTests(node, context);
52
+ case 'Action': return actionSteps(node, context);
53
+ case 'Machine': return machineSteps(node, context);
54
+ case 'Job': return jobSteps(node, context);
55
+ case 'Query': return querySteps(node, context);
56
+ case 'ProjectionField': return projectionFieldSteps(node, context);
57
+ case 'Interface': return interfaceSteps(node, context);
58
+ case 'Page': return pageSteps(node, context);
59
+ case 'Navigation': return navigationSteps(node, context);
60
+ case 'Messages': return [];
61
+ case 'Flow': return [task(`guide people through ${(node.data.pages ?? []).map(p => p.split('.').pop()).join(', ')} for the use case ${String(node.data.usecase).split('.').pop()}, for example with links between the LiveViews`)];
62
+ case 'Event': return [task(`publish ${lastOf(node.qn)} with an Ash notifier, for example Ash.Notifier.PubSub`)];
63
+ case 'External': return [task(`implement ${lastOf(node.qn)} as a client module or generic actions`)];
64
+ case 'UseCase': return [task(`implement ${lastOf(node.qn)} as a Reactor or a generic action`)];
65
+ case 'Role': return [task(`model the role ${lastOf(node.qn)} on the actor resource`)];
66
+ case 'Param':
67
+ case 'ErrorDecl':
68
+ case 'SetEffect':
69
+ case 'CreateEffect':
70
+ case 'EmitEffect':
71
+ case 'Projection':
72
+ case 'ExternalOperation':
73
+ case 'Endpoint':
74
+ return [];
75
+ default: return undefined;
76
+ }
77
+ }
78
+ };
79
+ export default extension;
80
+ function owner(node, context) {
81
+ return context.node(parentOf(node.qn));
82
+ }
83
+ function transitionTests(transition, context) {
84
+ const machine = owner(transition, context);
85
+ const entity = owner(context.node(machine.data.field), context);
86
+ const title = `transition ${transition.data.from.join(', ')} -> ${transition.data.to}`;
87
+ return testSteps(transition, entity, title, ['moves from allowed states', 'refuses other states'], context);
88
+ }
89
+ function entitySteps(entity, context) {
90
+ const attributes = fieldsOf(entity, context).filter(f => !f.data.derived && !relationTarget(f, context));
91
+ const specs = attributes.map(f => {
92
+ const type = f.data.type;
93
+ return [lastOf(f.qn), attributeType(type, context), ...(type.many ? ['array'] : []), ...(type.optional ? [] : ['required']), 'public'].join(':');
94
+ });
95
+ return [
96
+ mix(['ash.gen.resource', typeModule(entity, context), '--domain', moduleName(entity.module, context),
97
+ '--default-actions', 'read,create,update,destroy', '--uuid-primary-key', 'id', ...(specs.length ? ['--attribute', specs.join(',')] : []),
98
+ '--extend', 'postgres', '--timestamps']),
99
+ patch(fileOf(entity, context), existing => patchResource(existing, entity, context))
100
+ ];
101
+ }
102
+ function fieldSteps(field, context) {
103
+ const owner = context.node(parentOf(field.qn));
104
+ if (owner.kind === 'ValueType')
105
+ return field.data.derived || field.data.default ? [task(`add ${lastOf(field.qn)} to the embedded resource: ${field.props.derived ?? field.props.default}`)] : [];
106
+ if (owner.kind === 'Event')
107
+ return [];
108
+ if (owner.kind !== 'Entity')
109
+ return undefined;
110
+ const type = field.data.type;
111
+ const target = relationTarget(field, context);
112
+ if (target && type.many)
113
+ return [task(`model the many to many relationship ${lastOf(field.qn)} to ${target.qn}`)];
114
+ if (target) {
115
+ const spec = ['belongs_to', lastOf(field.qn), typeModule(target, context), ...(type.optional ? [] : ['required'])].join(':');
116
+ return [{ ...mix(['ash.gen.resource', typeModule(owner, context), '--relationship', spec]), phase: 1 }];
117
+ }
118
+ const tasks = [];
119
+ if (field.data.derived && !calculation(field, context))
120
+ tasks.push(task(`add the calculation ${lastOf(field.qn)} = ${field.props.derived}`));
121
+ if (field.data.default && defaultValue(field, context) === undefined)
122
+ tasks.push(task(`set the default of ${lastOf(field.qn)} to ${field.props.default}`));
123
+ return tasks;
124
+ }
125
+ /** Adds defaults, identities, calculations and validations to the resource `ash.gen.resource` created. */
126
+ function patchResource(text, entity, context) {
127
+ const fields = fieldsOf(entity, context);
128
+ for (const field of fields) {
129
+ const value = defaultValue(field, context);
130
+ if (value !== undefined)
131
+ text = text.replace(new RegExp(`(\\n([ \\t]*)attribute :${lastOf(field.qn)}, [^\\n]* do\\n)`), `$1$2 default ${value}\n`);
132
+ }
133
+ const blocks = [
134
+ block('identities', fields.filter(f => (f.data.modifiers ?? []).includes('unique')).map(f => `identity :unique_${lastOf(f.qn)}, [:${lastOf(f.qn)}]`)),
135
+ block('calculations', fields.flatMap(f => calculation(f, context) ?? [])),
136
+ block('validations', context.children(entity.qn).filter(n => n.kind === 'Invariant').flatMap(n => {
137
+ const rule = check(n, context);
138
+ return rule ? [`validate ${rule}, message: ${JSON.stringify(n.data.label)}`] : [];
139
+ }))
140
+ ].filter(Boolean).join('');
141
+ return blocks ? text.replace(/\nend\n?$/, `\n${blocks}end\n`) : text;
142
+ }
143
+ function block(name, lines) {
144
+ return lines.length ? `\n ${name} do\n${lines.map(l => ` ${l}\n`).join('')} end\n` : '';
145
+ }
146
+ function check(invariant, context) {
147
+ return validation(invariant.data.condition, storedAttributes(context.node(parentOf(invariant.qn)), context), context.node);
148
+ }
149
+ function defaultValue(field, context) {
150
+ const expr = field.data.default;
151
+ if (!expr)
152
+ return undefined;
153
+ if (expr.$type === 'NameExpr' && expr.name === 'now' && !expr.target)
154
+ return '&DateTime.utc_now/0';
155
+ return constant(expr, context.node);
156
+ }
157
+ function embedded(node, context) {
158
+ const attributes = fieldsOf(node, context).filter(f => !f.data.derived).map(f => {
159
+ const type = f.data.type;
160
+ const elixirType = type.many ? `{:array, ${attributeType(type, context, true)}}` : attributeType(type, context, true);
161
+ return ` attribute :${lastOf(f.qn)}, ${elixirType}, allow_nil?: ${type.optional ? 'true' : 'false'}, public?: true\n`;
162
+ });
163
+ return `defmodule ${typeModule(node, context)} do\n use Ash.Resource, data_layer: :embedded\n\n attributes do\n${attributes.join('')} end\nend\n`;
164
+ }
@@ -0,0 +1,7 @@
1
+ import type { MapContext, MigrationChange, ProjectFiles, Step } from '@appling/codegen';
2
+ /**
3
+ * Carries one Appling migration step into the generated project: the resource changes, an Ecto
4
+ * migration renames, retypes or removes the column, and the resource snapshots are brought up to date
5
+ * so `mix ash.codegen` does not guess a rename as a drop and an add.
6
+ */
7
+ export declare function migrationSteps(change: MigrationChange, context: MapContext, files: ProjectFiles): Step[];
@@ -0,0 +1,62 @@
1
+ import { lastOf } from './elixir.js';
2
+ import { app, attributeType, fileOf, pascal, task } from './naming.js';
3
+ const COLUMNS = {
4
+ string: ':text', integer: ':bigint', decimal: ':decimal', boolean: ':boolean', date: ':date',
5
+ utc_datetime_usec: ':utc_datetime_usec', duration: ':interval', uuid: ':uuid'
6
+ };
7
+ /**
8
+ * Carries one Appling migration step into the generated project: the resource changes, an Ecto
9
+ * migration renames, retypes or removes the column, and the resource snapshots are brought up to date
10
+ * so `mix ash.codegen` does not guess a rename as a drop and an add.
11
+ */
12
+ export function migrationSteps(change, context, files) {
13
+ const parent = change.parent ? context.node(change.parent) : undefined;
14
+ const element = change.current ? context.node(change.current) : undefined;
15
+ if (parent?.kind !== 'Entity' || (element && element.kind !== 'Field')) {
16
+ return [task(`carry the ${change.kind} of ${change.target} into the resources and the database`)];
17
+ }
18
+ const resource = fileOf(parent, context);
19
+ const table = /\n\s+table "(\w+)"/.exec(files.read(resource) ?? '')?.[1];
20
+ if (!table)
21
+ return [task(`carry the ${change.kind} of ${change.target} into ${resource}`)];
22
+ const old = lastOf(change.target);
23
+ const atom = new RegExp(`:${old}\\b`, 'g');
24
+ let patch;
25
+ let statement;
26
+ if (change.kind === 'rename') {
27
+ patch = text => text.replace(atom, `:${change.newName}`);
28
+ statement = `rename table(:${table}), :${old}, to: :${change.newName}`;
29
+ }
30
+ else if (change.kind === 'retype') {
31
+ const type = element.data.type;
32
+ patch = text => text.replace(new RegExp(`(\\n\\s+attribute :${old}, )[^,\\n]+( do|,)`), `$1${elixirType(type, context)}$2`);
33
+ statement = `alter table(:${table}) do\n modify :${old}, ${column(type, context)}\n end`;
34
+ }
35
+ else {
36
+ patch = text => text
37
+ .replace(new RegExp(`\\n\\s+attribute :${old}, [^\\n]* do\\n[\\s\\S]*?\\n\\s+end\\n`), '\n')
38
+ .replace(new RegExp(`\\n\\s+attribute :${old}, [^\\n]*\\n`), '\n')
39
+ .replace(new RegExp(`(, )?:${old}\\b(, )?`, 'g'), (_, before, after) => (before && after ? ', ' : ''));
40
+ statement = `alter table(:${table}) do\n remove :${old}\n end`;
41
+ }
42
+ const migration = `priv/repo/migrations/${change.stamp}_appling_${change.block}.exs`;
43
+ const module = `${pascal(app(context))}.Repo.Migrations.Appling${pascal(change.block)}`;
44
+ return [
45
+ { kind: 'template', file: resource, write: existing => patch(existing) },
46
+ {
47
+ kind: 'template', file: migration, write: existing => (existing
48
+ ?? `defmodule ${module} do\n use Ecto.Migration\n\n def change do\n end\nend\n`).replace(/\n end\nend\n$/, `\n ${statement}\n end\nend\n`)
49
+ },
50
+ { kind: 'command', run: ['mix', 'ash_postgres.generate_migrations', '--snapshots-only'], phase: 1 },
51
+ task(`update the code that uses ${change.target} after the ${change.kind}${change.newName ? ` to ${change.newName}` : ''}; resources and migrations are done`)
52
+ ];
53
+ }
54
+ function elixirType(type, context) {
55
+ const base = attributeType(type, context, true);
56
+ return type.many ? `{:array, ${base}}` : base;
57
+ }
58
+ function column(type, context) {
59
+ const decl = type.decl ? context.node(type.decl) : undefined;
60
+ const base = decl?.kind === 'ValueType' ? ':map' : decl ? ':text' : COLUMNS[attributeType(type, context)];
61
+ return type.many ? `{:array, ${base}}` : base;
62
+ }
@@ -0,0 +1,21 @@
1
+ import type { CommandStep, MapContext, Step } from '@appling/codegen';
2
+ import type { GraphNode, TypeData } from '@appling/model';
3
+ export declare const TYPES: Record<string, string>;
4
+ export declare function attributeType(type: TypeData, context: MapContext, asCode?: boolean): string;
5
+ export declare function relationTarget(field: GraphNode, context: MapContext): GraphNode | undefined;
6
+ export declare function fieldsOf(node: GraphNode, context: MapContext): GraphNode[];
7
+ export declare function app(context: MapContext): string;
8
+ export declare function moduleName(moduleQn: string, context: MapContext): string;
9
+ export declare function typeModule(node: GraphNode, context: MapContext): string;
10
+ export declare function fileOf(node: GraphNode, context: MapContext): string;
11
+ export declare function pascal(name: string): string;
12
+ export declare function snake(name: string): string;
13
+ export declare function mix(args: string[]): CommandStep;
14
+ export declare function task(what: string): Step;
15
+ export declare function children(node: GraphNode, context: MapContext, kind?: string): GraphNode[];
16
+ /** The attributes of a resource that are stored columns, not calculations or relationships. */
17
+ export declare function storedAttributes(entity: GraphNode, context: MapContext): Set<string>;
18
+ /** Patches a generated module after every resource and relationship exists, so expressions may follow relationships. */
19
+ export declare function patch(file: string, write: (existing: string) => string): Step;
20
+ /** The calculation for a derived field, or undefined when Ash expressions cannot say it. */
21
+ export declare function calculation(field: GraphNode, context: MapContext): string | undefined;
package/out/naming.js ADDED
@@ -0,0 +1,59 @@
1
+ import { ashExpr, lastOf } from './elixir.js';
2
+ export const TYPES = {
3
+ String: 'string', Text: 'string', Int: 'integer', Decimal: 'decimal', Money: 'decimal', Bool: 'boolean',
4
+ Date: 'date', DateTime: 'utc_datetime_usec', Duration: 'duration', File: 'string', Uuid: 'uuid'
5
+ };
6
+ export function attributeType(type, context, asCode = false) {
7
+ if (type.primitive)
8
+ return asCode ? `:${TYPES[type.primitive]}` : TYPES[type.primitive];
9
+ return typeModule(context.node(type.decl), context);
10
+ }
11
+ export function relationTarget(field, context) {
12
+ const decl = field.data.type?.decl;
13
+ const target = decl ? context.node(decl) : undefined;
14
+ return target?.kind === 'Entity' ? target : undefined;
15
+ }
16
+ export function fieldsOf(node, context) {
17
+ return context.children(node.qn).filter(f => f.kind === 'Field');
18
+ }
19
+ export function app(context) {
20
+ return context.name.toLowerCase().replace(/[^a-z0-9_]/g, '_');
21
+ }
22
+ export function moduleName(moduleQn, context) {
23
+ return [app(context), ...moduleQn.split('.')].map(pascal).join('.');
24
+ }
25
+ export function typeModule(node, context) {
26
+ return `${moduleName(node.module, context)}.${lastOf(node.qn)}`;
27
+ }
28
+ export function fileOf(node, context) {
29
+ return ['lib', app(context), ...node.module.split('.').map(snake), `${snake(lastOf(node.qn))}.ex`].join('/');
30
+ }
31
+ export function pascal(name) {
32
+ return name.split('_').map(part => part.charAt(0).toUpperCase() + part.slice(1)).join('');
33
+ }
34
+ export function snake(name) {
35
+ return name.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase();
36
+ }
37
+ export function mix(args) {
38
+ return { kind: 'command', run: ['mix', ...args, '--yes'] };
39
+ }
40
+ export function task(what) {
41
+ return { kind: 'task', what };
42
+ }
43
+ export function children(node, context, kind) {
44
+ return context.children(node.qn).filter(c => !kind || c.kind === kind);
45
+ }
46
+ /** The attributes of a resource that are stored columns, not calculations or relationships. */
47
+ export function storedAttributes(entity, context) {
48
+ return new Set(fieldsOf(entity, context).filter(f => !f.data.derived && !relationTarget(f, context)).map(f => f.qn));
49
+ }
50
+ /** Patches a generated module after every resource and relationship exists, so expressions may follow relationships. */
51
+ export function patch(file, write) {
52
+ return { kind: 'template', file, write: existing => write(existing), phase: 2 };
53
+ }
54
+ /** The calculation for a derived field, or undefined when Ash expressions cannot say it. */
55
+ export function calculation(field, context) {
56
+ const type = field.data.type;
57
+ const body = field.data.derived && !type.many && ashExpr(field.data.derived, context.node);
58
+ return body ? `calculate :${lastOf(field.qn)}, ${attributeType(type, context, true)}, expr(${body})` : undefined;
59
+ }
package/out/pages.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ import type { MapContext, Step } from '@appling/codegen';
2
+ import type { GraphNode } from '@appling/model';
3
+ /** Whether the model has pages, which makes the generated project a Phoenix application. */
4
+ export declare function hasPages(context: MapContext): boolean;
5
+ export declare function web(context: MapContext): string;
6
+ /**
7
+ * A page becomes a LiveView: lists read through the query's read action into a `.table`, details load
8
+ * the record of the route's `:id` into a `.list`, forms are AshPhoenix forms for the action. Row actions
9
+ * and forms run the action and report the outcome as a flash.
10
+ */
11
+ export declare function pageSteps(page: GraphNode, context: MapContext): Step[];
12
+ export declare function navigationSteps(navigation: GraphNode, context: MapContext): Step[];
package/out/pages.js ADDED
@@ -0,0 +1,173 @@
1
+ import { ashExpr, lastOf } from './elixir.js';
2
+ import { app, calculation, children, pascal, patch, snake, task, typeModule, TYPES } from './naming.js';
3
+ /** Whether the model has pages, which makes the generated project a Phoenix application. */
4
+ export function hasPages(context) {
5
+ return context.graph.nodes.some(n => n.kind === 'Page');
6
+ }
7
+ export function web(context) {
8
+ return `${pascal(app(context))}Web`;
9
+ }
10
+ /**
11
+ * A page becomes a LiveView: lists read through the query's read action into a `.table`, details load
12
+ * the record of the route's `:id` into a `.list`, forms are AshPhoenix forms for the action. Row actions
13
+ * and forms run the action and report the outcome as a flash.
14
+ */
15
+ export function pageSteps(page, context) {
16
+ const tasks = [];
17
+ const name = `${lastOf(page.qn)}Live`;
18
+ const route = String(page.data.route).replace(/\{(\w+)\}/g, ':$1');
19
+ const byId = route.includes(':id');
20
+ const assigns = [];
21
+ const markup = [];
22
+ const events = new Map();
23
+ page.data.components.forEach((component, i) => {
24
+ const id = `${component.$type === 'ListView' ? 'list' : component.$type === 'DetailView' ? 'record' : 'form'}_${i + 1}`;
25
+ const actions = (component.actions ?? []).map(qn => context.node(qn)).filter(action => {
26
+ const ok = !!action.data.entity && !children(action, context, 'Param').some(p => !p.data.type.optional);
27
+ if (!ok)
28
+ tasks.push(task(`offer ${lastOf(action.qn)} on ${lastOf(page.qn)}; it needs inputs, so it needs a form`));
29
+ return ok;
30
+ });
31
+ for (const action of actions)
32
+ events.set(`run_${snake(lastOf(action.qn))}`, runEvent(action, context));
33
+ const buttons = (record) => actions.map(a => `<.button phx-click="run_${snake(lastOf(a.qn))}" phx-value-id={${record}.id}>${lastOf(a.qn)}</.button>`).join(' ');
34
+ if (component.$type === 'ListView') {
35
+ const query = context.node(component.query);
36
+ const entity = context.node(query.data.entity);
37
+ const columns = columnsOf(component.projection, component.picks, context, tasks);
38
+ const load = columns.filter(c => c.load).map(c => `:${c.field}`);
39
+ const read = `Ash.read!(${typeModule(entity, context)}, action: :${snake(lastOf(query.qn))}${load.length ? `, load: [${load.join(', ')}]` : ''}${query.data.pageSize ? `, page: [limit: ${query.data.pageSize}]` : ''})`;
40
+ assigns.push(`|> assign(:${id}, ${query.data.pageSize ? `${read}.results` : read})`);
41
+ 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>');
42
+ }
43
+ else if (component.$type === 'DetailView') {
44
+ if (!byId) {
45
+ tasks.push(task(`show ${lastOf(component.projection)} on ${lastOf(page.qn)}; the route has no :id`));
46
+ return;
47
+ }
48
+ const entity = sourceEntity(component.projection, context);
49
+ const columns = columnsOf(component.projection, component.picks, context, tasks);
50
+ const load = columns.filter(c => c.load).map(c => `:${c.field}`);
51
+ assigns.push(`|> assign(:${id}, Ash.get!(${typeModule(entity, context)}, socket.assigns.id${load.length ? `, load: [${load.join(', ')}]` : ''}))`);
52
+ markup.push('<.list>', ...columns.map(c => ` <:item title=${JSON.stringify(c.label)}>{to_string(@${id}.${c.field})}</:item>`), '</.list>', ...(actions.length ? [buttons(`@${id}`)] : []));
53
+ }
54
+ else if (component.$type === 'FormView') {
55
+ const action = context.node(component.submits);
56
+ const entity = action.kind === 'Action' && action.data.entity ? context.node(action.data.entity) : undefined;
57
+ if (!entity || !byId) {
58
+ tasks.push(task(`offer the form ${lastOf(action.qn)} on ${lastOf(page.qn)}`));
59
+ return;
60
+ }
61
+ const event = `submit_${snake(lastOf(action.qn))}`;
62
+ assigns.push(`|> assign(:${id}, AshPhoenix.Form.for_update(Ash.get!(${typeModule(entity, context)}, socket.assigns.id), :${snake(lastOf(action.qn))}) |> to_form())`);
63
+ events.set(event, [
64
+ `def handle_event("${event}", %{"form" => params}, socket) do`,
65
+ ` case AshPhoenix.Form.submit(socket.assigns.${id}, params: params) do`,
66
+ ` {:ok, _} -> {:noreply, socket |> put_flash(:info, ${JSON.stringify(`${lastOf(action.qn)} done.`)}) |> load()}`,
67
+ ` {:error, form} -> {:noreply, assign(socket, :${id}, form)}`,
68
+ ' end',
69
+ 'end'
70
+ ].join('\n'));
71
+ 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>');
72
+ }
73
+ });
74
+ const nav = navigationLinks(page.module, context);
75
+ const code = [
76
+ `defmodule ${web(context)}.${name} do`,
77
+ ` use ${web(context)}, :live_view`,
78
+ '',
79
+ ' @impl true',
80
+ ` def mount(${byId ? '%{"id" => id}' : '_params'}, _session, socket) do`,
81
+ ` {:ok, socket |> assign(:page_title, ${JSON.stringify(title(lastOf(page.qn)))})${byId ? ' |> assign(:id, id)' : ''} |> load()}`,
82
+ ' end',
83
+ '',
84
+ ' defp load(socket) do',
85
+ ' socket',
86
+ ...assigns.map(a => ` ${a}`),
87
+ ' end',
88
+ ...[...events.values()].flatMap(handler => ['', ' @impl true', ...handler.split('\n').map(l => ` ${l}`)]),
89
+ '',
90
+ ' @impl true',
91
+ ' def render(assigns) do',
92
+ ' ~H"""',
93
+ ' <Layouts.app flash={@flash}>',
94
+ ...(nav ? [` ${nav}`] : []),
95
+ ` <.header>${title(lastOf(page.qn))}</.header>`,
96
+ ...markup.map(l => ` ${l}`),
97
+ ' </Layouts.app>',
98
+ ' """',
99
+ ' end',
100
+ 'end',
101
+ ''
102
+ ].join('\n');
103
+ return [
104
+ { kind: 'template', file: `lib/${app(context)}_web/live/${snake(lastOf(page.qn))}_live.ex`, write: () => code, phase: 2 },
105
+ patch(`lib/${app(context)}_web/router.ex`, existing => existing.includes(`live "${route}", ${name}`) ? existing
106
+ : existing.replace(/(\n(\s*)get "\/", PageController, :home\n)/, `$1$2live "${route}", ${name}\n`)),
107
+ ...tasks
108
+ ];
109
+ }
110
+ function runEvent(action, context) {
111
+ const entity = context.node(action.data.entity);
112
+ return [
113
+ `def handle_event("run_${snake(lastOf(action.qn))}", %{"id" => id}, socket) do`,
114
+ ` case Ash.update(Ash.get!(${typeModule(entity, context)}, id), %{}, action: :${snake(lastOf(action.qn))}) do`,
115
+ ` {:ok, _} -> {:noreply, socket |> put_flash(:info, ${JSON.stringify(`${lastOf(action.qn)} done.`)}) |> load()}`,
116
+ ` {:error, error} -> {:noreply, put_flash(socket, :error, ${JSON.stringify(`${lastOf(action.qn)} failed: `)} <> Exception.message(error))}`,
117
+ ' end',
118
+ 'end'
119
+ ].join('\n');
120
+ }
121
+ /** The navigation of the module as links; items to pages that need an id are left out. */
122
+ function navigationLinks(module, context) {
123
+ const items = context.graph.nodes.filter(n => n.kind === 'Navigation' && n.module === module).flatMap(n => (n.data.items ?? []));
124
+ const links = items.filter(i => !String(context.node(i.page)?.data.route ?? '').includes('{')).map(i => `<.link navigate="${context.node(i.page).data.route}">${i.label}</.link>`);
125
+ return links.length ? `<nav class="flex gap-4 mb-6">${links.join(' ')}</nav>` : undefined;
126
+ }
127
+ export function navigationSteps(navigation, context) {
128
+ return (navigation.data.items ?? [])
129
+ .filter(i => String(context.node(i.page)?.data.route ?? '').includes('{'))
130
+ .map(i => task(`link ${i.label} in ${lastOf(navigation.qn)}; its page needs an id`));
131
+ }
132
+ /** Projection fields as columns: stored attributes as they are, derived and computed fields through their calculations. */
133
+ function columnsOf(projectionQn, picks, context, tasks) {
134
+ const projection = context.node(projectionQn);
135
+ const entity = sourceEntity(projectionQn, context);
136
+ const fields = new Map(children(entity, context, 'Field').map(f => [lastOf(f.qn), f]));
137
+ const chosen = picks?.length ? picks.map(p => context.node(p)) : children(projection, context, 'ProjectionField');
138
+ return chosen.flatMap(field => {
139
+ const name = lastOf(field.qn);
140
+ const label = labelOf(projection, name, context);
141
+ const value = field.data.value;
142
+ if (value) {
143
+ if (ashExpr(value, context.node) && TYPES[value.type.replace(/\?$/, '')])
144
+ return [{ label, field: name, load: true }];
145
+ }
146
+ else {
147
+ const source = fields.get(name);
148
+ if (source && !source.data.derived)
149
+ return [{ label, field: name }];
150
+ if (source && calculation(source, context))
151
+ return [{ label, field: name, load: true }];
152
+ }
153
+ tasks.push(task(`show ${name} of ${lastOf(projection.qn)} on pages`));
154
+ return [];
155
+ });
156
+ }
157
+ function labelOf(projection, field, context) {
158
+ const key = `${lastOf(projection.qn)}.${field}`;
159
+ for (const messages of context.graph.nodes.filter(n => n.kind === 'Messages' && n.module === projection.module)) {
160
+ const entry = (messages.data.entries ?? []).find(e => e.key === key);
161
+ if (entry)
162
+ return entry.text;
163
+ }
164
+ return title(field);
165
+ }
166
+ function sourceEntity(projectionQn, context) {
167
+ const source = context.node(context.node(projectionQn).data.source);
168
+ return source.kind === 'Query' ? context.node(source.data.entity) : source;
169
+ }
170
+ function title(name) {
171
+ const words = name.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/_/g, ' ').toLowerCase();
172
+ return words.charAt(0).toUpperCase() + words.slice(1);
173
+ }
@@ -0,0 +1,8 @@
1
+ /** Text patches for resource and domain modules generated by `ash.gen.*`. */
2
+ /**
3
+ * Adds lines at the end of a `name do ... end` section of a module, creating it before the module's
4
+ * `end` when missing. With `inner`, the lines go into a section nested in it, such as `oban` > `triggers`.
5
+ */
6
+ export declare function addToSection(text: string, name: string, lines: string[], inner?: string): string;
7
+ /** Adds an extension to the `use Ash.Resource` or `use Ash.Domain` options. */
8
+ export declare function addExtension(text: string, extension: string): string;
@@ -0,0 +1,37 @@
1
+ /** Text patches for resource and domain modules generated by `ash.gen.*`. */
2
+ /**
3
+ * Adds lines at the end of a `name do ... end` section of a module, creating it before the module's
4
+ * `end` when missing. With `inner`, the lines go into a section nested in it, such as `oban` > `triggers`.
5
+ */
6
+ export function addToSection(text, name, lines, inner) {
7
+ const section = new RegExp(`\\n ${name} do\\n([\\s\\S]*?)\\n end\\n`);
8
+ const match = section.exec(text);
9
+ if (!match) {
10
+ const body = inner ? [`${inner} do`, ...lines.map(l => ` ${l}`), 'end'] : lines;
11
+ return text.replace(/\nend\n?$/, `\n\n ${name} do\n${indent(body, ' ')}\n end\nend\n`);
12
+ }
13
+ const separator = lines[0].endsWith(' do') ? '\n' : '';
14
+ const content = inner ? addToInner(match[1], inner, lines) : `${match[1]}\n${separator}${indent(lines, ' ')}`;
15
+ return text.replace(match[0], `\n ${name} do\n${content}\n end\n`);
16
+ }
17
+ function addToInner(content, inner, lines) {
18
+ const section = new RegExp(`(^|\\n) ${inner} do\\n([\\s\\S]*?)\\n end(?=\\n|$)`);
19
+ const match = section.exec(content);
20
+ if (!match)
21
+ return `${content}\n\n${indent([`${inner} do`, ...lines.map(l => ` ${l}`), 'end'], ' ')}`;
22
+ const separator = lines[0].endsWith(' do') ? '\n' : '';
23
+ return content.replace(match[0], `${match[1]} ${inner} do\n${match[2]}\n${separator}${indent(lines, ' ')}\n end`);
24
+ }
25
+ function indent(lines, prefix) {
26
+ return lines.map(l => (l ? prefix + l : l)).join('\n');
27
+ }
28
+ /** Adds an extension to the `use Ash.Resource` or `use Ash.Domain` options. */
29
+ export function addExtension(text, extension) {
30
+ const match = /use Ash\.(Resource|Domain),?[^\n]*(?:\n {4,}[^\n]*)*/.exec(text);
31
+ if (!match || match[0].includes(extension))
32
+ return text;
33
+ const updated = /extensions: \[/.test(match[0])
34
+ ? match[0].replace(/extensions: \[/, `extensions: [${extension}, `)
35
+ : `${match[0]},\n extensions: [${extension}]`;
36
+ return text.replace(match[0], updated);
37
+ }
package/out/tests.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import type { MapContext, Step } from '@appling/codegen';
2
+ import type { GraphNode } from '@appling/model';
3
+ /**
4
+ * Skipped ExUnit tests for a rule in the test module of its resource, one per case. Bodies are registry
5
+ * tasks; each test points at its entry.
6
+ */
7
+ export declare function testSteps(node: GraphNode, resource: GraphNode, title: string, cases: string[], context: MapContext): Step[];
package/out/tests.js ADDED
@@ -0,0 +1,19 @@
1
+ import { lastOf } from './elixir.js';
2
+ import { app, snake, task, typeModule } from './naming.js';
3
+ /**
4
+ * Skipped ExUnit tests for a rule in the test module of its resource, one per case. Bodies are registry
5
+ * tasks; each test points at its entry.
6
+ */
7
+ export function testSteps(node, resource, title, cases, context) {
8
+ const module = `${typeModule(resource, context)}Test`;
9
+ const file = ['test', app(context), ...resource.module.split('.').map(snake), `${snake(lastOf(resource.qn))}_test.exs`].join('/');
10
+ const tests = cases.map(c => ` @tag skip: ${JSON.stringify(`registry task: ${node.qn}`)}\n test ${JSON.stringify(`${title} ${c}`)}\n`).join('\n');
11
+ return [
12
+ {
13
+ kind: 'template', file, write: existing => existing
14
+ ? existing.replace(/end\n?$/, `\n${tests}end\n`)
15
+ : `defmodule ${module} do\n use ExUnit.Case, async: true\n\n${tests}end\n`
16
+ },
17
+ task(`write the tests "${title}" in ${file}`)
18
+ ];
19
+ }
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "@appling/codegen-ash",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Appling code generation extension for Ash",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./out/index.d.ts",
9
+ "default": "./out/index.js"
10
+ }
11
+ },
12
+ "files": [
13
+ "out"
14
+ ],
15
+ "dependencies": {
16
+ "@appling/model": "0.1.1"
17
+ },
18
+ "peerDependencies": {
19
+ "@appling/codegen": "0.1.1"
20
+ },
21
+ "devDependencies": {
22
+ "@appling/codegen": "0.1.1",
23
+ "@types/node": "^24.19.2",
24
+ "typescript": "7.0.2"
25
+ },
26
+ "license": "MIT",
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "scripts": {
31
+ "build": "tsc"
32
+ }
6
33
  }