@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
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.GoGenerator = void 0;
3
+ exports.GoGenerator = exports.goNestedScopes = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const path = tslib_1.__importStar(require("path"));
6
6
  const Eta = tslib_1.__importStar(require("eta"));
@@ -84,6 +84,22 @@ const jsonType = (goType) => {
84
84
  return { type: "array" };
85
85
  return {};
86
86
  };
87
+ /**
88
+ * A scopeBy path through parents as SQL names: the entity's foreign key column,
89
+ * each parent's table with its foreign key column to the next, and the tenant
90
+ * column on the last parent. Columns are the .apsorc names, as the DDL writer
91
+ * names them.
92
+ */
93
+ function goNestedScopes(nested, entities) {
94
+ const table = (name) => (0, ddl_1.tableName)(entities.find((e) => e.name === name));
95
+ return nested.map((n) => ({
96
+ column: n.field,
97
+ parents: n.parents.map((p) => { var _a; return ({ table: table(p.entity), column: (_a = p.field) !== null && _a !== void 0 ? _a : "" }); }),
98
+ tenantColumn: n.tenantField,
99
+ source: n.source,
100
+ }));
101
+ }
102
+ exports.goNestedScopes = goNestedScopes;
87
103
  /**
88
104
  * Go/Gin generator that produces GORM models, DTOs, Gin handlers,
89
105
  * and service layer code.
@@ -162,7 +178,7 @@ class GoGenerator extends base_1.BaseGenerator {
162
178
  "array",
163
179
  ];
164
180
  if (field.type && !supportedTypes.includes(field.type)) {
165
- warnings.push(`Entity '${entity.name}' field '${field.name}' has type '${field.type}' which may not be fully supported`);
181
+ errors.push(`Entity '${entity.name}' field '${field.name}': the Go generator does not support field type "${field.type}"; use one of ${supportedTypes.join(", ")} or generate a TypeScript service.`);
166
182
  }
167
183
  }
168
184
  }
@@ -323,6 +339,7 @@ class GoGenerator extends base_1.BaseGenerator {
323
339
  ];
324
340
  }
325
341
  async generateController(options) {
342
+ var _a;
326
343
  const { entity, relationships } = options;
327
344
  const { name: entityName } = entity;
328
345
  const relationshipsForTemplate = (0, relationships_1.getRelationshipForTemplate)(entityName, relationships);
@@ -336,7 +353,7 @@ class GoGenerator extends base_1.BaseGenerator {
336
353
  primaryKeyGoType: this.getPrimaryKeyGoType(primaryKeyType),
337
354
  primaryKeySwaggerType: this.getPrimaryKeySwaggerType(primaryKeyType),
338
355
  associations: [...new Set(relationshipsForTemplate)],
339
- scope: (0, guards_1.entityScope)(entity, Boolean(options.auth)),
356
+ scope: (0, guards_1.entityScope)(entity, Boolean(options.auth), (_a = this.config.relationshipMap) !== null && _a !== void 0 ? _a : {}),
340
357
  // A write that names a row the caller cannot read is answered like a scope error.
341
358
  references: this.goReferences(entity, this.goAssociations(entity, relationships, options.allEntities), options.allEntities, options.auth).length > 0,
342
359
  };
@@ -370,7 +387,7 @@ class GoGenerator extends base_1.BaseGenerator {
370
387
  ...r,
371
388
  hidden: (0, guards_1.hidesRelation)(entityName, r.name, allEntities, options.auth),
372
389
  })),
373
- scope: this.goScope(entity, Boolean(options.auth)),
390
+ scope: this.goScope(entity, Boolean(options.auth), allEntities),
374
391
  references: this.goReferences(entity, goRelationships, allEntities, options.auth),
375
392
  };
376
393
  const content = await this.renderTemplate("./services/service", data);
@@ -598,21 +615,24 @@ ${modelRefs}
598
615
  * Scope data for a Go service: each direct scopeBy field's struct field and
599
616
  * column (the .apsorc name, as the DDL writer names it). A field declared on the entity is
600
617
  * pascalCase; a relation's foreign key (organizationId) is OrganizationID.
618
+ * A path through a parent (task.workspaceId) carries the foreign key the
619
+ * service reads from a write, to check the parent is the caller's.
601
620
  */
