@apso/cli 0.52.0 → 0.53.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 (93) hide show
  1. package/dist/commands/import/supabase.js +31 -6
  2. package/dist/commands/init.d.ts +9 -0
  3. package/dist/commands/init.js +31 -1
  4. package/dist/commands/mcp/serve.js +20 -0
  5. package/dist/lib/apsorc-parser.js +7 -3
  6. package/dist/lib/ddl/catalog.js +5 -2
  7. package/dist/lib/ddl/change.js +13 -2
  8. package/dist/lib/ddl/index.d.ts +62 -3
  9. package/dist/lib/ddl/index.js +211 -40
  10. package/dist/lib/generators/go.js +17 -3
  11. package/dist/lib/generators/python.js +17 -3
  12. package/dist/lib/generators/typescript.js +85 -15
  13. package/dist/lib/import/copy-data.js +4 -0
  14. package/dist/lib/import/introspect.d.ts +40 -0
  15. package/dist/lib/import/introspect.js +137 -49
  16. package/dist/lib/import/pg-to-apsorc.d.ts +62 -0
  17. package/dist/lib/import/pg-to-apsorc.js +248 -37
  18. package/dist/lib/import/types.d.ts +48 -3
  19. package/dist/lib/migrate/sandbox.js +23 -6
  20. package/dist/lib/migrate/snapshot.d.ts +5 -0
  21. package/dist/lib/plan/index.d.ts +4 -1
  22. package/dist/lib/plan/index.js +9 -3
  23. package/dist/lib/templates/entities/entity-col-array.eta +2 -1
  24. package/dist/lib/templates/entities/entity-col-bigint.eta +2 -2
  25. package/dist/lib/templates/entities/entity-col-bigserial.eta +2 -2
  26. package/dist/lib/templates/entities/entity-col-boolean.eta +1 -1
  27. package/dist/lib/templates/entities/entity-col-bytea.eta +2 -2
  28. package/dist/lib/templates/entities/entity-col-char.eta +4 -3
  29. package/dist/lib/templates/entities/entity-col-date.eta +6 -2
  30. package/dist/lib/templates/entities/entity-col-datetime.eta +8 -1
  31. package/dist/lib/templates/entities/entity-col-decimal.eta +2 -2
  32. package/dist/lib/templates/entities/entity-col-double.eta +2 -2
  33. package/dist/lib/templates/entities/entity-col-float.eta +1 -1
  34. package/dist/lib/templates/entities/entity-col-geography.eta +1 -1
  35. package/dist/lib/templates/entities/entity-col-geometry.eta +1 -1
  36. package/dist/lib/templates/entities/entity-col-geometrycollection.eta +1 -1
  37. package/dist/lib/templates/entities/entity-col-inet.eta +2 -2
  38. package/dist/lib/templates/entities/entity-col-int4range.eta +1 -1
  39. package/dist/lib/templates/entities/entity-col-integer.eta +2 -2
  40. package/dist/lib/templates/entities/entity-col-interval.eta +2 -2
  41. package/dist/lib/templates/entities/entity-col-json-plain.eta +1 -1
  42. package/dist/lib/templates/entities/entity-col-json.eta +1 -1
  43. package/dist/lib/templates/entities/entity-col-jsonb.eta +1 -1
  44. package/dist/lib/templates/entities/entity-col-linestring.eta +1 -1
  45. package/dist/lib/templates/entities/entity-col-money.eta +2 -2
  46. package/dist/lib/templates/entities/entity-col-multilinestring.eta +1 -1
  47. package/dist/lib/templates/entities/entity-col-multipoint.eta +1 -1
  48. package/dist/lib/templates/entities/entity-col-multipolygon.eta +1 -1
  49. package/dist/lib/templates/entities/entity-col-numeric.eta +2 -2
  50. package/dist/lib/templates/entities/entity-col-point.eta +1 -1
  51. package/dist/lib/templates/entities/entity-col-polygon.eta +1 -1
  52. package/dist/lib/templates/entities/entity-col-real.eta +2 -2
  53. package/dist/lib/templates/entities/entity-col-serial.eta +2 -2
  54. package/dist/lib/templates/entities/entity-col-smallint.eta +2 -2
  55. package/dist/lib/templates/entities/entity-col-smallserial.eta +2 -2
  56. package/dist/lib/templates/entities/entity-col-string.eta +2 -2
  57. package/dist/lib/templates/entities/entity-col-text.eta +4 -3
  58. package/dist/lib/templates/entities/entity-col-time.eta +2 -2
  59. package/dist/lib/templates/entities/entity-col-timestamp.eta +8 -1
  60. package/dist/lib/templates/entities/entity-col-timestamptz.eta +8 -1
  61. package/dist/lib/templates/entities/entity-col-timetz.eta +2 -2
  62. package/dist/lib/templates/entities/entity-col-tsvector.eta +2 -2
  63. package/dist/lib/templates/entities/entity-col-uuid.eta +5 -2
  64. package/dist/lib/templates/entities/entity-col-varchar.eta +4 -3
  65. package/dist/lib/templates/entities/entity-col-xml.eta +2 -2
  66. package/dist/lib/templates/entities/entity.eta +30 -18
  67. package/dist/lib/templates/go/models/model.eta +3 -3
  68. package/dist/lib/templates/python/models/model.eta +1 -1
  69. package/dist/lib/templates/rest/controller-rest.eta +16 -5
  70. package/dist/lib/templates/rest/dto-rest.eta +2 -2
  71. package/dist/lib/templates/rest/index-module-rest.eta +6 -0
  72. package/dist/lib/templates/rest/schema-extras-module.eta +24 -0
  73. package/dist/lib/types/constraints.d.ts +13 -0
  74. package/dist/lib/types/entity.d.ts +67 -2
  75. package/dist/lib/types/entity.js +39 -1
  76. package/dist/lib/types/field.d.ts +20 -2
  77. package/dist/lib/types/indices.d.ts +21 -0
  78. package/dist/lib/types/relationship.d.ts +33 -0
  79. package/dist/lib/types/relationship.js +13 -0
  80. package/dist/lib/utils/field.d.ts +22 -0
  81. package/dist/lib/utils/field.js +62 -3
  82. package/dist/lib/utils/relationships/index.d.ts +1 -1
  83. package/dist/lib/utils/relationships/index.js +2 -1
  84. package/dist/lib/utils/relationships/parse.d.ts +11 -0
  85. package/dist/lib/utils/relationships/parse.js +44 -1
  86. package/dist/lib/utils/template.d.ts +3 -3
  87. package/dist/lib/utils/template.js +4 -4
  88. package/dist/lib/verify/crud-plan.d.ts +2 -0
  89. package/dist/lib/verify/crud-plan.js +19 -5
  90. package/dist/lib/verify/index.js +32 -3
  91. package/npm-shrinkwrap.json +72 -87
  92. package/oclif.manifest.json +7 -1
  93. package/package.json +3 -2
