@apso/cli 0.55.0 → 0.57.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/commands/import/data.d.ts +1 -0
  2. package/dist/commands/import/data.js +8 -3
  3. package/dist/commands/import/{supabase.d.ts → index.d.ts} +4 -1
  4. package/dist/commands/import/{supabase.js → index.js} +20 -11
  5. package/dist/commands/mcp/serve.js +5 -2
  6. package/dist/commands/schema/validate.js +5 -0
  7. package/dist/lib/access/cases.js +1 -2
  8. package/dist/lib/access/rules.json +1 -1
  9. package/dist/lib/api/services.js +15 -1
  10. package/dist/lib/base-command.d.ts +6 -0
  11. package/dist/lib/base-command.js +14 -0
  12. package/dist/lib/ddl/index.d.ts +12 -7
  13. package/dist/lib/ddl/index.js +50 -22
  14. package/dist/lib/generators/go.d.ts +18 -0
  15. package/dist/lib/generators/go.js +40 -18
  16. package/dist/lib/generators/python.js +6 -7
  17. package/dist/lib/generators/typescript.js +76 -14
  18. package/dist/lib/guards.d.ts +43 -5
  19. package/dist/lib/guards.js +148 -18
  20. package/dist/lib/import/copy-data.js +4 -2
  21. package/dist/lib/import/introspect.js +23 -10
  22. package/dist/lib/import/pg-to-apsorc.d.ts +5 -1
  23. package/dist/lib/import/pg-to-apsorc.js +44 -32
  24. package/dist/lib/import/types.d.ts +9 -4
  25. package/dist/lib/migrate/sandbox.js +4 -0
  26. package/dist/lib/templates/entities/entity.eta +2 -2
  27. package/dist/lib/templates/go/middleware/auth.eta +136 -7
  28. package/dist/lib/templates/go/services/service.eta +29 -1
  29. package/dist/lib/templates/guards/permission.guard.eta +15 -0
  30. package/dist/lib/templates/guards/scope.guard.eta +9 -5
  31. package/dist/lib/templates/python/auth.eta +100 -2
  32. package/dist/lib/templates/python/services/service.eta +19 -0
  33. package/dist/lib/templates/rest/controller-rest.eta +17 -2
  34. package/dist/lib/templates/rest/dto-rest.eta +20 -8
  35. package/dist/lib/templates/rest/index-module-rest.eta +5 -1
  36. package/dist/lib/types/constraints.d.ts +6 -1
  37. package/dist/lib/types/relationship.d.ts +40 -1
  38. package/dist/lib/types/relationship.js +34 -1
  39. package/dist/lib/utils/relationships/parse.js +25 -0
  40. package/npm-shrinkwrap.json +2 -2
  41. package/oclif.manifest.json +23 -14
  42. package/package.json +1 -1
@@ -43,6 +43,7 @@ import jwt
43
43
  from fastapi import HTTPException, Request, Response, status
44
44
  from jwt import PyJWKClient
45
45
  from sqlalchemy import String, cast, func, select
46
+ from sqlalchemy.orm import aliased
46
47
  from starlette.concurrency import run_in_threadpool
47
48
 
48
49
 
@@ -409,6 +410,98 @@ def relation_refused(auth: Optional[AuthContext], root: str, path: str) -> Optio
409
410
  return None
410
411
 
411
412
 