602
- goScope(entity, hasAuth) {
603
- var _a;
604
- const scope = (0, guards_1.entityScope)(entity, hasAuth);
621
+ goScope(entity, hasAuth, allEntities) {
622
+ var _a, _b;
623
+ const scope = (0, guards_1.entityScope)(entity, hasAuth, (_a = this.config.relationshipMap) !== null && _a !== void 0 ? _a : {});
605
624
  if (!scope)
606
625
  return;
607
- const declared = new Set(((_a = entity.fields) !== null && _a !== void 0 ? _a : []).map((f) => f.name));
626
+ const declared = new Set(((_b = entity.fields) !== null && _b !== void 0 ? _b : []).map((f) => f.name));
627
+ const goField = (field) => declared.has(field) || !field.endsWith("Id")
628
+ ? (0, casing_1.pascalCase)(field)
629
+ : `${(0, casing_1.pascalCase)(field.slice(0, -2))}ID`;
608
630
  return {
609
631
  ...scope,
610
- fields: scope.fields.map((f) => ({
611
- ...f,
612
- goField: declared.has(f.field) || !f.field.endsWith("Id")
613
- ? (0, casing_1.pascalCase)(f.field)
614
- : `${(0, casing_1.pascalCase)(f.field.slice(0, -2))}ID`,
615
- column: f.field,
632
+ fields: scope.fields.map((f) => ({ ...f, goField: goField(f.field), column: f.field })),
633
+ nested: goNestedScopes(scope.nested, allEntities).map((n) => ({
634
+ ...n,
635
+ goField: goField(n.column),
616
636
  })),
617
637
  };
618
638
  }
@@ -683,9 +703,6 @@ ${modelRefs}
683
703
  const permissions = (0, guards_1.getPermissionConfig)(entities, relationshipMap, auth);
684
704
  if (permissions && !auth)
685
705
  throw new Error("permissions in .apsorc need an auth block: roles come from the signed-in caller");
686
- const nested = auth ? (0, guards_1.nestedScopeEntities)(entities) : [];
687
- if (nested.length > 0)
688
- throw new Error(`${nested.join(", ")}: a scopeBy path through a parent (for example "project.organizationId") is enforced in TypeScript services only for now. In Go, put the tenant field on the entity and scope by it, or generate with --language typescript.`);
689
706
  // The API key check is part of every service; auth adds user sign-in.
690
707
  // One entry per trusted issuer; undefined when there is no sign-in.
691
708
  const jwt = (0, types_1.resolveJwtProviders)(auth);
@@ -696,6 +713,11 @@ ${modelRefs}
696
713
  authRoutes: (0, guards_1.authEntityNames)(entities, auth).map((name) => (0, casing_1.kebabCase)((0, pluralize_1.default)(name))),
697
714
  relationScopes: (_b = (0, guards_1.relationScopes)(entities, relationshipMap, Boolean(auth))) !== null && _b !== void 0 ? _b : {},
698
715
  tables: Object.fromEntries(entities.map((e) => [e.name, (0, ddl_1.tableName)(e)])),
716
+ // Each entity's scopeBy paths through a parent, as tables and columns.
717
+ nestedScopes: Object.fromEntries(entities.map((e) => [
718
+ e.name,
719
+ auth ? goNestedScopes((0, guards_1.nestedScopes)(e, relationshipMap), entities) : [],
720
+ ])),
699
721
  };
700
722
  const content = await this.renderTemplate("./middleware/auth", data);
701
723
  const files = [{ path: "middleware/auth.go", content }];
@@ -736,7 +758,7 @@ ${modelRefs}
736
758
  }),
737
759
  });
738
760
  // Shared helpers for services and handlers of entities with a direct scopeBy.
739
- if (auth && entities.some((e) => (0, guards_1.entityScope)(e, true))) {
761
+ if (auth && entities.some((e) => (0, guards_1.entityScope)(e, true, relationshipMap))) {
740
762
  files.push({
741
763
  path: "services/scope.go",
742
764
  content: await this.renderTemplate("./services/scope", {}),
@@ -204,7 +204,7 @@ class PythonGenerator extends base_1.BaseGenerator {
204
204
  "array",
205
205
  ];
206
206
  if (field.type && !supportedTypes.includes(field.type)) {
207
- warnings.push(`Entity '${entity.name}' field '${field.name}' has type '${field.type}' which may not be fully supported`);
207
+ errors.push(`Entity '${entity.name}' field '${field.name}': the Python generator does not support field type "${field.type}"; use one of ${supportedTypes.join(", ")} or generate a TypeScript service.`);
208
208
  }
209
209
  }
210
210
  }
@@ -325,7 +325,7 @@ class PythonGenerator extends base_1.BaseGenerator {
325
325
  ];
326
326
  }
327
327
  async generateService(options) {
328
- var _a;
328
+ var _a, _b, _c;
329
329
  const { entity, relationships } = options;
330
330
  const { name: entityName } = entity;
331
331
  const relationshipsForTemplate = (0, relationships_1.getRelationshipForTemplate)(entityName, relationships);
@@ -336,11 +336,11 @@ class PythonGenerator extends base_1.BaseGenerator {
336
336
  pluralEntityName,
337
337
  primaryKeyType,
338
338
  associations: [...new Set(relationshipsForTemplate)],
339
- scope: (0, guards_1.entityScope)(entity, Boolean(options.auth)),
339
+ scope: (0, guards_1.entityScope)(entity, Boolean(options.auth), (_b = (_a = options.relationshipMap) !== null && _a !== void 0 ? _a : this.config.relationshipMap) !== null && _b !== void 0 ? _b : {}),
340
340
  // Foreign keys a write must check: those onto tenant-scoped entities.
341
341
  references: Object.entries((0, guards_1.scopedReferences)(entity, relationshipsForTemplate
342
342
  .filter((a) => a.type === "ManyToOne" || (a.type === "OneToOne" && a.joinTable))
343
- .map((a) => [a.camelCasedId, a.name]), (0, guards_1.relationScopes)(options.allEntities, (_a = options.relationshipMap) !== null && _a !== void 0 ? _a : this.config.relationshipMap, Boolean(options.auth)))).map(([field, target]) => ({ field, target })),
343
+ .map((a) => [a.camelCasedId, a.name]), (0, guards_1.relationScopes)(options.allEntities, (_c = options.relationshipMap) !== null && _c !== void 0 ? _c : this.config.relationshipMap, Boolean(options.auth)))).map(([field, target]) => ({ field, target })),
344
344
  };