@@ -1,2 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.onDeleteOf = void 0;
4
+ /**
5
+ * The ON DELETE rule of a ManyToOne's foreign key, undefined for the
6
+ * database default (NO ACTION).
7
+ *
8
+ * @param {object} r - A relationship's "onDelete" and "cascadeDelete".
9
+ * @returns {OnDelete | undefined} The rule to write, if any.
10
+ */
11
+ const onDeleteOf = (r) => {
12
+ const rule = r.onDelete || (r.cascadeDelete ? "CASCADE" : undefined);
13
+ return rule === "NO ACTION" ? undefined : rule;
14
+ };
15
+ exports.onDeleteOf = onDeleteOf;
@@ -24,6 +24,28 @@ export declare const arrayElementType: (field: Field & {
24
24
  arrayType?: string;
25
25
  arrayItemType?: string;
26
26
  }) => string;
27
+ /**
28
+ * A default that has to be written as SQL: { "sql": ... }, or an object or
29
+ * array literal on a json or array field.
30
+ *
31
+ * @param {Field} field - A field from .apsorc.
32
+ * @returns {string | undefined} The SQL text, or undefined for a plain literal.
33
+ */
34
+ export declare const defaultSqlOf: (field: Field) => string | undefined;
35
+ /** A default Postgres itself fills with a new uuid. */
36
+ export declare const isUuidGenerator: (sql?: string | null) => boolean;
37
+ /**
38
+ * A SQL default as a TypeORM entity has to spell it. TypeORM strips type
39
+ * casts from the default it reads out of Postgres, so an entity that keeps
40
+ * `'[]'::jsonb` never compares equal and the default is set again on every
41
+ * schema sync and reported as drift. Postgres puts the cast back when the
42
+ * column is created, so the database is the same either way.
43
+ *
44
+ * @param {string} sql - The default as the source database prints it.
45
+ * @returns {string} The cast-free text, or the original when removing the
46
+ * casts would remove more than casts or leave an untyped empty array.
47
+ */
48
+ export declare const typeormDefault: (sql: string) => string;
27
49
  export declare const getDefaultValueForField: (field: Field) => string | null;
