mobiletto-orm-typedef-gen 2.3.42 → 2.8.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.
- package/README.md +16 -0
- package/lib/esm/generate.d.ts +12 -2
- package/lib/esm/generate.js +213 -30
- package/lib/esm/generate.js.map +1 -0
- package/lib/esm/generators/h3.d.ts +7 -0
- package/lib/esm/generators/h3.js +84 -0
- package/lib/esm/generators/h3.js.map +1 -0
- package/lib/esm/generators/jsonSchema.d.ts +3 -0
- package/lib/esm/generators/jsonSchema.js +48 -0
- package/lib/esm/generators/jsonSchema.js.map +1 -0
- package/lib/esm/generators/server.d.ts +14 -9
- package/lib/esm/generators/server.js +79 -53
- package/lib/esm/generators/server.js.map +1 -0
- package/lib/esm/generators/tsType.d.ts +2 -2
- package/lib/esm/generators/tsType.js +2 -1
- package/lib/esm/generators/tsType.js.map +1 -0
- package/lib/esm/generators/vue/admin.d.ts +5 -0
- package/lib/esm/generators/vue/admin.js +83 -0
- package/lib/esm/generators/vue/admin.js.map +1 -0
- package/lib/esm/generators/vue/service.d.ts +4 -0
- package/lib/esm/generators/vue/service.js +47 -0
- package/lib/esm/generators/vue/service.js.map +1 -0
- package/lib/esm/generators/vue/store.d.ts +5 -0
- package/lib/esm/generators/vue/store.js +43 -0
- package/lib/esm/generators/vue/store.js.map +1 -0
- package/lib/esm/helpers.d.ts +4 -0
- package/lib/esm/helpers.js +160 -0
- package/lib/esm/helpers.js.map +1 -0
- package/lib/esm/index.d.ts +6 -2
- package/lib/esm/index.js +7 -2
- package/lib/esm/index.js.map +1 -0
- package/lib/esm/templates/admin/adminComponent.vue.hbs +662 -0
- package/lib/esm/templates/admin/adminHelper.ts.hbs +52 -0
- package/lib/esm/templates/admin/adminPage.vue.hbs +53 -0
- package/lib/esm/templates/api/h3.ts.hbs +13 -0
- package/lib/esm/templates/api/id.delete.ts.hbs +94 -32
- package/lib/esm/templates/api/id.get.ts.hbs +79 -18
- package/lib/esm/templates/api/id.patch.ts.hbs +76 -24
- package/lib/esm/templates/api/id.put.ts.hbs +65 -18
- package/lib/esm/templates/api/index.post.ts.hbs +111 -22
- package/lib/esm/templates/api/index.put.ts.hbs +75 -0
- package/lib/esm/templates/api/refs.ts.hbs +26 -0
- package/lib/esm/templates/filter/errorFilter.ts.hbs +10 -0
- package/lib/esm/templates/filter/sessionFilter.ts.hbs +125 -25
- package/lib/esm/templates/schema/jsonSchema.json.hbs +62 -0
- package/lib/esm/templates/service/service.ts.hbs +59 -29
- package/lib/esm/templates/service/serviceHelper.ts.hbs +38 -27
- package/lib/esm/templates/service/singletonService.ts.hbs +46 -24
- package/lib/esm/templates/store/singletonStore.ts.hbs +57 -28
- package/lib/esm/templates/store/store.ts.hbs +169 -39
- package/lib/esm/templates/store/storeHelper.ts.hbs +21 -9
- package/lib/esm/templates/type/tsType.ts.hbs +7 -3
- package/package.json +37 -22
- package/src/generate.ts +400 -0
- package/src/generators/h3.ts +125 -0
- package/src/generators/jsonSchema.ts +65 -0
- package/src/generators/server.ts +242 -0
- package/src/generators/tsType.ts +6 -0
- package/src/generators/vue/admin.ts +136 -0
- package/src/generators/vue/service.ts +76 -0
- package/src/generators/vue/store.ts +74 -0
- package/src/helpers.ts +195 -0
- package/src/index.ts +10 -0
- package/lib/cjs/generate.d.ts +0 -19
- package/lib/cjs/generate.js +0 -154
- package/lib/cjs/generators/client.d.ts +0 -8
- package/lib/cjs/generators/client.js +0 -75
- package/lib/cjs/generators/server.d.ts +0 -11
- package/lib/cjs/generators/server.js +0 -91
- package/lib/cjs/generators/tsType.d.ts +0 -3
- package/lib/cjs/generators/tsType.js +0 -4
- package/lib/cjs/generators/yup.d.ts +0 -3
- package/lib/cjs/generators/yup.js +0 -8
- package/lib/cjs/index.d.ts +0 -6
- package/lib/cjs/index.js +0 -6
- package/lib/cjs/package.json +0 -16
- package/lib/cjs/templates/api/id.delete.ts.hbs +0 -66
- package/lib/cjs/templates/api/id.get.ts.hbs +0 -38
- package/lib/cjs/templates/api/id.patch.ts.hbs +0 -51
- package/lib/cjs/templates/api/id.put.ts.hbs +0 -42
- package/lib/cjs/templates/api/index.post.ts.hbs +0 -39
- package/lib/cjs/templates/component/admin.vue.hbs +0 -493
- package/lib/cjs/templates/component/adminHelper.ts.hbs +0 -65
- package/lib/cjs/templates/component/componentHelper.d.ts +0 -3
- package/lib/cjs/templates/component/componentHelper.js +0 -53
- package/lib/cjs/templates/filter/errorFilter.ts.hbs +0 -51
- package/lib/cjs/templates/filter/sessionFilter.ts.hbs +0 -56
- package/lib/cjs/templates/service/service.ts.hbs +0 -58
- package/lib/cjs/templates/service/serviceHelper.ts.hbs +0 -97
- package/lib/cjs/templates/service/singletonService.ts.hbs +0 -49
- package/lib/cjs/templates/store/singletonStore.ts.hbs +0 -74
- package/lib/cjs/templates/store/store.ts.hbs +0 -94
- package/lib/cjs/templates/store/storeHelper.d.ts +0 -15
- package/lib/cjs/templates/store/storeHelper.js +0 -15
- package/lib/cjs/templates/store/storeHelper.ts.hbs +0 -34
- package/lib/cjs/templates/type/tsType.ts.hbs +0 -7
- package/lib/cjs/templates/validation/yup.ts.hbs +0 -39
- package/lib/esm/generators/client.d.ts +0 -8
- package/lib/esm/generators/client.js +0 -75
- package/lib/esm/generators/yup.d.ts +0 -3
- package/lib/esm/generators/yup.js +0 -8
- package/lib/esm/templates/component/admin.vue.hbs +0 -493
- package/lib/esm/templates/component/adminHelper.ts.hbs +0 -65
- package/lib/esm/templates/component/componentHelper.d.ts +0 -3
- package/lib/esm/templates/component/componentHelper.js +0 -53
- package/lib/esm/templates/store/storeHelper.d.ts +0 -15
- package/lib/esm/templates/store/storeHelper.js +0 -15
- package/lib/esm/templates/validation/yup.ts.hbs +0 -39
package/src/generate.ts
ADDED
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
import * as fs from "fs";
|
|
2
|
+
import { dirname, resolve } from "pathe";
|
|
3
|
+
import { fileURLToPath } from "url";
|
|
4
|
+
import { capitalize } from "zilla-util";
|
|
5
|
+
import {
|
|
6
|
+
isArrayType,
|
|
7
|
+
MOBILETTO_CARDINALITY_LARGE,
|
|
8
|
+
MobilettoOrmError,
|
|
9
|
+
MobilettoOrmFieldDefConfigs,
|
|
10
|
+
MobilettoOrmTypeDef,
|
|
11
|
+
MobilettoApiConfig,
|
|
12
|
+
MobilettoApiPath,
|
|
13
|
+
MobilettoOrmFieldDefConfig,
|
|
14
|
+
} from "mobiletto-orm-typedef";
|
|
15
|
+
import { HandlebarsEnv, registerHandlebarsHelpers } from "./helpers.js";
|
|
16
|
+
|
|
17
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
18
|
+
|
|
19
|
+
export const DUMMY_TYPEDEF = new MobilettoOrmTypeDef({ typeName: "dummy", fields: {} });
|
|
20
|
+
|
|
21
|
+
export const STANDARD_AUTOGEN_FILE_DISCLAIMER = "DO NOT EDIT THIS FILE. AUTO-GENERATED BY mobiletto-orm-typedef-gen";
|
|
22
|
+
export const STANDARD_AUTOGEN_OVERRIDE_DISCLAIMER =
|
|
23
|
+
"OVERRIDING AUTO-GENERATION. Retain this comment to keep autogen happy.";
|
|
24
|
+
export const MIN_DISCLAIMER_LENGTH = 12;
|
|
25
|
+
|
|
26
|
+
export type TypeDeclaration = {
|
|
27
|
+
name: string;
|
|
28
|
+
fields: Record<string, unknown>;
|
|
29
|
+
root?: boolean;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export type GenerateOptions = {
|
|
33
|
+
outfile?: string;
|
|
34
|
+
header?: string;
|
|
35
|
+
typescript?: boolean;
|
|
36
|
+
name?: string;
|
|
37
|
+
rootOnly?: boolean;
|
|
38
|
+
disclaimer?: string;
|
|
39
|
+
overrideDisclaimer?: string;
|
|
40
|
+
prepareContext?: (typeDef: MobilettoOrmTypeDef, ctx: Record<string, unknown>) => Record<string, unknown>;
|
|
41
|
+
mobilettoOrmObjectPackage?: string;
|
|
42
|
+
findApiOptsPackage?: string;
|
|
43
|
+
errorFilterImport?: string;
|
|
44
|
+
eventContextVar?: string;
|
|
45
|
+
logger?: string;
|
|
46
|
+
loggerImport?: string;
|
|
47
|
+
skipServiceHandlers?: boolean;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
const findDecls = (name: string, fields: MobilettoOrmFieldDefConfigs) => {
|
|
51
|
+
return _findDecls(name, fields, []);
|
|
52
|
+
};
|
|
53
|
+
const _findDecls = (name: string, fields: MobilettoOrmFieldDefConfigs, decls: TypeDeclaration[]) => {
|
|
54
|
+
for (const fieldName of Object.keys(fields)) {
|
|
55
|
+
const field = fields[fieldName];
|
|
56
|
+
if (field.type === "object" && field.fields && !field.tsType) {
|
|
57
|
+
const subName = name + "_" + field.name;
|
|
58
|
+
const subFields = field.fields;
|
|
59
|
+
decls.unshift({ name: subName, fields: subFields });
|
|
60
|
+
_findDecls(subName, subFields, decls);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return decls;
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
const onlyUnique = <T>(value: T, index: number, array: T[]) => array.indexOf(value) === index;
|
|
67
|
+
|
|
68
|
+
const defaultPrepareContext = (
|
|
69
|
+
typeDef: MobilettoOrmTypeDef,
|
|
70
|
+
allImports: Set<string>,
|
|
71
|
+
ctx: Record<string, unknown>,
|
|
72
|
+
): Record<string, unknown> => {
|
|
73
|
+
const fieldNames: string[] = ctx.fieldNames as string[];
|
|
74
|
+
const tsTypeImports: Record<string, string[]> = {};
|
|
75
|
+
// build the template view on copies: the generator-only properties set below must not
|
|
76
|
+
// leak onto the typedef's own field config objects (which ctx.fields points at)
|
|
77
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
78
|
+
const sourceFields = ctx.fields as Record<string, any>;
|
|
79
|
+
const viewFields: Record<string, any> = {};
|
|
80
|
+
/* eslint-enable @typescript-eslint/no-explicit-any */
|
|
81
|
+
for (const fieldName of fieldNames) {
|
|
82
|
+
viewFields[fieldName] = { ...sourceFields[fieldName] };
|
|
83
|
+
}
|
|
84
|
+
ctx.fields = viewFields;
|
|
85
|
+
for (const fieldName of fieldNames) {
|
|
86
|
+
const field = viewFields[fieldName];
|
|
87
|
+
field.optional =
|
|
88
|
+
typeof field.when === "function" ||
|
|
89
|
+
(typeof field.normalize === "function" && field.normalize.length === 0) ||
|
|
90
|
+
(!field.primary && !field.required);
|
|
91
|
+
field.typeIsBoolean = field.type === "boolean";
|
|
92
|
+
field.typeIsString = field.type === "string";
|
|
93
|
+
field.typeIsNumber = field.type === "number";
|
|
94
|
+
field.typeIsArray = isArrayType(field.type);
|
|
95
|
+
field.typeIsObject = field.type === "object";
|
|
96
|
+
if (field.typeIsArray) {
|
|
97
|
+
field.valueType = field.type.substring(0, field.type.indexOf("[]"));
|
|
98
|
+
field.arrayIndent = " ";
|
|
99
|
+
}
|
|
100
|
+
if (typeof field.default !== "undefined") {
|
|
101
|
+
field.defaultValue = JSON.stringify(field.default);
|
|
102
|
+
}
|
|
103
|
+
if (field.regex) {
|
|
104
|
+
field.regexValue = field.regex.toString();
|
|
105
|
+
}
|
|
106
|
+
if (field.values && Array.isArray(field.values) && field.values.length > 0) {
|
|
107
|
+
field.isEnum = true;
|
|
108
|
+
field.enumValues = JSON.stringify(field.values);
|
|
109
|
+
} else if (field.items && Array.isArray(field.items) && field.items.length > 0 && field.items[0].value) {
|
|
110
|
+
field.isEnum = true;
|
|
111
|
+
field.enumValues = JSON.stringify(field.items.map((i: { value: string }) => i.value));
|
|
112
|
+
}
|
|
113
|
+
if (field.when) {
|
|
114
|
+
field.hasWhen = true;
|
|
115
|
+
field.whenCode = field.when.toString();
|
|
116
|
+
if (ctx.typescript) {
|
|
117
|
+
field.whenCode = field.whenCode.replace(
|
|
118
|
+
/\(([a-z_]+)\)/i,
|
|
119
|
+
(a: string, b: string) => `(${b}: Record<string, unknown>)`,
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
// field names are extracted by regexing the function source for `v.<name>` — this only
|
|
123
|
+
// works when the parameter is named `v` and fields are plainly dereferenced; set an
|
|
124
|
+
// explicit `whenFields: string[]` on the field config to bypass the extraction
|
|
125
|
+
field.whenFieldNames =
|
|
126
|
+
field.whenFields ||
|
|
127
|
+
(Array.from(field.whenCode.matchAll(/v\.([A-Za-z\d_.\s+]+)/g)) as string[][])
|
|
128
|
+
.map((matches): string | null => (matches && matches.length > 1 ? matches[1] : null))
|
|
129
|
+
.filter((x) => x != null)
|
|
130
|
+
.map((f) => f?.replace(/\s+/, ""))
|
|
131
|
+
.map((f) => (f?.includes(".") ? f.substring(0, f.indexOf(".")) : f))
|
|
132
|
+
.filter(onlyUnique);
|
|
133
|
+
if (!field.whenFields && field.whenFieldNames.length === 0) {
|
|
134
|
+
console.warn(
|
|
135
|
+
`defaultPrepareContext: field '${fieldName}' has a 'when' function but no field names could be extracted from its source — name the parameter 'v' and use plain 'v.<field>' access, or set 'whenFields: [...]' on the field config; generated form logic will not track this field's dependencies`,
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
field.whenFieldNamesQuoted = field.whenFieldNames
|
|
139
|
+
.filter((f: string) => f !== fieldName)
|
|
140
|
+
.map((f: string) => JSON.stringify(f));
|
|
141
|
+
field.whenFieldSignature = field.whenFieldNames
|
|
142
|
+
.map((f: string) => {
|
|
143
|
+
const fld = (ctx.fields as MobilettoOrmFieldDefConfigs)[f];
|
|
144
|
+
return fld ? f + (fld.required ? "" : "?") + ": " + fld.type : f + "?: unknown";
|
|
145
|
+
})
|
|
146
|
+
.join(", ");
|
|
147
|
+
}
|
|
148
|
+
if (field.test && field.test.message && field.test.valid) {
|
|
149
|
+
field.testCode = field.test.valid.toString();
|
|
150
|
+
}
|
|
151
|
+
field.Name = capitalize(field.name);
|
|
152
|
+
field.fullName = (ctx.name !== typeDef.typeName ? ctx.name + "_" : "") + field.name;
|
|
153
|
+
field.labelName = typeof field.label === "string" ? field.label : field.fullName;
|
|
154
|
+
if (field.tsType && field.tsTypePackage) {
|
|
155
|
+
if (!(field.tsTypePackage in tsTypeImports)) {
|
|
156
|
+
tsTypeImports[field.tsTypePackage] = [];
|
|
157
|
+
}
|
|
158
|
+
const imp = field.tsType.replace(/(\[])+$/, "");
|
|
159
|
+
if (!allImports.has(imp)) {
|
|
160
|
+
allImports.add(imp);
|
|
161
|
+
tsTypeImports[field.tsTypePackage].push(imp);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
ctx.fieldNamesArray = JSON.stringify(fieldNames);
|
|
167
|
+
ctx.fieldParamsArray = fieldNames.join(",");
|
|
168
|
+
ctx.typeName = typeDef.typeName;
|
|
169
|
+
ctx.TypeName = typeDef.TypeName;
|
|
170
|
+
ctx.TypeNameType = `${typeDef.TypeName}Type`;
|
|
171
|
+
ctx.curlyOpen = "{";
|
|
172
|
+
ctx.curlyClose = "}";
|
|
173
|
+
ctx.emptyObject = "{}";
|
|
174
|
+
ctx.tsTypeImports =
|
|
175
|
+
Object.keys(tsTypeImports).length === 0
|
|
176
|
+
? undefined
|
|
177
|
+
: Object.entries(tsTypeImports).map(([tsTypePackage, tsTypes]) => ({ tsTypePackage, tsTypes }));
|
|
178
|
+
ctx.hasTextSearch = typeDef.search && typeDef.search.textSearchFields && typeDef.search.textSearchFields.length > 0;
|
|
179
|
+
if (typeDef.search && typeDef.search.refSearch) {
|
|
180
|
+
const refSearch = typeDef.search.refSearch;
|
|
181
|
+
ctx.hasRefSearch = Object.values(refSearch).filter((rs) => rs !== "disabled").length > 0;
|
|
182
|
+
if (ctx.hasRefSearch) {
|
|
183
|
+
const refSearches: Record<string, string | boolean>[] = Object.keys(refSearch)
|
|
184
|
+
.filter((rs) => refSearch[rs] !== "disabled")
|
|
185
|
+
.map((ref) => ({
|
|
186
|
+
ref,
|
|
187
|
+
Ref: capitalize(ref),
|
|
188
|
+
refType: typeDef.fields[ref].ref?.refType || "?refType?",
|
|
189
|
+
RefType: capitalize(typeDef.fields[ref].ref?.refType || "?RefType?"),
|
|
190
|
+
text: refSearch[ref] === "text",
|
|
191
|
+
select: refSearch[ref] === "select",
|
|
192
|
+
disabled: refSearch[ref] === "disabled",
|
|
193
|
+
cardinality: `${typeDef.fields[ref].ref?.cardinality}`,
|
|
194
|
+
highCardinality: typeDef.fields[ref].ref?.cardinality === MOBILETTO_CARDINALITY_LARGE,
|
|
195
|
+
}));
|
|
196
|
+
ctx.refSearches = refSearches;
|
|
197
|
+
ctx.firstRefSearch = refSearches[0];
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
ctx.hasSearch = ctx.hasTextSearch || ctx.hasRefSearch;
|
|
201
|
+
return ctx;
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
const VALID_TEMPLATE_FILE_EXT = [".ts.hbs", ".vue.hbs", ".json.hbs"];
|
|
205
|
+
const validTemplateFile = (path: string) => !!VALID_TEMPLATE_FILE_EXT.find((ext) => path.endsWith(ext));
|
|
206
|
+
|
|
207
|
+
const OPEN_CURLY_SUBST_TOKEN = ",!_OPEN__CURLY_!;";
|
|
208
|
+
const CLOSE_CURLY_SUBST_TOKEN = ",!_CLOSE__CURLY_!;";
|
|
209
|
+
const OPEN_3CURLY_SUBST_TOKEN = ",!_OPEN__3CURLY_!;";
|
|
210
|
+
const CLOSE_3CURLY_SUBST_TOKEN = ",!_CLOSE__3CURLY_!;";
|
|
211
|
+
|
|
212
|
+
const OPEN_CURLY_SUBST_REGEX = new RegExp(OPEN_CURLY_SUBST_TOKEN, "g");
|
|
213
|
+
const CLOSE_CURLY_SUBST_REGEX = new RegExp(CLOSE_CURLY_SUBST_TOKEN, "g");
|
|
214
|
+
const OPEN_3CURLY_SUBST_REGEX = new RegExp(OPEN_3CURLY_SUBST_TOKEN, "g");
|
|
215
|
+
const CLOSE_3CURLY_SUBST_REGEX = new RegExp(CLOSE_3CURLY_SUBST_TOKEN, "g");
|
|
216
|
+
|
|
217
|
+
// 4KB: large enough that a long opts.header emitted before the disclaimer cannot push the
|
|
218
|
+
// disclaimer out of the scanned window (which would make regeneration refuse its own output)
|
|
219
|
+
const DISCLAIMER_SCAN_BYTES = 4096;
|
|
220
|
+
|
|
221
|
+
export const checkFileForDisclaimer = (outfile: string, disclaimer: string): boolean => {
|
|
222
|
+
if (!fs.existsSync(outfile)) return false;
|
|
223
|
+
const buffer = Buffer.alloc(DISCLAIMER_SCAN_BYTES);
|
|
224
|
+
const fd = fs.openSync(outfile, "r");
|
|
225
|
+
const stats = fs.fstatSync(fd);
|
|
226
|
+
if (stats.isDirectory()) {
|
|
227
|
+
throw new Error(`checkFileForDisclaimer: cannot check directory: ${outfile}`);
|
|
228
|
+
}
|
|
229
|
+
fs.readSync(fd, buffer, 0, DISCLAIMER_SCAN_BYTES, 0);
|
|
230
|
+
fs.closeSync(fd);
|
|
231
|
+
return buffer.toString().includes(disclaimer);
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
export const generate = (
|
|
235
|
+
apiPath: MobilettoApiPath,
|
|
236
|
+
parentPaths: MobilettoApiPath[],
|
|
237
|
+
templatePath: string,
|
|
238
|
+
opts?: GenerateOptions,
|
|
239
|
+
ctx?: Record<string, object | string | number | null | undefined>,
|
|
240
|
+
): string => {
|
|
241
|
+
registerHandlebarsHelpers();
|
|
242
|
+
if (!ctx) ctx = {};
|
|
243
|
+
const typeDef: MobilettoOrmTypeDef = apiPath.typeDef;
|
|
244
|
+
const apiConfig: MobilettoApiConfig = apiPath.apiConfig;
|
|
245
|
+
const typescript = !opts || opts.typescript !== false;
|
|
246
|
+
const mobilettoOrmObjectPackage = opts?.mobilettoOrmObjectPackage || "mobiletto-orm-typedef";
|
|
247
|
+
ctx.logger = opts?.logger || "logger";
|
|
248
|
+
ctx.loggerImport = opts?.loggerImport || "../utils/logger.js";
|
|
249
|
+
const disclaimer = opts?.disclaimer ? opts.disclaimer : STANDARD_AUTOGEN_FILE_DISCLAIMER;
|
|
250
|
+
if (disclaimer.length < MIN_DISCLAIMER_LENGTH) {
|
|
251
|
+
throw new Error(
|
|
252
|
+
`generate: disclaimer too short (${disclaimer.length} chars, must be at least ${MIN_DISCLAIMER_LENGTH} chars): '${disclaimer}'`,
|
|
253
|
+
);
|
|
254
|
+
}
|
|
255
|
+
const overrideDisclaimer = opts?.overrideDisclaimer
|
|
256
|
+
? opts.overrideDisclaimer
|
|
257
|
+
: STANDARD_AUTOGEN_OVERRIDE_DISCLAIMER;
|
|
258
|
+
if (overrideDisclaimer.length < MIN_DISCLAIMER_LENGTH) {
|
|
259
|
+
throw new Error(
|
|
260
|
+
`generate: overrideDisclaimer too short (${overrideDisclaimer.length} chars, must be at least ${MIN_DISCLAIMER_LENGTH} chars): '${overrideDisclaimer}'`,
|
|
261
|
+
);
|
|
262
|
+
}
|
|
263
|
+
const rootOnly = opts?.rootOnly === true;
|
|
264
|
+
const name = opts?.name ? opts.name : typeDef.typeName;
|
|
265
|
+
const rootDecl = { name, fields: typeDef.fields, root: true };
|
|
266
|
+
const decls = rootOnly ? [rootDecl] : [...findDecls(name, typeDef.fields), rootDecl];
|
|
267
|
+
const eventContextVar = opts?.eventContextVar || "event";
|
|
268
|
+
let allData = "";
|
|
269
|
+
let first = true;
|
|
270
|
+
const parentPathsWithRefs = [];
|
|
271
|
+
for (let i = parentPaths.length - 1; i >= 0; i--) {
|
|
272
|
+
const parent = parentPaths[i];
|
|
273
|
+
const parentTypeDef = i === parentPaths.length - 1 ? typeDef : parentPaths[i + 1].typeDef;
|
|
274
|
+
parentPathsWithRefs.unshift({
|
|
275
|
+
...parent,
|
|
276
|
+
refField: apiPath.refField || parentTypeDef.refFieldPath(parent.typeDef.typeName),
|
|
277
|
+
typeName: parent.typeDef.typeName,
|
|
278
|
+
TypeName: parent.typeDef.TypeName,
|
|
279
|
+
TypeNameType: `${parent.typeDef.TypeName}Type`,
|
|
280
|
+
shortId: parent.typeDef.shortId,
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
const allImports: Set<string> = new Set<string>();
|
|
284
|
+
while (decls.length > 0) {
|
|
285
|
+
const decl = decls.pop();
|
|
286
|
+
if (!decl) break;
|
|
287
|
+
const typeContext = defaultPrepareContext(typeDef, allImports, {
|
|
288
|
+
typeDef,
|
|
289
|
+
apiConfig,
|
|
290
|
+
parentPaths: parentPathsWithRefs,
|
|
291
|
+
parentRef: parentPathsWithRefs.length > 0 ? parentPathsWithRefs[parentPathsWithRefs.length - 1] : undefined,
|
|
292
|
+
parentRefField:
|
|
293
|
+
parentPathsWithRefs.length > 0
|
|
294
|
+
? parentPathsWithRefs[parentPathsWithRefs.length - 1].refField
|
|
295
|
+
: undefined,
|
|
296
|
+
parentRefShortId:
|
|
297
|
+
parentPathsWithRefs.length > 0
|
|
298
|
+
? parentPathsWithRefs[parentPathsWithRefs.length - 1].typeDef.shortId
|
|
299
|
+
: undefined,
|
|
300
|
+
parentRefIdParam:
|
|
301
|
+
parentPathsWithRefs.length > 0
|
|
302
|
+
? parentPathsWithRefs[parentPathsWithRefs.length - 1].typeDef.idParam
|
|
303
|
+
: undefined,
|
|
304
|
+
name: decl.name,
|
|
305
|
+
Name: capitalize(decl.name),
|
|
306
|
+
fields: decl.fields,
|
|
307
|
+
fieldNames: Object.keys(decl.fields),
|
|
308
|
+
requiredFields: (Object.values(decl.fields) as MobilettoOrmFieldDefConfig[])
|
|
309
|
+
.filter((f) => f.required)
|
|
310
|
+
.map((f) => f.name),
|
|
311
|
+
disclaimer: decls.length > 0 ? null : disclaimer,
|
|
312
|
+
header: decls.length > 0 ? null : opts?.header,
|
|
313
|
+
first,
|
|
314
|
+
root: decl.root || false,
|
|
315
|
+
typescript,
|
|
316
|
+
mobilettoOrmObjectPackage,
|
|
317
|
+
eventContextVar,
|
|
318
|
+
skipServiceHandlers: opts?.skipServiceHandlers,
|
|
319
|
+
...ctx,
|
|
320
|
+
});
|
|
321
|
+
const preparedContext = opts?.prepareContext ? opts.prepareContext(typeDef, typeContext) : typeContext;
|
|
322
|
+
first = false;
|
|
323
|
+
typeContext.ctx = typeContext;
|
|
324
|
+
// sanity, scrub templatePath; we should only ever read template files
|
|
325
|
+
const lastSlash = templatePath.lastIndexOf("/");
|
|
326
|
+
if (lastSlash === -1 || lastSlash === templatePath.length - 1) {
|
|
327
|
+
throw new MobilettoOrmError(`invalid template path: ${templatePath}`);
|
|
328
|
+
}
|
|
329
|
+
if (templatePath.split("/").includes("..")) {
|
|
330
|
+
throw new MobilettoOrmError(`invalid template path: ${templatePath}`);
|
|
331
|
+
}
|
|
332
|
+
const endPath =
|
|
333
|
+
templatePath.substring(0, lastSlash).replace(/[^A-Z0-9_./-]/gi, "") + templatePath.substring(lastSlash);
|
|
334
|
+
if (endPath !== templatePath) {
|
|
335
|
+
throw new MobilettoOrmError(`invalid template path: ${templatePath}`);
|
|
336
|
+
}
|
|
337
|
+
if (!validTemplateFile(templatePath)) {
|
|
338
|
+
throw new MobilettoOrmError(`invalid template path: ${templatePath}`);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
const preContext: Record<string, string> = {};
|
|
342
|
+
// the package-local candidate must resolve under __dirname; anything else (e.g. a
|
|
343
|
+
// caller-supplied absolute path) is only readable via the explicit fallback below
|
|
344
|
+
const localTemplate = resolve(__dirname, templatePath);
|
|
345
|
+
let template;
|
|
346
|
+
try {
|
|
347
|
+
if (!localTemplate.startsWith(__dirname + "/")) {
|
|
348
|
+
throw new MobilettoOrmError(`not a package-local template: ${templatePath}`);
|
|
349
|
+
}
|
|
350
|
+
template = fs.readFileSync(localTemplate).toString("utf8");
|
|
351
|
+
if (template.includes("[[[include ")) preContext.includeBaseDir = dirname(localTemplate);
|
|
352
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
353
|
+
} catch (e) {
|
|
354
|
+
try {
|
|
355
|
+
template = fs.readFileSync(templatePath).toString("utf8");
|
|
356
|
+
if (template.includes("[[[include ")) preContext.includeBaseDir = dirname(templatePath);
|
|
357
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
358
|
+
} catch (e2) {
|
|
359
|
+
throw new MobilettoOrmError(`template path not found: ${templatePath}`);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
if (preContext.includeBaseDir) {
|
|
364
|
+
// first replace [[[include some-file]]] with included content
|
|
365
|
+
const preTemplate = template
|
|
366
|
+
.replace(/\{\{\{/g, OPEN_3CURLY_SUBST_TOKEN)
|
|
367
|
+
.replace(/}}}/g, CLOSE_3CURLY_SUBST_TOKEN)
|
|
368
|
+
.replace(/\{\{/g, OPEN_CURLY_SUBST_TOKEN)
|
|
369
|
+
.replace(/}}/g, CLOSE_CURLY_SUBST_TOKEN)
|
|
370
|
+
.replace(/\[\[\[/g, "{{{")
|
|
371
|
+
.replace(/]]]/g, "}}}");
|
|
372
|
+
// run template to process includes, then transform back to normal
|
|
373
|
+
template = HandlebarsEnv.compile(preTemplate)(preContext)
|
|
374
|
+
.replace(OPEN_3CURLY_SUBST_REGEX, "{{{")
|
|
375
|
+
.replace(CLOSE_3CURLY_SUBST_REGEX, "}}}")
|
|
376
|
+
.replace(OPEN_CURLY_SUBST_REGEX, "{{")
|
|
377
|
+
.replace(CLOSE_CURLY_SUBST_REGEX, "}}");
|
|
378
|
+
}
|
|
379
|
+
const data = HandlebarsEnv.compile(template)(preparedContext);
|
|
380
|
+
allData = data + allData;
|
|
381
|
+
}
|
|
382
|
+
if (opts?.outfile) {
|
|
383
|
+
const outDir = dirname(opts.outfile);
|
|
384
|
+
if (!fs.existsSync(outDir)) {
|
|
385
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
386
|
+
}
|
|
387
|
+
if (fs.existsSync(opts.outfile)) {
|
|
388
|
+
if (checkFileForDisclaimer(opts.outfile, disclaimer)) {
|
|
389
|
+
fs.writeFileSync(opts.outfile, allData);
|
|
390
|
+
} else if (!checkFileForDisclaimer(opts.outfile, overrideDisclaimer)) {
|
|
391
|
+
throw new Error(
|
|
392
|
+
`File of unknown provenance (missing autogen disclaimer and manual overrideDisclaimer, not overwriting): ${opts.outfile}`,
|
|
393
|
+
);
|
|
394
|
+
}
|
|
395
|
+
} else {
|
|
396
|
+
fs.writeFileSync(opts.outfile, allData);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
return allData;
|
|
400
|
+
};
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import fs from "fs";
|
|
2
|
+
import path from "path";
|
|
3
|
+
import { fileURLToPath } from "url";
|
|
4
|
+
import { GenerateOptions, STANDARD_AUTOGEN_FILE_DISCLAIMER } from "../generate.js";
|
|
5
|
+
import { registerHandlebarsHelpers } from "../helpers.js";
|
|
6
|
+
import { basename } from "pathe";
|
|
7
|
+
|
|
8
|
+
interface ImportLine {
|
|
9
|
+
importName: string;
|
|
10
|
+
importPath: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
interface RouteDefinition {
|
|
14
|
+
route: string;
|
|
15
|
+
method: string;
|
|
16
|
+
importName: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
interface TemplateContext {
|
|
20
|
+
imports: ImportLine[];
|
|
21
|
+
routes: RouteDefinition[];
|
|
22
|
+
disclaimer?: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Convert a bracketed segment "[something]" to H3 param ":something"
|
|
26
|
+
const toParam = (segment: string): string =>
|
|
27
|
+
segment.startsWith("[") && segment.endsWith("]") ? ":" + segment.slice(1, -1) : segment;
|
|
28
|
+
|
|
29
|
+
// From a file path like "account/[acct_id]/index.delete.ts",
|
|
30
|
+
// extract: route = "/account/:acct_id", method = "delete"
|
|
31
|
+
const parseRouteAndMethod = (filePath: string): { route: string; method: string } => {
|
|
32
|
+
const base: string = path.basename(filePath, ".ts");
|
|
33
|
+
const [maybeName, maybeMethod] = base.split(".");
|
|
34
|
+
const fileSegment: string = maybeName !== "index" ? maybeName : "";
|
|
35
|
+
const method: string = (maybeMethod || "").toLowerCase();
|
|
36
|
+
const dirs: string[] = path.dirname(filePath).split(path.sep).map(toParam);
|
|
37
|
+
if (fileSegment) dirs.push(toParam(fileSegment));
|
|
38
|
+
const route: string = "/" + dirs.join("/");
|
|
39
|
+
return { route, method };
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
// Turn "account/[acct_id]/index.delete.ts" into a variable-friendly import name
|
|
43
|
+
const generateImportName = (filePath: string): string =>
|
|
44
|
+
filePath
|
|
45
|
+
.replace(/\.ts$/, "")
|
|
46
|
+
.replace(/[^a-zA-Z0-9]/g, "_")
|
|
47
|
+
.replace(/__/g, "_")
|
|
48
|
+
.replace(/_index_/g, "_");
|
|
49
|
+
|
|
50
|
+
// Recursively find .ts files within a directory
|
|
51
|
+
const scanRoutes = (dir: string): string[] => {
|
|
52
|
+
let results: string[] = [];
|
|
53
|
+
const entries = fs.readdirSync(dir);
|
|
54
|
+
|
|
55
|
+
entries.forEach((entry) => {
|
|
56
|
+
const fullPath: string = path.join(dir, entry);
|
|
57
|
+
const stat = fs.statSync(fullPath);
|
|
58
|
+
if (stat.isDirectory()) {
|
|
59
|
+
results = results.concat(scanRoutes(fullPath));
|
|
60
|
+
} else if (entry.endsWith(".ts")) {
|
|
61
|
+
results.push(fullPath);
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
return results;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
69
|
+
const __dirname = path.dirname(__filename);
|
|
70
|
+
const templatePath = path.join(__dirname, "../templates/api/h3.ts.hbs");
|
|
71
|
+
|
|
72
|
+
const compareRoutes = (a: string, b: string) => a.replace(/\[/g, "~").localeCompare(b.replace(/\[/g, "~"));
|
|
73
|
+
|
|
74
|
+
const METHOD_ORDER = ["GET", "POST", "PUT", "PATCH", "DELETE"];
|
|
75
|
+
|
|
76
|
+
const compareMethods = (r1: RouteDefinition, r2: RouteDefinition) =>
|
|
77
|
+
METHOD_ORDER.indexOf(r1.method.toUpperCase()) - METHOD_ORDER.indexOf(r2.method.toUpperCase());
|
|
78
|
+
|
|
79
|
+
export type GenerateH3Options = {
|
|
80
|
+
modulePrefix?: string;
|
|
81
|
+
routePrefix?: string;
|
|
82
|
+
exclude?: string | string[];
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
// Build final router file content from the Handlebars template
|
|
86
|
+
export const generateH3 = (rootDir: string, opts?: GenerateOptions, genOpts?: GenerateH3Options): string => {
|
|
87
|
+
const ex = genOpts?.exclude;
|
|
88
|
+
const exclude = ex ? (Array.isArray(ex) ? ex : [ex]) : [];
|
|
89
|
+
const disclaimer = opts?.disclaimer ? opts.disclaimer : STANDARD_AUTOGEN_FILE_DISCLAIMER;
|
|
90
|
+
const templateSource: string = fs.readFileSync(templatePath, "utf-8");
|
|
91
|
+
// the template uses custom helpers (ALL_CAPS), so compile with the registered environment
|
|
92
|
+
const template = registerHandlebarsHelpers().compile(templateSource);
|
|
93
|
+
const prefix = genOpts?.modulePrefix || "";
|
|
94
|
+
const rp = genOpts?.routePrefix || "";
|
|
95
|
+
|
|
96
|
+
const files: string[] = scanRoutes(rootDir);
|
|
97
|
+
const context: TemplateContext = { imports: [], routes: [], disclaimer };
|
|
98
|
+
|
|
99
|
+
files
|
|
100
|
+
.filter((f) => !exclude || !exclude.includes(basename(f)))
|
|
101
|
+
.forEach((absolutePath) => {
|
|
102
|
+
const relativeFromRoot = path.relative(rootDir, absolutePath);
|
|
103
|
+
const { route, method } = parseRouteAndMethod(relativeFromRoot);
|
|
104
|
+
const importName = generateImportName(relativeFromRoot);
|
|
105
|
+
// const importPath = "./" + path.relative(__dirname, absolutePath).replace(/\\/g, "/");
|
|
106
|
+
|
|
107
|
+
const routePfx1 = rp.startsWith("./") ? rp.substring(1) : rp;
|
|
108
|
+
const routePfx = routePfx1.endsWith("/") ? routePfx1.substring(0, routePfx1.length - 1) : routePfx1;
|
|
109
|
+
context.imports.push({ importName, importPath: prefix + relativeFromRoot.replace(/\.ts$/, ".js") });
|
|
110
|
+
context.routes.push({ route: routePfx + route, method, importName });
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
context.routes.sort((r1, r2) => {
|
|
114
|
+
const diff = compareRoutes(r1.route, r2.route);
|
|
115
|
+
return diff !== 0 ? diff : compareMethods(r1, r2);
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
const allData = template(context);
|
|
119
|
+
|
|
120
|
+
if (opts?.outfile) {
|
|
121
|
+
fs.writeFileSync(opts.outfile, allData);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return allData;
|
|
125
|
+
};
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { MobilettoOrmFieldDefConfig, MobilettoOrmTypeDef } from "mobiletto-orm-typedef";
|
|
2
|
+
import { generate, GenerateOptions, STANDARD_AUTOGEN_FILE_DISCLAIMER } from "../generate.js";
|
|
3
|
+
|
|
4
|
+
export const generateJsonSchema = (typeDef: MobilettoOrmTypeDef, opts?: GenerateOptions): string => {
|
|
5
|
+
const customOpts: GenerateOptions = {
|
|
6
|
+
...opts,
|
|
7
|
+
typescript: false, // This is JSON, not TypeScript
|
|
8
|
+
disclaimer: opts?.disclaimer ? opts.disclaimer : STANDARD_AUTOGEN_FILE_DISCLAIMER,
|
|
9
|
+
prepareContext: (typeDef: MobilettoOrmTypeDef, ctx: Record<string, unknown>): Record<string, unknown> => {
|
|
10
|
+
// Collect required fields for each type
|
|
11
|
+
const requiredFields: string[] = [];
|
|
12
|
+
const subTypes: Array<{ name: string; fields: unknown; requiredFields: string[] }> = [];
|
|
13
|
+
|
|
14
|
+
// Process main type required fields
|
|
15
|
+
for (const [fieldName, field] of Object.entries(typeDef.fields)) {
|
|
16
|
+
if (field.required === true || field.primary === true) {
|
|
17
|
+
requiredFields.push(fieldName);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Process nested object types
|
|
22
|
+
const processNestedTypes = (name: string, fields: Record<string, unknown>, parentName?: string) => {
|
|
23
|
+
for (const [fieldName, field] of Object.entries(fields) as [string, MobilettoOrmFieldDefConfig][]) {
|
|
24
|
+
if (field.type === "object" && field.fields && !field.tsType) {
|
|
25
|
+
const subTypeName = parentName ? `${parentName}_${fieldName}` : `${name}_${fieldName}`;
|
|
26
|
+
const subRequiredFields: string[] = [];
|
|
27
|
+
|
|
28
|
+
for (const [subFieldName, subField] of Object.entries(field.fields) as [
|
|
29
|
+
string,
|
|
30
|
+
MobilettoOrmFieldDefConfig,
|
|
31
|
+
][]) {
|
|
32
|
+
if (subField.required === true || subField.primary === true) {
|
|
33
|
+
subRequiredFields.push(subFieldName);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
subTypes.push({
|
|
38
|
+
name: subTypeName,
|
|
39
|
+
fields: field.fields,
|
|
40
|
+
requiredFields: subRequiredFields,
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
// Recursively process nested types
|
|
44
|
+
processNestedTypes(subTypeName, field.fields, subTypeName);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
processNestedTypes(typeDef.typeName, typeDef.fields);
|
|
50
|
+
|
|
51
|
+
return {
|
|
52
|
+
...ctx,
|
|
53
|
+
requiredFields: requiredFields.length > 0 ? requiredFields : undefined,
|
|
54
|
+
subTypes: subTypes.length > 0 ? subTypes : undefined,
|
|
55
|
+
};
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
return generate(
|
|
60
|
+
{ typeDef, apiConfig: typeDef.apiConfig || {} },
|
|
61
|
+
[],
|
|
62
|
+
"templates/schema/jsonSchema.json.hbs",
|
|
63
|
+
customOpts,
|
|
64
|
+
);
|
|
65
|
+
};
|