345
345
  const content = await this.renderTemplate("./services/service", data);
346
346
  return [
@@ -575,9 +575,6 @@ ${downStatements || " pass"}
575
575
  const permissions = (0, guards_1.getPermissionConfig)(entities, relationshipMap, auth);
576
576
  if (permissions && !auth)
577
577
  throw new Error("permissions in .apsorc need an auth block: roles come from the signed-in caller");
578
- const nested = auth ? (0, guards_1.nestedScopeEntities)(entities) : [];
579
- if (nested.length > 0)
580
- throw new Error(`${nested.join(", ")}: a scopeBy path through a parent (for example "project.organizationId") is enforced in TypeScript services only for now. In Python, put the tenant field on the entity and scope by it, or generate with --language typescript.`);
581
578
  // The API key check is part of every service; auth adds user sign-in.
582
579
  // One entry per trusted issuer; undefined when there is no sign-in.
583
580
  const jwt = (0, types_1.resolveJwtProviders)(auth);
@@ -587,6 +584,8 @@ ${downStatements || " pass"}
587
584
  // Routes only a service caller reaches (sessions, accounts, ...).
588
585
  authRoutes: (0, guards_1.authEntityRoutes)(entities, auth),
589
586
  relationScopes: (_b = (0, guards_1.relationScopes)(entities, relationshipMap, Boolean(auth))) !== null && _b !== void 0 ? _b : {},
587
+ // Each entity's scopeBy paths through a parent, resolved to foreign keys.
588
+ nestedScopes: Object.fromEntries(entities.map((e) => [e.name, auth ? (0, guards_1.nestedScopes)(e, relationshipMap) : []])),
590
589
  };
591
590
  const files = [
592
591
  { path: "auth.py", content: await this.renderTemplate("./auth", data) },
@@ -132,7 +132,22 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
132
132
  ...c,
133
133
  fields: c.fields.map((f) => { var _a, _b; return fieldNames.has(f) ? f : (_b = (_a = oneToOneColumns.get(f)) !== null && _a !== void 0 ? _a : joinColumns.get(f)) !== null && _b !== void 0 ? _b : f; }),
134
134
  }));
135
- const foreignKeys = (0, ddl_1.extraForeignKeys)(entity, new Map(allEntities.map((e) => [e.name, e])));
135
+ const schema = {
136
+ entities: allEntities,
137
+ relationshipMap: {
138
+ ...this.config.relationshipMap,
139
+ [name]: relationships,
140
+ },
141
+ };
142
+ const foreignKeys = (0, ddl_1.extraForeignKeys)(entity, schema).map((k) => ({
143
+ ...k,
144
+ options: [
145
+ `name: ${JSON.stringify(k.name)}`,
146
+ (0, relationship_1.keyRuleOptions)(k.onDelete, k),
147
+ ]
148
+ .filter(Boolean)
149
+ .join(", "),
150
+ }));
136
151
  const data = {
137
152
  name,
138
153
  foreignKeys,
@@ -160,11 +175,15 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
160
175
  : c),
161
176
  associations: [...new Set(relationshipsForTemplate)].map((r) => {
162
177
  // A foreign key column copies the type of the key it references.
163
- const key = (0, ddl_1.keyColumn)(allEntities.find((e) => e.name === r.name));
178
+ const key = (0, ddl_1.keyColumn)(allEntities.find((e) => e.name === r.name), schema);
164
179
  return {
165
180
  ...r,
166
- onDeleteRule: (0, relationship_1.onDeleteOf)(r),
167
- fkColumnOptions: key.options,
181
+ keyRules: (0, relationship_1.keyRuleOptions)((0, relationship_1.onDeleteOf)(r), r),
182
+ // The entity spells a default the way TypeORM reads it back.
183
+ fkColumnOptions: key.options +
184
+ (r.joinColumnDefault
185
+ ? `, default: () => ${JSON.stringify((0, field_1.typeormDefault)(r.joinColumnDefault))}`
186
+ : ""),
168
187
  fkTsType: key.ts,
169
188
  };
170
189
  }),
@@ -186,7 +205,7 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
186
205
  ];
187
206
  }
188
207
  async generateController(options) {
189
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
208
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
190
209
  const { entity, relationships, relationshipMap, auth } = options;
191
210
  const { name: entityName } = entity;
192
211
  // Auth entities are for service callers only, so no other entity's
@@ -232,13 +251,27 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
232
251
  .filter((r) => r.primary)
233
252
  .map((r) => r.camelCasedId),
234
253
  ];