413
+ # entity -> its scopeBy paths through a parent (task.workspaceId), each as
414
+ # {"field": the entity's foreign key to the first parent, "parents": [{"entity",
415
+ # "field": its foreign key to the next parent, absent on the last}],
416
+ # "tenantField": the tenant column on the last parent, "source": "userId",
417
+ # "email" or "tenant"}.
418
+ NESTED_SCOPES: dict = json.loads(<%~ JSON.stringify(JSON.stringify(it.nestedScopes)) %>)
419
+
420
+
421
+ def _caller_value(auth: Optional[AuthContext], source: str) -> Any:
422
+ """The caller's value for a scopeBy key: its user id, its email, or its tenant."""
423
+ by_key = {"userId": "user_id", "email": "email"}
424
+ return getattr(auth, by_key.get(source, "workspace_id"), None)
425
+
426
+
427
+ def _skips_scope(auth: Optional[AuthContext], entity: str) -> bool:
428
+ """A service caller, or a role that skips `entity`'s tenant scope."""
429
+ if auth is None:
430
+ return False
431
+ bypass = (RELATION_SCOPES.get(entity) or {}).get("bypassRoles") or []
432
+ return bool(auth.service_id) or bool(set(auth.roles) & set(bypass))
433
+
434
+
435
+ def _parents_in_tenant(nested: dict, index: int, value: Any) -> Any:
436
+ """
437
+ The ids of the parent at `index` of a scopeBy path that are in the caller's
438
+ tenant: the tenant column on the last parent, reached through each parent's
439
+ foreign key to the next. Each parent is aliased, so a path through the same
440
+ table twice does not correlate with the query around it.
441
+ """
442
+ from . import models
443
+
444
+ parents = nested["parents"]
445
+ parent = aliased(getattr(models, parents[index]["entity"]))
446
+ if index == len(parents) - 1:
447
+ condition = cast(getattr(parent, nested["tenantField"]), String) == str(value)
448
+ else:
449
+ condition = getattr(parent, parents[index]["field"]).in_(_parents_in_tenant(nested, index + 1, value))
450
+ return select(parent.id).where(condition)
451
+
452
+
453
+ def nested_conditions(auth: Optional[AuthContext], entity: str, model: Any) -> list:
454
+ """
455
+ SQL conditions that keep rows of `entity` (as `model`) to the caller's
456
+ tenant through each scopeBy path that runs through a parent
457
+ (task.workspaceId): the foreign key must name a parent in that tenant.
458
+ Empty for a service caller or a role that skips the entity's scope; 403
459
+ when the caller has no value for a path.
460
+ """
461
+ nested = NESTED_SCOPES.get(entity) or []
462
+ if not nested or _skips_scope(auth, entity):
463
+ return []
464
+ conditions = []
465
+ for n in nested:
466
+ value = _caller_value(auth, n["source"])
467
+ if value in (None, ""):
468
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="No tenant in the auth context")
469
+ conditions.append(getattr(model, n["field"]).in_(_parents_in_tenant(n, 0, value)))
470
+ return conditions
471
+
472
+
473
+ async def check_parents(auth: Optional[AuthContext], db: Any, entity: str, rows: List[dict]) -> None:
474
+ """
475
+ On a write to `entity`, each foreign key its scopeBy runs through
476
+ (task.workspaceId) must name a parent in the caller's tenant; otherwise
477
+ 403. A key that is absent or null is not checked, and a service caller or a
478
+ role that skips the entity's scope is not limited.
479
+ """
480
+ from . import models
481
+
482
+ nested = NESTED_SCOPES.get(entity) or []
483
+ if not nested or _skips_scope(auth, entity):
484
+ return
485
+ for n in nested:
486
+ ids = {row.get(n["field"]) for row in rows} - {None}
487
+ if not ids:
488
+ continue
489
+ value = _caller_value(auth, n["source"])
490
+ parent = getattr(models, n["parents"][0]["entity"])
491
+ found = None
492
+ if value not in (None, ""):
493
+ found = await db.execute(
494
+ select(func.count())
495
+ .select_from(parent)
496
+ .where(parent.id.in_(ids), parent.id.in_(_parents_in_tenant(n, 0, value)))
497
+ )
498
+ if found is None or found.scalar() != len(ids):
499
+ raise HTTPException(
500
+ status_code=status.HTTP_403_FORBIDDEN,
501
+ detail="You do not have access to a row this request references",
502
+ )
503
+
504
+
412
505
  def tenant_values(auth: Optional[AuthContext], entity: str) -> Optional[dict]:
413
506
  """
414
507
  The caller's value for each scopeBy field of `entity`, or None when the
@@ -445,7 +538,10 @@ def relation_conditions(auth: Optional[AuthContext], root: str, name: str, targe
445
538
  hop = ((RELATION_SCOPES.get(root) or {}).get("relations") or {}).get(name)
446
539
  # Only a hop the rule allows as a same-tenant one; any other is refused or not limited.
447
540
  values = tenant_values(auth, hop[0]) if hop and hop[1] else None
448
- return _tenant_conditions(target, values) if values else []
541
+ if values is None:
542
+ return []
543
+ # A target scoped through a parent has no tenant column of its own.
544
+ return _tenant_conditions(target, values) + nested_conditions(auth, hop[0], target)
449
545
 
450
546
 
451
547
  async def check_references(auth: Optional[AuthContext], db: Any, references: dict) -> None:
@@ -465,7 +561,9 @@ async def check_references(auth: Optional[AuthContext], db: Any, references: dic
465
561
  continue
466
562
  model = getattr(models, entity)
467
563
  found = await db.execute(
468
- select(func.count()).select_from(model).where(model.id.in_(ids), *_tenant_conditions(model, values))
564
+ select(func.count())
565
+ .select_from(model)
566
+ .where(model.id.in_(ids), *_tenant_conditions(model, values), *nested_conditions(auth, entity, model))
469
567
  )
470
568
  if found.scalar() != len(ids):
471
569
  raise HTTPException(
@@ -11,6 +11,9 @@ from sqlalchemy import String, cast
11
11
  <% if (it.references.length) { %>
12
12
  from ..auth import check_references
13
13
  <% } %>
14
+ <% if (it.scope && it.scope.nested.length) { %>
15
+ from ..auth import check_parents, nested_conditions
16
+ <% } %>
14
17
  from ..models.<%= it.entityName.toLowerCase() %> import <%= it.entityName %>
15
18
  from ..schemas.<%= it.entityName.toLowerCase() %> import <%= it.entityName %>Create, <%= it.entityName %>Update
16
19
  from ..utils.query import QueryBuilder, QueryOptions, PaginatedResult
@@ -57,6 +60,10 @@ class <%= it.entityName %>Service:
57
60
  cast(getattr(<%= it.entityName %>, field), String) == str(value)
58
61
  for field, value in self._scope_values(op).items()
59
62
  ]
63
+ <% if (it.scope.nested.length) { %>
64
+ # A path through a parent (task.workspaceId): the parent must be in the caller's tenant.
65
+ scope += nested_conditions(self.auth, <%~ JSON.stringify(it.entityName) %>, <%= it.entityName %>)
66
+ <% } %>
60
67
  return QueryBuilder(<%= it.entityName %>, self.db, auth=self.auth, scope=scope)
61
68
 
62
69
  def _with_tenant(self, payload: dict) -> dict:
@@ -115,6 +122,9 @@ class <%= it.entityName %>Service:
115
122
  payload = data.model_dump(exclude_unset=True)
116
123
  <% if (it.scope) { %>
117
124
  payload = self._with_tenant(payload)
125
+ <% if (it.scope.nested.length) { %>
126
+ await check_parents(self.auth, self.db, <%~ JSON.stringify(it.entityName) %>, [payload])
127
+ <% } %>
118
128
  <% } %>
119
129
  <% if (it.references.length) { %>
120
130
  await self._check_references([payload])
@@ -132,6 +142,9 @@ class <%= it.entityName %>Service:
132
142
  payloads = [item.model_dump(exclude_unset=True) for item in data]
133
143
  <% if (it.scope) { %>
134
144
  payloads = [self._with_tenant(payload) for payload in payloads]
145
+ <% if (it.scope.nested.length) { %>
146
+ await check_parents(self.auth, self.db, <%~ JSON.stringify(it.entityName) %>, payloads)
147
+ <% } %>
135
148
  <% } %>
136
149
  <% if (it.references.length) { %>
137
150
  await self._check_references(payloads)
@@ -160,6 +173,9 @@ class <%= it.entityName %>Service:
160
173
  # A scoped row cannot move to another tenant.
161
174
  for field in self._scope_values("update"):
162
175
  update_data.pop(field, None)
176
+ <% if (it.scope.nested.length) { %>
177
+ await check_parents(self.auth, self.db, <%~ JSON.stringify(it.entityName) %>, [update_data])
178
+ <% } %>
163
179
  <% } %>
164
180
  <% if (it.references.length) { %>
165
181
  await self._check_references([update_data])
@@ -187,6 +203,9 @@ class <%= it.entityName %>Service:
187
203
  <% if (it.scope) { %>
188
204
  for field in self._scope_values("update"):
189
205
  replace_data.pop(field, None)
206
+ <% if (it.scope.nested.length) { %>
207
+ await check_parents(self.auth, self.db, <%~ JSON.stringify(it.entityName) %>, [replace_data])
208
+ <% } %>
190
209
  <% } %>
191
210
  <% if (it.references.length) { %>
192
211
  await self._check_references([replace_data])
@@ -2,11 +2,12 @@
2
2
 
3
3
  import { Controller, Body<% if (it.relationAccess) { %>, UseInterceptors<% } %> } from "@nestjs/common";
4
4
  import { Crud, <% if (it.crudAuth.length || it.crudAuthNested.length) { %>CrudAuth, <% } %>CrudController, Override, ParsedRequest, CrudRequest, ParsedBody, CreateManyDto } from '@apso/crud';
5
- import { ApiTags, ApiResponse, ApiOperation, ApiBody } from '@nestjs/swagger';
5
+ import { ApiTags, ApiResponse, ApiOperation, ApiBody, ApiExtraModels, ApiUnauthorizedResponse<% if (it.hasAuth) { %>, ApiForbiddenResponse<% } %> } from '@nestjs/swagger';
6
6
  <% if (it.mcp.length) { %>
7
7
  import { McpTool } from '@apso/mcp';
8
8
  <% } %>
9
- import {<%= it.entityName %>Create, <%= it.entityName %>Update} from './dtos/<%= it.entityName%>.dto'
9
+ // The row schema is named after the entity (<%= it.entityName %>), the name the responses reference.
10
+ import {<%= it.entityName %>Create, <%= it.entityName %>Update, <%= it.entityName %> as <%= it.entityName %>Row} from './dtos/<%= it.entityName%>.dto'
10
11
  // The entity, not the response DTO: the documented filter parameters (one per
11
12
  // column, which is also what an MCP list tool accepts) come from its columns.
12
13
  import { <%= it.entityName %> } from './<%= it.entityName %>.entity';
@@ -14,6 +15,9 @@ import {<%= it.svcName %>} from './<%= it.entityName %>.service';
14
15
  <% if (it.relationAccess) { %>
15
16
  import { RelationAccess, RelationRoot } from '../guards/relations.interceptor';
16
17
  <% } %>
18
+ <% if (Object.keys(it.roleDocs).length) { %>
19
+ import { DescribeRoles } from '../guards/permission.guard';
20
+ <% } %>
17
21
 
18
22
  <%
19
23
  // Postgres computes a generated column, so a value sent for one is dropped
@@ -45,6 +49,10 @@ const skipScope = (req: any) => {
45
49
  return roles.some((r) => BYPASS_ROLES.includes(r));
46
50
  };
47
51
  <% } %>
52
+ <% if (Object.keys(it.roleDocs).length) { %>
53
+ // Above @Crud, which writes its own operation text: adds each role rule to it.
54
+ @DescribeRoles(<%~ JSON.stringify(it.roleDocs, null, 4) %>)
55
+ <% } %>
48
56
  <% if (it.relationAccess) { %>
49
57
  // Above @Crud, so it runs after @Crud's interceptor has parsed the request.
50
58
  @UseInterceptors(RelationAccess)
@@ -123,6 +131,13 @@ const skipScope = (req: any) => {
123
131
  <% } %>
124
132
 
125
133
  @Controller('<%= it.pluralEntityName %>')
134
+ @ApiExtraModels(<%= it.entityName %>Row)
135
+ <% if (it.hasAuth) { %>
136
+ @ApiUnauthorizedResponse({ description: 'No valid sign-in token (Authorization: Bearer) or API key (x-api-key).' })
137
+ @ApiForbiddenResponse({ description: "The token's role does not allow this operation, or the record is outside the caller's tenant." })
138
+ <% } else { %>
139
+ @ApiUnauthorizedResponse({ description: 'No valid API key (x-api-key).' })
140
+ <% } %>
126
141
  @ApiTags('<%= it.pluralEntityName %>')
127
142
  export class <%= it.ctrlName %> implements CrudController<<%= it.entityName %>>{
128
143
  constructor(public service: <%= it.svcName %>) {}
@@ -1,6 +1,6 @@
1
1
  <%~ includeFile('./header.eta') %>
2
2
 
3
- import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
3
+ import { ApiHideProperty, ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
4
4
  import {
5
5
  IsString,
6
6
  IsNumber,
@@ -19,6 +19,10 @@ import { Type } from 'class-transformer';
19
19
  <% if (it.importEnums) { %>
20
20
  import * as enums from '../../enums';
21
21
  <% } %>
22
+ <% /* Enum values go in the OpenAPI document, as one named schema per enum. */ %>
23
+ <% const apiOpts = (f) => f.dataType.includes("Enum") ? `{ enum: enums.${f.dataType}, enumName: '${f.dataType}' }` : ''; %>
24
+ <% /* Postgres numeric reads back as a string ("12.50"), so the row schema says so. */ %>
25
+ <% const rowOpts = (f) => (f.type === 'numeric' || f.type === 'decimal') ? `{ type: String, format: 'decimal', description: 'A decimal, sent as a string ("12.50") to keep its precision.' }` : apiOpts(f); %>
22
26
 
23
27
  export class <%= it.entityName %>Create {
24
28
  <% if (it.addDefaultPKProperty && (it.primaryKeyType === 'uuid' || it.primaryKeyType === 'text')) { %>
@@ -29,11 +33,15 @@ export class <%= it.entityName %>Create {
29
33
 
30
34
  <% } -%>
31
35
  <% it.columns.filter((field) => !field.generated).forEach((field) => { -%>
32
- <% if (!field.required) { -%>
33
- @ApiPropertyOptional()
36
+ <% if (field.serverSet) { -%>
37
+ // Set by the server from the caller's tenant (scopeBy).
38
+ @ApiHideProperty()
39
+ @IsOptional()
40
+ <% } else if (!field.required) { -%>
41
+ @ApiPropertyOptional(<%~ apiOpts(field) %>)
34
42
  @IsOptional()
35
43
  <% } else { -%>
36
- @ApiProperty()
44
+ @ApiProperty(<%~ apiOpts(field) %>)
37
45
  @IsNotEmpty()
38
46
  <% } -%>
39
47
  <% if (field.dataType.includes("Enum")) { -%>
@@ -99,7 +107,11 @@ export class <%= it.entityName %>Create {
99
107
 
100
108
  export class <%= it.entityName %>Update {
101
109
  <% it.columns.filter((field) => !field.generated).forEach((field) => { -%>
102
- @ApiPropertyOptional()
110
+ <% if (field.serverSet) { -%>
111
+ @ApiHideProperty()
112
+ <% } else { -%>
113
+ @ApiPropertyOptional(<%~ apiOpts(field) %>)
114
+ <% } -%>
103
115
  @IsOptional()
104
116
  <% if (field.dataType.includes("Enum")) { -%>
105
117
  @IsEnum(enums.<%= field.dataType %>)
@@ -169,12 +181,12 @@ export class <%= it.entityName %> {
169
181
 
170
182
  <% } -%>
171
183
  <% it.columns.forEach((field) => { -%>
172
- <% if (!field.required) { -%>
173
- @ApiPropertyOptional()
184
+ <% if (field.nullable) { -%>
185
+ @ApiPropertyOptional(<%~ rowOpts(field) %>)
174
186
  <%= field.name %>?: <% if (field.dataType.includes("Enum")) { %>enums.<%= field.dataType %><% } else if (field.type === 'json' || field.type === 'json-plain') { %>Record<string, any><% } else if (field.type === 'timestamp' || field.type === 'timestamptz') { %>Date<% } else { %><%= field.dataType %><% } %>;
175
187
 
176
188
  <% } else { -%>
177
- @ApiProperty()
189
+ @ApiProperty(<%~ rowOpts(field) %>)
178
190
  <%= field.name %>: <% if (field.dataType.includes("Enum")) { %>enums.<%= field.dataType %><% } else if (field.type === 'json' || field.type === 'json-plain') { %>Record<string, any><% } else if (field.type === 'timestamp' || field.type === 'timestamptz') { %>Date<% } else { %><%= field.dataType %><% } %>;
179
191
 
180
192
  <% } -%>
@@ -20,4 +20,8 @@ GuardsModule,
20
20
  <% if (it.schemaExtras) { %>
21
21
  SchemaExtrasModule,
22
22
  <% } %>
23
- ]
23
+ ]
24
+
25
+ // The OpenAPI info.description: who signs callers in, how records are scoped
26
+ // and which operations need which role (from .apsorc).
27
+ export const apiDescription = <%~ JSON.stringify(it.apiDescription) %>;
@@ -1,3 +1,4 @@
1
+ import { Deferrable, OnDelete } from "./relationship";
1
2
  export interface Unique {
2
3
  fields: string[];
3
4
  name?: string;
@@ -25,7 +26,11 @@ export interface ExtraForeignKey {
25
26
  column: string;
26
27
  /** The entity it references, by its primary key. */
27
28
  to: string;
28
- onDelete?: "CASCADE" | "SET NULL" | "RESTRICT" | "NO ACTION";
29
+ onDelete?: OnDelete;
30
+ /** The key's ON UPDATE rule. Defaults to NO ACTION. */
31
+ onUpdate?: OnDelete;
32
+ /** Makes the key DEFERRABLE, checked as the value says. */
33
+ deferrable?: Deferrable;
29
34
  /** False keeps the key NOT VALID in migrations, as on a relationship. */
30
35
  validate?: boolean;
31
36
  }
@@ -1,6 +1,33 @@
1
1
  export type RelationshipType = "OneToMany" | "ManyToOne" | "ManyToMany" | "OneToOne";
2
2
  /** A foreign key's ON DELETE rule. "cascadeDelete": true is "CASCADE". */
3
- export type OnDelete = "CASCADE" | "SET NULL" | "RESTRICT" | "NO ACTION";
3
+ export type OnDelete = "CASCADE" | "SET NULL" | "SET DEFAULT" | "RESTRICT" | "NO ACTION";
4
+ /** When a DEFERRABLE foreign key is checked: per statement, or at commit. */
5
+ export type Deferrable = "INITIALLY IMMEDIATE" | "INITIALLY DEFERRED";
6
+ /** The rules of a foreign key beyond the column and the table it references. */
7
+ export interface KeyRules {
8
+ /** The key's ON UPDATE rule. Defaults to NO ACTION. */
9
+ onUpdate?: OnDelete;
10
+ /** Makes the key DEFERRABLE, checked as the value says. */
11
+ deferrable?: Deferrable;
12
+ /** false keeps the key NOT VALID. Only migrations can create it that way. */
13
+ validate?: boolean;
14
+ }
15
+ /**
16
+ * A foreign key's rules as SQL writes them after REFERENCES.
17
+ *
18
+ * @param {OnDelete | undefined} onDelete - The ON DELETE rule, if not the default.
19
+ * @param {KeyRules} k - The key's other rules.
20
+ * @returns {string} "ON DELETE ... ON UPDATE ..." and what follows.
21
+ */
22
+ export declare const keyRulesSql: (onDelete: OnDelete | undefined, k: KeyRules) => string;
23
+ /**
24
+ * A foreign key's rules as TypeORM options, without the braces.
25
+ *
26
+ * @param {OnDelete | undefined} onDelete - The ON DELETE rule, if not the default.
27
+ * @param {KeyRules} k - The key's other rules.
28
+ * @returns {string} For example `onDelete: "CASCADE", onUpdate: "CASCADE"`.
29
+ */
30
+ export declare const keyRuleOptions: (onDelete: OnDelete | undefined, k: KeyRules) => string;
4
31
  /**
5
32
  * The ON DELETE rule of a ManyToOne's foreign key, undefined for the
6
33
  * database default (NO ACTION).
@@ -21,6 +48,12 @@ export interface ApsorcRelationship {
21
48
  bi_directional?: boolean;
22
49
  cascadeDelete?: boolean;
23
50
  onDelete?: OnDelete;
51
+ /** The foreign key's ON UPDATE rule. Defaults to NO ACTION. */
52
+ onUpdate?: OnDelete;
53
+ /** Makes the foreign key DEFERRABLE, checked as the value says. */
54
+ deferrable?: Deferrable;
55
+ /** The foreign key column's DEFAULT, as a SQL expression. */
56
+ joinColumnDefault?: string;
24
57
  /** Name of the foreign key constraint; defaults to the name TypeORM derives. */
25
58
  foreignKeyName?: string;
26
59
  /** The foreign key column is (part of) the entity's primary key. */
@@ -44,6 +77,12 @@ export interface Relationship {
44
77
  biDirectional?: boolean;
45
78
  cascadeDelete?: boolean;
46
79
  onDelete?: OnDelete;
80
+ /** The foreign key's ON UPDATE rule. Defaults to NO ACTION. */
81
+ onUpdate?: OnDelete;
82
+ /** Makes the foreign key DEFERRABLE, checked as the value says. */
83
+ deferrable?: Deferrable;
84
+ /** The foreign key column's DEFAULT, as a SQL expression. */
85
+ joinColumnDefault?: string;
47
86
  /** Name of the foreign key constraint; defaults to the name TypeORM derives. */
48
87
  foreignKeyName?: string;
49
88
  /** The foreign key column is (part of) the entity's primary key. */
@@ -1,6 +1,39 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.onDeleteOf = void 0;
3
+ exports.onDeleteOf = exports.keyRuleOptions = exports.keyRulesSql = void 0;
4
+ /**
5
+ * A foreign key's rules as SQL writes them after REFERENCES.
6
+ *
7
+ * @param {OnDelete | undefined} onDelete - The ON DELETE rule, if not the default.
8
+ * @param {KeyRules} k - The key's other rules.
9
+ * @returns {string} "ON DELETE ... ON UPDATE ..." and what follows.
10
+ */
11
+ const keyRulesSql = (onDelete, k) => {
12
+ var _a;
13
+ return `ON DELETE ${onDelete !== null && onDelete !== void 0 ? onDelete : "NO ACTION"} ON UPDATE ${(_a = k.onUpdate) !== null && _a !== void 0 ? _a : "NO ACTION"}${k.deferrable ? ` DEFERRABLE ${k.deferrable}` : ""}${k.validate === false ? " NOT VALID" : ""}`;
14
+ };
15
+ exports.keyRulesSql = keyRulesSql;
16
+ /**
17
+ * A foreign key's rules as TypeORM options, without the braces.
18
+ *
19
+ * @param {OnDelete | undefined} onDelete - The ON DELETE rule, if not the default.
20
+ * @param {KeyRules} k - The key's other rules.
21
+ * @returns {string} For example `onDelete: "CASCADE", onUpdate: "CASCADE"`.
22
+ */
23
+ const keyRuleOptions = (onDelete, k) => {
24
+ // TypeORM types the rule "DEFAULT" and writes whatever it is given into
25
+ // the SQL, where Postgres needs "SET DEFAULT".
26
+ const rule = (r) => r === "SET DEFAULT" ? '"SET DEFAULT" as never' : JSON.stringify(r);
27
+ const onUpdate = k.onUpdate === "NO ACTION" ? undefined : k.onUpdate;
28
+ return [
29
+ onDelete && `onDelete: ${rule(onDelete)}`,
30
+ onUpdate && `onUpdate: ${rule(onUpdate)}`,
31
+ k.deferrable && `deferrable: ${JSON.stringify(k.deferrable)}`,
32
+ ]
33
+ .filter(Boolean)
34
+ .join(", ");
35
+ };
36
+ exports.keyRuleOptions = keyRuleOptions;
4
37
  /**
5
38
  * The ON DELETE rule of a ManyToOne's foreign key, undefined for the
6
39
  * database default (NO ACTION).
@@ -267,6 +267,13 @@ isOwner // Is the 'from' side the owner?
267
267
  * @returns A RelationshipMap, potentially containing entries for both entities involved in the relationship.
268
268
  */
269
269
  const parseRelationship = (relationship, allRelationships) => {
270
+ // These describe the one foreign key of a ManyToOne, or of the OneToMany
271
+ // that mirrors it. Anywhere else they would be dropped without a word.
272
+ if (relationship.type !== "ManyToOne" && relationship.type !== "OneToMany") {
273
+ const set = ["onUpdate", "deferrable", "joinColumnDefault"].find((key) => relationship[key] !== undefined);
274
+ if (set)
275
+ throw new Error(`${relationship.from} ${relationship.type} ${relationship.to} sets "${set}", which only a ManyToOne or OneToMany takes.`);
276
+ }
270
277
  if (relationship.type === "ManyToMany") {
271
278
  return (0, exports.parseManyToMany)(relationship, allRelationships);
272
279
  }
@@ -299,6 +306,9 @@ const parseRelationship = (relationship, allRelationships) => {
299
306
  foreignKeyName: relationship.foreignKeyName,
300
307
  primary: relationship.primary,
301
308
  validate: relationship.validate,
309
+ onUpdate: relationship.onUpdate,
310
+ deferrable: relationship.deferrable,
311
+ joinColumnDefault: relationship.joinColumnDefault,
302
312
  },
303
313
  ],
304
314
  };
@@ -321,11 +331,15 @@ const parseRelationship = (relationship, allRelationships) => {
321
331
  referenceName: manySideRefName,
322
332
  nullable: relationship.nullable || false,
323
333
  index: relationship.index || false,
334
+ cascadeDelete: relationship.cascadeDelete,
324
335
  joinColumnName: relationship.joinColumnName,
325
336
  onDelete: relationship.onDelete,
326
337
  foreignKeyName: relationship.foreignKeyName,
327
338
  primary: relationship.primary,
328
339
  validate: relationship.validate,
340
+ onUpdate: relationship.onUpdate,
341
+ deferrable: relationship.deferrable,
342
+ joinColumnDefault: relationship.joinColumnDefault,
329
343
  },
330
344
  ],
331
345
  };
@@ -346,6 +360,9 @@ const parseRelationship = (relationship, allRelationships) => {
346
360
  foreignKeyName: relationship.foreignKeyName,
347
361
  primary: relationship.primary,
348
362
  validate: relationship.validate,
363
+ onUpdate: relationship.onUpdate,
364
+ deferrable: relationship.deferrable,
365
+ joinColumnDefault: relationship.joinColumnDefault,
349
366
  },
350
367
  ],
351
368
  [relationship.to]: [
@@ -697,6 +714,14 @@ const joinColumnErrors = (relationshipMap, language) => Object.entries(relations
697
714
  ]
698
715
  : []),
699
716
  ...keyAndNameErrors(entity, r, language),
717
+ ...(r.onUpdate ||
718
+ r.deferrable ||
719
+ r.joinColumnDefault ||
720
+ r.onDelete === "SET DEFAULT"
721
+ ? [
722
+ `${entity} ${r.type} ${r.name} sets "onUpdate", "deferrable", "joinColumnDefault" or "SET DEFAULT". The ${language} generator cannot keep those foreign key settings yet; remove them or generate a TypeScript service.`,
723
+ ]
724
+ : []),
700
725
  ]));
701
726
  exports.joinColumnErrors = joinColumnErrors;
702
727
  const keyAndNameErrors = (entity, r, language) => ["joinColumnName", "foreignKeyName", "primary"]
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@apso/cli",
3
- "version": "0.55.0",
3
+ "version": "0.57.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@apso/cli",
9
- "version": "0.55.0",
9
+ "version": "0.57.0",
10
10
  "license": "Apache-2.0",
11
11
  "dependencies": {
12
12
  "@apso/schema-tools": "^0.2.3",
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.55.0",
2
+ "version": "0.57.0",
3
3
  "commands": {
4
4
  "config": {
5
5
  "id": "config",
@@ -843,7 +843,7 @@
843
843
  },
844
844
  "import:data": {
845
845
  "id": "import:data",
846
- "description": "Copy table data from a source Supabase (Postgres) database into the target database rebuilt from the imported schema. Reads the source read-only; inserts into empty target tables.",
846
+ "description": "Copy table data from a source Postgres database (Supabase, Neon, RDS, or any other) into the target database rebuilt from the imported schema. Reads the source read-only; inserts into empty target tables.",
847
847
  "strict": true,
848
848
  "pluginName": "@apso/cli",
849
849
  "pluginAlias": "@apso/cli",
@@ -906,54 +906,63 @@
906
906
  },
907
907
  "args": {}
908
908
  },
909
- "import:supabase": {
910
- "id": "import:supabase",
911
- "description": "Introspect an existing Supabase (Postgres) database and generate a local .apsorc schema. Read-only: it never writes to the source database.",
909
+ "import": {
910
+ "id": "import",
911
+ "description": "Introspect an existing Postgres database (Supabase, Neon, RDS, or any Postgres you can reach with a connection string) and generate a local .apsorc schema. Runs on your machine and is read-only: it never writes to the source database.",
912
912
  "strict": true,
913
913
  "pluginName": "@apso/cli",
914
914
  "pluginAlias": "@apso/cli",
915
915
  "pluginType": "core",
916
- "aliases": [],
916
+ "aliases": [
917
+ "import:supabase"
918
+ ],
917
919
  "hiddenAliases": [],
918
920
  "examples": [
919
- "$ apso import supabase",
920
- "$ apso import supabase -c \"postgresql://postgres:[pw]@db.[ref].supabase.co:5432/postgres\"",
921
- "$ SUPABASE_DB_URL=\"postgresql://...\" apso import supabase --dry-run"
921
+ "$ apso import",
922
+ "$ apso import -c \"postgresql://user:[pw]@host:5432/dbname\"",
923
+ "$ apso import -c \"postgresql://postgres:[pw]@db.[ref].supabase.co:5432/postgres\"",
924
+ "$ DATABASE_URL=\"postgresql://...\" apso import --dry-run"
922
925
  ],
926
+ "deprecateAliases": true,
923
927
  "flags": {
924
928
  "connection-string": {
925
929
  "name": "connection-string",
926
930
  "type": "option",
927
931
  "char": "c",
928
932
  "description": "Postgres connection string. Falls back to SUPABASE_DB_URL or DATABASE_URL, then prompts.",
929
- "multiple": false
933
+ "multiple": false,
934
+ "deprecateAliases": true
930
935
  },
931
936
  "schema": {
932
937
  "name": "schema",
933
938
  "type": "option",
934
939
  "description": "Database schema to import",
935
940
  "multiple": false,
936
- "default": "public"
941
+ "default": "public",
942
+ "deprecateAliases": true
937
943
  },
938
944
  "out": {
939
945
  "name": "out",
940
946
  "type": "option",
941
947
  "char": "o",
942
948
  "description": "Path to write the .apsorc (default: existing .apsorc or ./.apsorc)",
943
- "multiple": false
949
+ "multiple": false,
950
+ "deprecateAliases": true
944
951
  },
945
952
  "dry-run": {
946
953
  "name": "dry-run",
947
954
  "type": "boolean",
948
955
  "description": "Introspect and print a summary without writing any file",
949
- "allowNo": false
956
+ "allowNo": false,
957
+ "deprecateAliases": true
950
958
  },
951
959
  "yes": {
952
960
  "name": "yes",
953
961
  "type": "boolean",
954
962
  "char": "y",
955
963
  "description": "Skip the overwrite confirmation prompt",
956
- "allowNo": false
964
+ "allowNo": false,
965
+ "deprecateAliases": true
957
966
  }
958
967
  },
959
968
  "args": {}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@apso/cli",
3
- "version": "0.55.0",
3
+ "version": "0.57.0",
4
4
  "mcpName": "io.github.apsoai/apso",
5
5
  "description": "Apso CLI",
6
6
  "author": "Apso by Mavric - @mavric",