28
50
  export declare const getFieldForTemplate: (fields: Field[], entityName: string) => ComputedField[];
29
51
  export declare const fieldToEnumType: (fieldName: string, entityName: string) => string;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateDecimalField = exports.typeExistsInEntity = exports.fieldToEnumType = exports.getFieldForTemplate = exports.getDefaultValueForField = exports.arrayElementType = exports.getJsTypeFromFieldType = exports.normalizeFieldType = exports.fieldTypeToColumnType = void 0;
3
+ exports.validateDecimalField = exports.typeExistsInEntity = exports.fieldToEnumType = exports.getFieldForTemplate = exports.getDefaultValueForField = exports.typeormDefault = exports.isUuidGenerator = exports.defaultSqlOf = exports.arrayElementType = exports.getJsTypeFromFieldType = exports.normalizeFieldType = exports.fieldTypeToColumnType = void 0;
4
4
  const casing_1 = require("./casing");
5
5
  /**
6
6
  * Canonical mapping from .apsorc field types to Postgres column types.
@@ -140,7 +140,56 @@ exports.getJsTypeFromFieldType = getJsTypeFromFieldType;
140
140
  */
141
141
  const arrayElementType = (field) => field.elementType || field.arrayType || field.arrayItemType || "text";
142
142
  exports.arrayElementType = arrayElementType;