254
+ // Each role-gated handler's rule, added to its OpenAPI description.
255
+ const handlers = {
256
+ read: ["getMany", "get"],
257
+ create: ["create", "createMany"],
258
+ update: ["update", "replace", "recoverOneBase"],
259
+ delete: ["delete"],
260
+ };
261
+ const roleDocs = {};
262
+ if (auth)
263
+ for (const [op, rule] of Object.entries((0, guards_1.entityRoleRules)(entity)))
264
+ for (const handler of (_c = handlers[op]) !== null && _c !== void 0 ? _c : [])
265
+ roleDocs[handler] = (0, guards_1.roleRuleText)(rule, auth);
235
266
  const data = {
267
+ hasAuth: Boolean(auth),
268
+ roleDocs,
236
269
  svcName,
237
270
  ctrlName,
238
271
  entityName,
239
272
  pluralEntityName,
240
273
  primaryKeyType,
241
- generatedFields: ((_c = entity.fields) !== null && _c !== void 0 ? _c : [])
274
+ generatedFields: ((_d = entity.fields) !== null && _d !== void 0 ? _d : [])
242
275
  .filter((f) => f.generated)
243
276
  .map((f) => f.name),
244
277
  keyField: keyFields.length === 1 ? keyFields[0] : "id",
@@ -257,10 +290,10 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
257
290
  mcp,
258
291
  mcpName: (0, casing_1.snakeCase)(entityName),
259
292
  mcpPluralName: (0, casing_1.snakeCase)(pluralEntityName),
260
- dialects: (_e = (_d = options.query) === null || _d === void 0 ? void 0 : _d.dialects) !== null && _e !== void 0 ? _e : ["postgrest"],
261
- dialectList: ((_g = (_f = options.query) === null || _f === void 0 ? void 0 : _f.dialects) !== null && _g !== void 0 ? _g : ["postgrest"]).map((d) => `'${d}'`).join(", "),
262
- limit: (_j = (_h = options.query) === null || _h === void 0 ? void 0 : _h.limit) !== null && _j !== void 0 ? _j : 25,
263
- alwaysPaginate: (_l = (_k = options.query) === null || _k === void 0 ? void 0 : _k.alwaysPaginate) !== null && _l !== void 0 ? _l : false,
293
+ dialects: (_f = (_e = options.query) === null || _e === void 0 ? void 0 : _e.dialects) !== null && _f !== void 0 ? _f : ["postgrest"],
294
+ dialectList: ((_h = (_g = options.query) === null || _g === void 0 ? void 0 : _g.dialects) !== null && _h !== void 0 ? _h : ["postgrest"]).map((d) => `'${d}'`).join(", "),
295
+ limit: (_k = (_j = options.query) === null || _j === void 0 ? void 0 : _j.limit) !== null && _k !== void 0 ? _k : 25,
296
+ alwaysPaginate: (_m = (_l = options.query) === null || _l === void 0 ? void 0 : _l.alwaysPaginate) !== null && _m !== void 0 ? _m : false,
264
297
  };
265
298
  const controllerContent = await this.renderTemplate("./rest/controller-rest", data);
266
299
  const specContent = await this.renderTemplate("./rest/controller-rest-spec", data);
@@ -327,16 +360,21 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
327
360
  ];
328
361
  }
329
362
  async generateDto(options) {
330
- const { entity, relationships, allEntities, apiType } = options;
363
+ var _a, _b;
364
+ const { entity, relationships, allEntities, apiType, auth } = options;
331
365
  const { name: entityName, fields = [] } = entity;
332
366
  const columns = (0, field_1.getFieldForTemplate)(fields, entityName);
333
367
  const relationshipsTemplate = (0, relationships_1.getRelationshipForTemplate)(entityName, relationships);
334
368
  // Add foreign key columns for ManyToOne relationships
335
369
  relationshipsTemplate.forEach((rel) => {
370
+ var _a;
336
371
  if (rel.type === "ManyToOne") {
337
372
  const fkName = (0, casing_1.camelCase)(rel.referenceName || rel.name) + "Id";
338
373
  const referencedEntity = allEntities === null || allEntities === void 0 ? void 0 : allEntities.find((e) => e.name === rel.name);
339
- const fkDataType = (0, ddl_1.keyColumn)(referencedEntity).ts;
374
+ const fkDataType = (0, ddl_1.keyColumn)(referencedEntity, {
375
+ entities: allEntities !== null && allEntities !== void 0 ? allEntities : [],
376
+ relationshipMap: (_a = this.config.relationshipMap) !== null && _a !== void 0 ? _a : {},
377
+ }).ts;
340
378
  const fkType = fkDataType === "string" ? "text" : "integer";
341
379
  if (!columns.some((col) => col.name === fkName)) {
342
380
  columns.push({
@@ -344,6 +382,7 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
344
382
  dataType: fkDataType,
345
383
  type: fkType,
346
384
  ...(rel.primary && { primary: true }),
385
+ nullable: rel.nullable,
347
386
  });
348
387
  }
349
388
  }
@@ -353,7 +392,25 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
353
392
  const createdAt = entity.created_at;
354
393
  const updatedAt = entity.updated_at;
355
394
  const primaryKeyType = entity.primaryKeyType || "serial";
356
- const dtoColumns = columns.filter((col) => !["id", "createdAt", "updatedAt"].includes(col.name));
395
+ // With sign-in configured, @CrudAuth sets the scopeBy field from the
396
+ // caller's tenant on every write, so the request schemas leave it out.
397
+ const scopeFields = auth
398
+ ? ((_b = (_a = (0, guards_1.getScopedEntities)([entity])[0]) === null || _a === void 0 ? void 0 : _a.scopes) !== null && _b !== void 0 ? _b : [])
399
+ .filter((s) => s.direct)
400
+ .map((s) => s.field)
401
+ : [];
402
+ const dtoColumns = columns
403
+ .filter((col) => !["id", "createdAt", "updatedAt"].includes(col.name))
404
+ .map((col) => ({
405
+ ...col,
406
+ // A create must send it: NOT NULL with no default the database fills in.
407
+ required: !col.nullable &&
408
+ !col.auto &&
409
+ !col.primary &&
410
+ (col.default === null || col.default === undefined) &&
411
+ !scopeFields.includes(col.name),
412
+ serverSet: scopeFields.includes(col.name),
413
+ }));
357
414
  const createDtoName = `Create${(0, casing_1.pascalCase)(entityName)}Dto`;
358
415
  const updateDtoName = `Update${(0, casing_1.pascalCase)(entityName)}Dto`;
359
416
  const data = {
@@ -439,7 +496,12 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
439
496
  // "sqlIndexes" are created by a generated module, after TypeORM's sync.
440
497
  const statements = entities.flatMap((e) => (0, ddl_1.sqlIndexStatements)(e));
441
498
  const schemaExtras = apiType === "rest" && statements.length > 0;
442
- const content = await this.renderTemplate(`./${apiType}/index-module-${apiType}`, { entities, schemaExtras, guards: (opts === null || opts === void 0 ? void 0 : opts.guards) !== false });
499
+ const content = await this.renderTemplate(`./${apiType}/index-module-${apiType}`, {
500
+ entities,
501
+ schemaExtras,
502
+ guards: (opts === null || opts === void 0 ? void 0 : opts.guards) !== false,
503
+ apiDescription: (0, guards_1.accessSummary)(entities, opts === null || opts === void 0 ? void 0 : opts.auth),
504
+ });
443
505
  return [
444
506
  {
445
507
  path: "index.ts",
@@ -108,18 +108,46 @@ export interface DirectScopeField {
108
108
  /** userId and email map to the caller's own; anything else is the tenant. */
109
109
  source: "userId" | "email" | "tenant";
110
110
  }
111
+ /**
112
+ * One scopeBy path through parents (task.project.organizationId), resolved to
113
+ * the foreign keys it follows, for services that filter in SQL (Go, Python).
114
+ */
115
+ export interface NestedScopeData {
116
+ /** The entity's foreign key to the first parent, as .apsorc names it (taskId). */
117
+ field: string;
118
+ /**
119
+ * Each parent on the way to the tenant, nearest first: the entity, and its
120
+ * foreign key to the next parent (none on the last).
121
+ */
122
+ parents: {
123
+ entity: string;
124
+ field?: string;
125
+ }[];
126
+ /** The field on the last parent that holds the tenant. */
127
+ tenantField: string;
128
+ /** userId and email map to the caller's own; anything else is the tenant. */
129
+ source: "userId" | "email" | "tenant";
130
+ }
111
131
  /** What Go and Python services need to scope one entity. */
112
132
  export interface EntityScopeData {
113
133
  fields: DirectScopeField[];
134
+ /** Paths through a parent; empty unless the relationship map was given. */
135
+ nested: NestedScopeData[];
114
136
  bypassRoles: string[];
115
137
  }
138
+ /**
139
+ * The scopeBy paths of an entity that run through parents, each resolved hop
140
+ * by hop. Every step before the last must be a many-to-one relationship: its
141
+ * foreign key is what the SQL filter follows.
142
+ */
143
+ export declare function nestedScopes(entity: Entity, relationshipMap: RelationshipMap): NestedScopeData[];
116
144
  /**
117
145
  * The direct scopeBy fields of an entity, for services that filter in their
118
146
  * own queries (Go, Python). Undefined without auth: with no caller identity
119
- * there is no tenant to scope by. Nested paths (task.workspaceId) are not
120
- * included; see hasNestedScopes.
147
+ * there is no tenant to scope by. Paths through a parent (task.workspaceId)
148
+ * are resolved only when the relationship map is given.
121
149
  */
122
- export declare function entityScope(entity: Entity, hasAuth: boolean): EntityScopeData | undefined;
150
+ export declare function entityScope(entity: Entity, hasAuth: boolean, relationshipMap?: RelationshipMap): EntityScopeData | undefined;
123
151
  /** One entity in the relation table every generated service checks. */
124
152
  export interface RelationScope {
125
153
  /** Set when the entity's reads are tenant-scoped: the roles that skip its scope. */
@@ -154,8 +182,6 @@ export interface RelationScope {
154
182
  * Undefined without auth or when no entity is scoped.
155
183
  */
156
184
  export declare function relationScopes(entities: Entity[], relationshipMap: RelationshipMap | undefined, hasAuth: boolean): Record<string, RelationScope> | undefined;
157
- /** Entities whose scopeBy uses a nested path, which Go and Python cannot enforce. */
158
- export declare function nestedScopeEntities(entities: Entity[]): string[];
159
185
  /**
160
186
  * One warning per provider that maps no tenant claim while entities are
161
187
  * tenant-scoped: its users would get 403 on every one of those entities.
@@ -169,3 +195,15 @@ export declare function tenantClaimWarnings(entities: Entity[], auth?: AuthConfi
169
195
  * the caller.
170
196
  */
171
197
  export declare function scopedReferences(entity: Entity, foreignKeys: [field: string, target: string][], scopes: Record<string, RelationScope> | undefined): Record<string, string>;
198
+ /**
199
+ * One operation's role rule as a sentence, for its OpenAPI description:
200
+ * "Requires role: manager (from the token's `o.rol` claim). Other callers get 403."
201
+ */
202
+ export declare function roleRuleText(rule: PermissionRule, auth?: AuthConfig): string;
203
+ /** Each guarded operation of an entity and its rule, from .apsorc permissions. */
204
+ export declare function entityRoleRules(entity: Entity): Partial<Record<PermissionOperation, PermissionRule>>;
205
+ /**
206
+ * The OpenAPI info.description: who signs callers in, how records are scoped
207
+ * and which operations need which role, in plain words.
208
+ */
209
+ export declare function accessSummary(entities: Entity[], auth?: AuthConfig): string;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.scopedReferences = exports.tenantClaimWarnings = exports.nestedScopeEntities = exports.relationScopes = exports.entityScope = exports.getPermissionConfig = exports.hasPermissions = exports.mcpToolNames = exports.authEntityRoutes = exports.hidesRelation = exports.authEntityNames = exports.mcpOperations = exports.hasScopedEntities = exports.getScopedEntities = exports.toRouteName = exports.removedScopeOptionErrors = void 0;
3
+ exports.accessSummary = exports.entityRoleRules = exports.roleRuleText = exports.scopedReferences = exports.tenantClaimWarnings = exports.relationScopes = exports.entityScope = exports.nestedScopes = exports.getPermissionConfig = exports.hasPermissions = exports.mcpToolNames = exports.authEntityRoutes = exports.hidesRelation = exports.authEntityNames = exports.mcpOperations = exports.hasScopedEntities = exports.getScopedEntities = exports.toRouteName = exports.removedScopeOptionErrors = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const types_1 = require("./types");
6
6
  const pluralize_1 = tslib_1.__importDefault(require("pluralize"));
@@ -280,28 +280,58 @@ function getPermissionConfig(entities, relationshipMap, auth) {
280
280
  return { routes, joins, grants: resolveGrants(entities, auth) };
281
281
  }
282
282
  exports.getPermissionConfig = getPermissionConfig;
283
+ const scopeSource = (contextKey) => contextKey === "userId" || contextKey === "email" ? contextKey : "tenant";
284
+ /**
285
+ * The scopeBy paths of an entity that run through parents, each resolved hop
286
+ * by hop. Every step before the last must be a many-to-one relationship: its
287
+ * foreign key is what the SQL filter follows.
288
+ */
289
+ function nestedScopes(entity, relationshipMap) {
290
+ if (!entity.scopeBy)
291
+ return [];
292
+ return parseScopeBy(entity.scopeBy)
293
+ .filter((s) => !s.direct && s.path)
294
+ .map((s) => {
295
+ const steps = s.path.split(".");
296
+ const tenantField = steps.pop();
297
+ let from = entity.name;
298
+ const hops = steps.map((step) => {
299
+ var _a;
300
+ const relation = ((_a = relationshipMap[from]) !== null && _a !== void 0 ? _a : []).find((r) => r.type === "ManyToOne" && (0, parse_1.getRelationshipName)(r) === step);
301
+ if (!relation)
302
+ throw new Error(`${entity.name}.scopeBy "${s.path}": "${step}" must be a many-to-one relationship of ${from}`);
303
+ const hop = { entity: relation.name, field: (0, parse_1.getRelationshipIdField)(relation) };
304
+ from = relation.name;
305
+ return hop;
306
+ });
307
+ return {
308
+ field: hops[0].field,
309
+ parents: hops.map((h, i) => { var _a; return ({ entity: h.entity, field: (_a = hops[i + 1]) === null || _a === void 0 ? void 0 : _a.field }); }),
310
+ tenantField,
311
+ source: scopeSource(tenantField),
312
+ };
313
+ });
314
+ }
315
+ exports.nestedScopes = nestedScopes;
283
316
  /**
284
317
  * The direct scopeBy fields of an entity, for services that filter in their
285
318
  * own queries (Go, Python). Undefined without auth: with no caller identity
286
- * there is no tenant to scope by. Nested paths (task.workspaceId) are not
287
- * included; see hasNestedScopes.
319
+ * there is no tenant to scope by. Paths through a parent (task.workspaceId)
320
+ * are resolved only when the relationship map is given.
288
321
  */
289
- function entityScope(entity, hasAuth) {
322
+ function entityScope(entity, hasAuth, relationshipMap) {
290
323
  if (!hasAuth || !entity.scopeBy)
291
324
  return undefined;
292
325
  const [config] = getScopedEntities([entity]);
293
326
  const fields = config.scopes
294
327
  .filter((s) => s.direct)
295
- .map((s) => ({
296
- field: s.field,
297
- source: s.contextKey === "userId" || s.contextKey === "email"
298
- ? s.contextKey
299
- : "tenant",
300
- }));
301
- if (fields.length === 0)
328
+ .map((s) => ({ field: s.field, source: scopeSource(s.contextKey) }));
329
+ const nested = relationshipMap ? nestedScopes(entity, relationshipMap) : [];
330
+ if (fields.length === 0 && nested.length === 0)
302
331
  return undefined;
303
332
  return {
304
333
  fields,
334
+ nested,
305
335
  bypassRoles: config.bypassRoles,
306
336
  };
307
337
  }
@@ -364,13 +394,6 @@ function relationScopes(entities, relationshipMap, hasAuth) {
364
394
  return table;
365
395
  }
366
396
  exports.relationScopes = relationScopes;
367
- /** Entities whose scopeBy uses a nested path, which Go and Python cannot enforce. */
368
- function nestedScopeEntities(entities) {
369
- return getScopedEntities(entities)
370
- .filter((e) => e.scopes.some((s) => !s.direct))
371
- .map((e) => e.name);
372
- }
373
- exports.nestedScopeEntities = nestedScopeEntities;
374
397
  /**
375
398
  * One warning per provider that maps no tenant claim while entities are
376
399
  * tenant-scoped: its users would get 403 on every one of those entities.
@@ -402,3 +425,110 @@ function scopedReferences(entity, foreignKeys, scopes) {
402
425
  return Object.fromEntries(foreignKeys.filter(([field, target]) => { var _a; return !own.has(field) && ((_a = scopes === null || scopes === void 0 ? void 0 : scopes[target]) === null || _a === void 0 ? void 0 : _a.bypassRoles) !== undefined; }));
403
426
  }
404
427
  exports.scopedReferences = scopedReferences;
428
+ /*
429
+ * Access text for the OpenAPI contract (/_docs-json). An app builder reading
430
+ * the contract should leave these rules to the API instead of copying them
431
+ * into the browser: matching users to roles by email, sending the tenant on a
432
+ * write, hiding a delete button as the only check.
433
+ */
434
+ const PROVIDER_NAMES = {
435
+ "better-auth": "Better Auth",
436
+ auth0: "Auth0",
437
+ clerk: "Clerk",
438
+ cognito: "Amazon Cognito",
439
+ jwt: "a JWT issuer",
440
+ };
441
+ const KEY_ONLY_DESCRIPTION = "Every request needs the service API key in the `x-api-key` header; without it the API answers 401. " +
442
+ "The key is for server-side callers only. Never put it in a browser app: a browser app calls its own backend, which calls this API.";
443
+ /** "the token's `o.rol` claim", naming each provider's claim when they differ. */
444
+ function claimText(providers, pick) {
445
+ const names = [...new Set(providers.map((p) => pick(p)).filter((n) => Boolean(n)))];
446
+ if (names.length === 0)
447
+ return undefined;
448
+ return `the token's ${names.map((n) => `\`${n}\``).join(" or ")} claim`;
449
+ }
450
+ const tenantClaim = (p) => { var _a; return (_a = p.claims.workspaceId) !== null && _a !== void 0 ? _a : p.claims.organizationId; };
451
+ const joinWords = (words, last = "and") => words.length <= 1 ? words.join("") : `${words.slice(0, -1).join(", ")} ${last} ${words[words.length - 1]}`;
452
+ /**
453
+ * One operation's role rule as a sentence, for its OpenAPI description:
454
+ * "Requires role: manager (from the token's `o.rol` claim). Other callers get 403."
455
+ */
456
+ function roleRuleText(rule, auth) {
457
+ const providers = (0, types_1.resolveJwtProviders)(auth);
458
+ const roles = claimText(providers, (p) => p.claims.roles);
459
+ const perms = claimText(providers, (p) => p.claims.permissions);
460
+ return (`Requires role: ${joinWords(rule.roles, "or")}${roles ? ` (from ${roles})` : " (from the token)"}` +
461
+ `${perms ? `, or \`${rule.permission}\` in ${perms}` : ""}. Other signed-in users get 403. ` +
462
+ "The API checks this; a client app must not re-implement it.");
463
+ }
464
+ exports.roleRuleText = roleRuleText;
465
+ /** Each guarded operation of an entity and its rule, from .apsorc permissions. */
466
+ function entityRoleRules(entity) {
467
+ var _a;
468
+ return Object.fromEntries(Object.entries((_a = entity.permissions) !== null && _a !== void 0 ? _a : {}).map(([op, roles]) => [
469
+ op,
470
+ { permission: `${permissionKey(entity.name)}:${op}`, roles: roles !== null && roles !== void 0 ? roles : [] },
471
+ ]));
472
+ }
473
+ exports.entityRoleRules = entityRoleRules;
474
+ /**
475
+ * The OpenAPI info.description: who signs callers in, how records are scoped
476
+ * and which operations need which role, in plain words.
477
+ */
478
+ function accessSummary(entities, auth) {
479
+ var _a, _b, _c, _d, _e, _f;
480
+ const providers = (0, types_1.resolveJwtProviders)(auth);
481
+ if (providers.length === 0)
482
+ return KEY_ONLY_DESCRIPTION;
483
+ const lines = [
484
+ "**Access rules.** This API enforces every rule below on every request. A client app must not re-implement them: " +
485
+ "do not look users up to decide their role, do not send the tenant field, and do not treat a hidden button as the check.",
486
+ "",
487
+ `- **Sign-in:** ${joinWords([...new Set(providers.map((p) => (p.provider === "jwt" ? `a JWT issuer (${p.issuer})` : PROVIDER_NAMES[p.provider])))], "or")}. Send the signed-in user's token as \`Authorization: Bearer <token>\`. Without a valid token the API answers 401.`,
488
+ ];
489
+ const tenant = (_a = claimText(providers, tenantClaim)) !== null && _a !== void 0 ? _a : "the token's tenant claim";
490
+ const user = (_b = claimText(providers, (p) => p.claims.userId)) !== null && _b !== void 0 ? _b : "the token's `sub` claim";
491
+ // Entities by scope sentence, so a schema scoped by one field reads as one line.
492
+ const byScope = new Map();
493
+ for (const { name, scopes, bypassRoles } of getScopedEntities(entities)) {
494
+ const parts = scopes.map((s) => s.direct
495
+ ? `\`${s.field}\` is taken from ${s.contextKey === "userId" ? user : s.contextKey === "email" ? "the token's email claim" : tenant}`
496
+ : `rows are limited through \`${s.path}\` to the caller's tenant (${tenant})`);
497
+ const bypass = bypassRoles.length > 0 ? ` Callers with role ${joinWords(bypassRoles, "or")} see every tenant.` : "";
498
+ const key = `${parts.join("; ")}.${bypass}`;
499
+ const group = (_c = byScope.get(key)) !== null && _c !== void 0 ? _c : { names: [], fields: scopes.filter((s) => s.direct).map((s) => `\`${s.field}\``) };
500
+ group.names.push(name);
501
+ byScope.set(key, group);
502
+ }
503
+ for (const [scope, { names, fields }] of byScope) {
504
+ const it = fields.length > 1 ? "them" : "it";
505
+ lines.push(`- **Scoped records:** ${joinWords(names)}: ${scope} Reads and lists return only the caller's records` +
506
+ (fields.length > 0
507
+ ? `, and creates and updates set ${joinWords(fields)} from the token. The client must not send ${it} or filter by ${it}.`
508
+ : "."));
509
+ }
510
+ const guarded = entities.filter((e) => e.permissions && Object.keys(e.permissions).length > 0);
511
+ if (guarded.length > 0) {
512
+ const roles = (_d = claimText(providers, (p) => p.claims.roles)) !== null && _d !== void 0 ? _d : "the token";
513
+ const perms = claimText(providers, (p) => p.claims.permissions);
514
+ lines.push(`- **Roles** come from ${roles}${perms ? ` (a permission such as \`${permissionKey(guarded[0].name)}:delete\` in ${perms} also passes)` : ""}. ` +
515
+ "A caller without the role gets 403. Operations not listed are open to any signed-in user:");
516
+ for (const entity of guarded) {
517
+ // Operations that need the same roles share a clause.
518
+ const byRoles = new Map();
519
+ for (const op of types_1.PERMISSION_OPERATIONS) {
520
+ const roles = (_e = entity.permissions) === null || _e === void 0 ? void 0 : _e[op];
521
+ if (!roles)
522
+ continue;
523
+ const key = joinWords(roles, "or");
524
+ byRoles.set(key, [...((_f = byRoles.get(key)) !== null && _f !== void 0 ? _f : []), op]);
525
+ }
526
+ const clauses = [...byRoles].map(([roles, ops]) => `${joinWords(ops)} need${ops.length === 1 ? "s" : ""} ${roles}`);
527
+ lines.push(` - ${entity.name}: ${clauses.join("; ")}.`);
528
+ }
529
+ lines.push("- To show only the actions a user may take, read the role from the same token, and still handle 403.");
530
+ }
531
+ lines.push("- **API key:** server-side callers may send the service key in `x-api-key` instead of a token. It is not limited to one tenant or role. Never put it in a browser app.");
532
+ return lines.join("\n");
533
+ }
534
+ exports.accessSummary = accessSummary;
@@ -28,7 +28,7 @@ exports.targetTableName = targetTableName;
28
28
  function buildColumnMapping(table) {
29
29
  const fkRefByColumn = new Map();
30
30
  for (const fk of table.foreignKeys) {
31
- if (fk.columns.length === 1) {
31
+ if (fk.columns.length === 1 && !fk.referencedSchema) {
32
32
  fkRefByColumn.set(fk.columns[0], fk.referencedTable);
33
33
  }
34
34
  }
@@ -60,7 +60,9 @@ function topoSortTables(tables) {
60
60
  for (const t of tables) {
61
61
  const d = new Set();
62
62
  for (const fk of t.foreignKeys) {
63
- if (fk.referencedTable !== t.name && names.has(fk.referencedTable)) {
63
+ if (!fk.referencedSchema &&
64
+ fk.referencedTable !== t.name &&
65
+ names.has(fk.referencedTable)) {
64
66
  d.add(fk.referencedTable);
65
67
  }
66
68
  }