143
+ /**
144
+ * A default that has to be written as SQL: { "sql": ... }, or an object or
145
+ * array literal on a json or array field.
146
+ *
147
+ * @param {Field} field - A field from .apsorc.
148
+ * @returns {string | undefined} The SQL text, or undefined for a plain literal.
149
+ */
150
+ const defaultSqlOf = (field) => {
151
+ const d = field.default;
152
+ if (d === null || typeof d !== "object")
153
+ return undefined;
154
+ if (!Array.isArray(d) && typeof d.sql === "string")
155
+ return d.sql;
156
+ return `'${JSON.stringify(d).replace(/'/g, "''")}'`;
157
+ };
158
+ exports.defaultSqlOf = defaultSqlOf;
159
+ /** A default Postgres itself fills with a new uuid. */
160
+ const isUuidGenerator = (sql) => /^(gen_random_uuid|uuid_generate_v\d)\(\)$/.test(sql !== null && sql !== void 0 ? sql : "");
161
+ exports.isUuidGenerator = isUuidGenerator;
162
+ // TypeORM reads a column default back through the first pattern before it
163
+ // compares it with the entity's. The second is the same thing limited to real
164
+ // type casts: TypeORM's also swallows what follows a cast, as in "::integer - 1".
165
+ const TYPEORM_CAST = /::[\s\w".[\]-]+/g;
166
+ const TYPE_CAST = /::"?[_a-z]\w*"?(?: varying| precision| with(?:out)? time zone)?(?:\(\d+(?:,\d+)?\))?(?:\[])?/gi;
167
+ const squash = (s) => s.replace(/\s+/g, "");
168
+ /**
169
+ * A SQL default as a TypeORM entity has to spell it. TypeORM strips type
170
+ * casts from the default it reads out of Postgres, so an entity that keeps
171
+ * `'[]'::jsonb` never compares equal and the default is set again on every
172
+ * schema sync and reported as drift. Postgres puts the cast back when the
173
+ * column is created, so the database is the same either way.
174
+ *
175
+ * @param {string} sql - The default as the source database prints it.
176
+ * @returns {string} The cast-free text, or the original when removing the
177
+ * casts would remove more than casts or leave an untyped empty array.
178
+ */
179
+ const typeormDefault = (sql) => {
180
+ const stripped = sql.replace(TYPEORM_CAST, "");
181
+ const onlyCasts = squash(stripped) === squash(sql.replace(TYPE_CAST, ""));
182
+ return onlyCasts && !/array\[\s*]/i.test(stripped) ? stripped : sql;
183
+ };
184
+ exports.typeormDefault = typeormDefault;
143
185
  const getDefaultValueForField = (field) => {
186
+ if ((0, exports.defaultSqlOf)(field) !== undefined)
187
+ return null;
188
+ const literal = { ...field, default: field.default };
189
+ return literalDefault(literal);
190
+ };
191
+ exports.getDefaultValueForField = getDefaultValueForField;
192
+ const literalDefault = (field) => {
144
193
  var _a, _b;
145
194
  switch (field.type) {
146
195
  case "enum":
@@ -169,10 +218,15 @@ const getDefaultValueForField = (field) => {
169
218
  return null;
170
219
  }
171
220
  };
172
- exports.getDefaultValueForField = getDefaultValueForField;
173
221
  const getFieldForTemplate = (fields, entityName) => fields.map((field) => {
174
222
  // Validate decimal/numeric fields
175
223
  (0, exports.validateDecimalField)(field);
224
+ if (field.generated !== undefined) {
225
+ const clash = (field.primary && "primary") ||
226
+ (field.default !== undefined && field.default !== null && "default");
227
+ if (clash)
228
+ throw new Error(`${entityName}.${field.name} sets "generated" and "${clash}". Postgres computes a generated column, so it cannot have a default or be the primary key.`);
229
+ }
176
230
  // Normalize field type for template lookup (e.g., "double precision" -> "double")
177
231
  const normalizedType = (0, exports.normalizeFieldType)(field.type);
178
232
  return {
@@ -181,7 +235,12 @@ const getFieldForTemplate = (fields, entityName) => fields.map((field) => {
181
235
  type: normalizedType,
182
236
  // Resolved here so every template and the DDL writer read one key.
183
237
  ...(field.type === "array" && { elementType: (0, exports.arrayElementType)(field) }),
184
- default: (0, exports.getDefaultValueForField)(field),
238
+ // A generated column has no default (a boolean would otherwise get false).
239
+ default: field.generated ? null : (0, exports.getDefaultValueForField)(field),
240
+ ...(field.generated && { noDefault: true }),
241
+ ...((0, exports.defaultSqlOf)(field) !== undefined && {
242
+ defaultSql: (0, exports.defaultSqlOf)(field),
243
+ }),
185
244
  dataType: field.type === "enum"
186
245
  ? (0, exports.fieldToEnumType)(field.name, entityName)
187
246
  : field.type === "array"
@@ -1,2 +1,2 @@
1
- export { parseRelationships, getRelationshipsForImport, getRelationshipForTemplate, getNestedRelationships, getRelationshipIdField, } from "./parse";
1
+ export { parseRelationships, getRelationshipsForImport, getRelationshipForTemplate, getNestedRelationships, getRelationshipIdField, joinColumnErrors, } from "./parse";
2
2
  export { parseV1Relationships } from "./parse-v1";
@@ -1,11 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parseV1Relationships = exports.getRelationshipIdField = exports.getNestedRelationships = exports.getRelationshipForTemplate = exports.getRelationshipsForImport = exports.parseRelationships = void 0;
3
+ exports.parseV1Relationships = exports.joinColumnErrors = exports.getRelationshipIdField = exports.getNestedRelationships = exports.getRelationshipForTemplate = exports.getRelationshipsForImport = exports.parseRelationships = void 0;
4
4
  var parse_1 = require("./parse");
5
5
  Object.defineProperty(exports, "parseRelationships", { enumerable: true, get: function () { return parse_1.parseRelationships; } });
6
6
  Object.defineProperty(exports, "getRelationshipsForImport", { enumerable: true, get: function () { return parse_1.getRelationshipsForImport; } });
7
7
  Object.defineProperty(exports, "getRelationshipForTemplate", { enumerable: true, get: function () { return parse_1.getRelationshipForTemplate; } });
8
8
  Object.defineProperty(exports, "getNestedRelationships", { enumerable: true, get: function () { return parse_1.getNestedRelationships; } });
9
9
  Object.defineProperty(exports, "getRelationshipIdField", { enumerable: true, get: function () { return parse_1.getRelationshipIdField; } });
10
+ Object.defineProperty(exports, "joinColumnErrors", { enumerable: true, get: function () { return parse_1.joinColumnErrors; } });
10
11
  var parse_v1_1 = require("./parse-v1");
11
12
  Object.defineProperty(exports, "parseV1Relationships", { enumerable: true, get: function () { return parse_v1_1.parseV1Relationships; } });
@@ -80,3 +80,14 @@ export declare function generateNestedRelationships(entityName: string, relation
80
80
  export declare function getNestedRelationships(entityName: string, relationshipMap: RelationshipMap, maxDepth?: number): string[];
81
81
  export declare function streamNestedRelationships(entityName: string, relationshipMap: RelationshipMap, writable: NodeJS.WritableStream, maxDepth?: number): Promise<number>;
82
82
  export declare const getRelationshipsForImport: (entityName: string, relationships?: Relationship[]) => string[];
83
+ /**
84
+ * One error per foreign key that names its own column. The Python and Go
85
+ * generators use one name for the column, the model attribute and the API
86
+ * field, so they refuse "joinColumnName" on a foreign key instead of
87
+ * building a different column (apsoai/cli#241).
88
+ *
89
+ * @param {RelationshipMap} relationshipMap - The parsed relationships.
90
+ * @param {string} language - The generator's name, for the message.
91
+ * @returns {string[]} The errors, empty when no foreign key sets a column name.
92
+ */
93
+ export declare const joinColumnErrors: (relationshipMap: RelationshipMap | undefined, language: string) => string[];
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getRelationshipsForImport = exports.streamNestedRelationships = exports.getNestedRelationships = exports.generateNestedRelationships = exports.getRelationshipForTemplate = exports.getRelationshipIdField = exports.getRelationshipName = exports.parseRelationships = exports.parseRelationship = exports.parseManyToMany = exports.parseManytoOne = exports.parseOneToMany = void 0;
3
+ exports.joinColumnErrors = exports.getRelationshipsForImport = exports.streamNestedRelationships = exports.getNestedRelationships = exports.generateNestedRelationships = exports.getRelationshipForTemplate = exports.getRelationshipIdField = exports.getRelationshipName = exports.parseRelationships = exports.parseRelationship = exports.parseManyToMany = exports.parseManytoOne = exports.parseOneToMany = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const pluralize_1 = tslib_1.__importDefault(require("pluralize"));
6
6
  const casing_1 = require("../casing");
@@ -235,6 +235,7 @@ const createFromOneToOneRelationship = (relationship, inverseDefinition) => {
235
235
  referenceName: relationship.to_name || relationship.to,
236
236
  biDirectional: relationship.bi_directional || false,
237
237
  inverseReferenceName: (inverseDefinition === null || inverseDefinition === void 0 ? void 0 : inverseDefinition.to_name) || relationship.from,
238
+ joinColumnName: isOwner ? relationship.joinColumnName : undefined,
238
239
  };
239
240
  };
240
241
  /**
@@ -254,6 +255,7 @@ isOwner // Is the 'from' side the owner?
254
255
  join: !isOwner,
255
256
  referenceName: inverseDefinition.to_name || relationship.from,
256
257
  inverseReferenceName: relationship.to_name || relationship.to,
258
+ joinColumnName: isOwner ? undefined : relationship.joinColumnName,
257
259
  };
258
260
  };
259
261
  /**
@@ -292,6 +294,11 @@ const parseRelationship = (relationship, allRelationships) => {
292
294
  cascadeDelete: relationship.cascadeDelete || false,
293
295
  referenceName: toSideRefName,
294
296
  inverseReferenceName: fromSideRefName,
297
+ joinColumnName: relationship.joinColumnName,
298
+ onDelete: relationship.onDelete,
299
+ foreignKeyName: relationship.foreignKeyName,
300
+ primary: relationship.primary,
301
+ validate: relationship.validate,
295
302
  },
296
303
  ],
297
304
  };
@@ -314,6 +321,11 @@ const parseRelationship = (relationship, allRelationships) => {
314
321
  referenceName: manySideRefName,
315
322
  nullable: relationship.nullable || false,
316
323
  index: relationship.index || false,
324
+ joinColumnName: relationship.joinColumnName,
325
+ onDelete: relationship.onDelete,
326
+ foreignKeyName: relationship.foreignKeyName,
327
+ primary: relationship.primary,
328
+ validate: relationship.validate,
317
329
  },
318
330
  ],
319
331
  };
@@ -329,6 +341,11 @@ const parseRelationship = (relationship, allRelationships) => {
329
341
  cascadeDelete: relationship.cascadeDelete || false,
330
342
  referenceName: manySideRefName,
331
343
  inverseReferenceName: relationship.from,
344
+ joinColumnName: relationship.joinColumnName,
345
+ onDelete: relationship.onDelete,
346
+ foreignKeyName: relationship.foreignKeyName,
347
+ primary: relationship.primary,
348
+ validate: relationship.validate,
332
349
  },
333
350
  ],
334
351
  [relationship.to]: [
@@ -661,3 +678,29 @@ const getRelationshipsForImport = (entityName, relationships) => {
661
678
  ];
662
679
  };
663
680
  exports.getRelationshipsForImport = getRelationshipsForImport;
681
+ /**
682
+ * One error per foreign key that names its own column. The Python and Go
683
+ * generators use one name for the column, the model attribute and the API
684
+ * field, so they refuse "joinColumnName" on a foreign key instead of
685
+ * building a different column (apsoai/cli#241).
686
+ *
687
+ * @param {RelationshipMap} relationshipMap - The parsed relationships.
688
+ * @param {string} language - The generator's name, for the message.
689
+ * @returns {string[]} The errors, empty when no foreign key sets a column name.
690
+ */
691
+ const joinColumnErrors = (relationshipMap, language) => Object.entries(relationshipMap !== null && relationshipMap !== void 0 ? relationshipMap : {}).flatMap(([entity, relationships]) => relationships
692
+ .filter((r) => r.type === "ManyToOne" || r.type === "OneToOne")
693
+ .flatMap((r) => [
694
+ ...(r.validate === false
695
+ ? [
696
+ `${entity} ${r.type} ${r.name} sets "validate": false. The ${language} generator cannot keep a NOT VALID foreign key yet; remove it or generate a TypeScript service.`,
697
+ ]
698
+ : []),
699
+ ...keyAndNameErrors(entity, r, language),
700
+ ]));
701
+ exports.joinColumnErrors = joinColumnErrors;
702
+ const keyAndNameErrors = (entity, r, language) => ["joinColumnName", "foreignKeyName", "primary"]
703
+ .filter((key) => r[key])
704
+ .map((key) => `${entity} ${r.type} ${r.name} sets "${key}": ${JSON.stringify(r[key])}. The ${language} generator cannot keep ${key === "primary"
705
+ ? "a primary key that is a foreign key"
706
+ : `a custom foreign key ${key === "joinColumnName" ? "column" : "constraint"} name`} yet; remove it or generate a TypeScript service.`);
@@ -3,9 +3,9 @@ export declare const TEMPLATE_REPOS: Record<TargetLanguage, string>;
3
3
  /**
4
4
  * Git ref (tag or branch) to clone for each template. Pinning to a tag makes
5
5
  * the CLI-version-to-template pairing explicit instead of a date cutoff on
6
- * template main. v2.1.2 matches what this CLI generates: @apso/crud ^1.1.0
7
- * (PostgREST-only), MCP at /mcp, request logging, and the AGENTS.md and
8
- * CLAUDE.md agent instructions. Move the tag when the template changes in a
6
+ * template main. v2.1.3 matches what this CLI generates: @apso/crud ^1.1.0
7
+ * (PostgREST-only), MCP at /mcp, request logging, the AGENTS.md and
8
+ * CLAUDE.md agent instructions, and uuid keys that work on PGlite. Move the tag when the template changes in a
9
9
  * way new projects need; the Python and Go
10
10
  * template repos are untagged and don't carry the dialect work.
11
11
  */
@@ -15,14 +15,14 @@ exports.TEMPLATE_REPOS = {
15
15
  /**
16
16
  * Git ref (tag or branch) to clone for each template. Pinning to a tag makes
17
17
  * the CLI-version-to-template pairing explicit instead of a date cutoff on
18
- * template main. v2.1.2 matches what this CLI generates: @apso/crud ^1.1.0
19
- * (PostgREST-only), MCP at /mcp, request logging, and the AGENTS.md and
20
- * CLAUDE.md agent instructions. Move the tag when the template changes in a
18
+ * template main. v2.1.3 matches what this CLI generates: @apso/crud ^1.1.0
19
+ * (PostgREST-only), MCP at /mcp, request logging, the AGENTS.md and
20
+ * CLAUDE.md agent instructions, and uuid keys that work on PGlite. Move the tag when the template changes in a
21
21
  * way new projects need; the Python and Go
22
22
  * template repos are untagged and don't carry the dialect work.
23
23
  */
24
24
  exports.TEMPLATE_REFS = {
25
- typescript: "v2.1.2",
25
+ typescript: "v2.1.3",
26
26
  python: "main",
27
27
  go: "main",
28
28
  };
@@ -9,6 +9,8 @@ import { RelationshipMap } from "../types/relationship";
9
9
  export declare function sampleValue(field: Field): unknown;
10
10
  export interface PlannedEntity {
11
11
  name: string;
12
+ /** The property that addresses a row: "id" unless the entity has its own key. */
13
+ key: string;
12
14
  payload: Record<string, unknown>;
13
15
  /** Foreign keys to fill from parents created earlier: property -> parent entity. */
14
16
  parents: {
@@ -46,10 +46,13 @@ function sampleValue(field) {
46
46
  }
47
47
  }
48
48
  exports.sampleValue = sampleValue;
49
- /** Required = not nullable, no default, and not a user-declared primary key. */
49
+ /**
50
+ * Required = not nullable, no default, and not a key the database fills. A
51
+ * uuid primary key is generated; any other primary field needs a value.
52
+ */
50
53
  const required = (field) => !field.nullable &&
51
54
  (field.default === undefined || field.default === null) &&
52
- !field.primary;
55
+ !(field.primary && field.type === "uuid");
53
56
  function planCrud(entities, relationships) {
54
57
  const pending = [];
55
58
  const skipped = [];
@@ -68,10 +71,21 @@ function planCrud(entities, relationships) {
68
71
  });
69
72
  continue;
70
73
  }
71
- const parents = (relationships[entity.name] || [])
72
- .filter((r) => r.type === "ManyToOne" && !r.nullable)
74
+ const manyToOne = (relationships[entity.name] || []).filter((r) => r.type === "ManyToOne");
75
+ const parents = manyToOne
76
+ .filter((r) => !r.nullable)
73
77
  .map((r) => ({ property: (0, relationships_1.getRelationshipIdField)(r), entity: r.name }));
74
- pending.push({ name: entity.name, payload, parents });
78
+ // The same rule as the generated controller's id parameter.
79
+ const keys = [
80
+ ...(entity.fields || []).filter((f) => f.primary).map((f) => f.name),
81
+ ...manyToOne.filter((r) => r.primary).map((r) => (0, relationships_1.getRelationshipIdField)(r)),
82
+ ];
83
+ pending.push({
84
+ name: entity.name,
85
+ key: keys.length === 1 ? keys[0] : "id",
86
+ payload,
87
+ parents,
88
+ });
75
89
  }
76
90
  // Topological order: take entities whose required parents are all planned.
77
91
  const order = [];
@@ -274,6 +274,7 @@ async function verifyMigration(projectDir, baselineApsorc, migrationFile, cliBin
274
274
  const source = fs.readFileSync(path.resolve(projectDir, migrationFile), "utf8");
275
275
  const findings = (0, review_1.reviewMigration)(source);
276
276
  const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "apso-pglite-"));
277
+ const metadataFile = `${dataDir}-generated.sql`;
277
278
  const steps = [];
278
279
  const done = (s) => {
279
280
  steps.push(s);
@@ -320,14 +321,42 @@ async function verifyMigration(projectDir, baselineApsorc, migrationFile, cliBin
320
321
  if (checkFile &&
321
322
  !done(step("check", await run(process.execPath, ["-e", RUN_CHECKS, path.resolve(checkFile)], projectDir, (0, exports.pgliteEnv)(dataDir)))))
322
323
  return { ok: false, steps, findings };
324
+ const metadata = generatedMetadataSql(path.join(projectDir, ".apsorc"));
325
+ if (metadata) {
326
+ fs.writeFileSync(metadataFile, metadata);
327
+ if (!done(step("generated", await run(process.execPath, ["-e", RUN_CHECKS, metadataFile], projectDir, (0, exports.pgliteEnv)(dataDir)))))
328
+ return { ok: false, steps, findings };
329
+ }
323
330
  const drift = await typeorm(projectDir, ["migration:generate", "./src/migrations/drift", "--check"], (0, exports.pgliteEnv)(dataDir));
324
331
  return { ok: done(step("drift", drift)), steps, findings };
325
332
  }
326
333
  finally {
327
334
  fs.rmSync(dataDir, { recursive: true, force: true });
335
+ fs.rmSync(metadataFile, { force: true });
328
336
  }
329
337
  }
330
338
  exports.verifyMigration = verifyMigration;
339
+ /**
340
+ * TypeORM reads a generated column's expression from its own typeorm_metadata
341
+ * table, which only its schema sync writes. A migration leaves that table
342
+ * alone, so the scratch database gets the rows here before TypeORM compares.
343
+ */
344
+ const generatedMetadataSql = (apsorcFile) => {
345
+ const { entities } = (0, apsorc_parser_1.parseApsorcV2)(JSON.parse(fs.readFileSync(apsorcFile).toString()));
346
+ const rows = entities.flatMap((e) => {
347
+ var _a;
348
+ return ((_a = e.fields) !== null && _a !== void 0 ? _a : [])
349
+ .filter((f) => f.generated)
350
+ .map((f) => `(current_database(), current_schema(), ${(0, ddl_1.literal)((0, ddl_1.tableName)(e))}, 'GENERATED_COLUMN', ${(0, ddl_1.literal)(f.name)}, ${(0, ddl_1.literal)(f.generated)})`);
351
+ });
352
+ if (rows.length === 0)
353
+ return undefined;
354
+ return [
355
+ 'CREATE TABLE IF NOT EXISTS "typeorm_metadata" ("type" varchar NOT NULL, "database" varchar, "schema" varchar, "table" varchar, "name" varchar, "value" text)',
356
+ `DELETE FROM "typeorm_metadata" WHERE "type" = 'GENERATED_COLUMN'`,
357
+ `INSERT INTO "typeorm_metadata" ("database", "schema", "table", "type", "name", "value") VALUES ${rows.join(", ")}`,
358
+ ].join(";\n");
359
+ };
331
360
  const ddlOf = (apsorcFile) => (0, ddl_1.schemaDdl)((0, apsorc_parser_1.parseApsorcV2)(JSON.parse(fs.readFileSync(apsorcFile).toString()))).join(";\n");
332
361
  /**
333
362
  * verifyMigration for an Alembic or goose migration. Python and Go services
@@ -473,10 +502,10 @@ const expectStatus = (res, ...ok) => ({
473
502
  ? undefined
474
503
  : `${res.status} ${tail(res.body, 500)}`,
475
504
  });
476
- const idOf = (body) => {
505
+ const idOf = (body, key = "id") => {
477
506
  var _a;
478
507
  try {
479
- return (_a = JSON.parse(body).id) !== null && _a !== void 0 ? _a : undefined;
508
+ return (_a = JSON.parse(body)[key]) !== null && _a !== void 0 ? _a : undefined;
480
509
  }
481
510
  catch {
482
511
  return undefined;
@@ -526,7 +555,7 @@ async function checkEndpoints(base, language, entities, relationships, done) {
526
555
  body[parent.property] = ids.get(parent.entity);
527
556
  const created = await request("POST", base + r, body);
528
557
  const id = [200, 201].includes(created.status)
529
- ? idOf(created.body)
558
+ ? idOf(created.body, p.key)
530
559
  : undefined;
531
560
  if (!done({
532
561
  name: `POST ${r}`,