hekireki 0.50.0 → 0.52.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 +115 -0
- package/dist/bin/activerecord.js +1 -1
- package/dist/bin/ajv.js +1 -1
- package/dist/bin/arktype.js +1 -1
- package/dist/bin/atlas.js +1 -1
- package/dist/bin/django.js +1 -1
- package/dist/bin/docs.js +1 -1
- package/dist/bin/drizzle.js +1 -1
- package/dist/bin/ecto.js +1 -1
- package/dist/bin/efcore.js +1 -1
- package/dist/bin/effect.js +1 -1
- package/dist/bin/eloquent.js +1 -1
- package/dist/bin/er.js +1 -1
- package/dist/bin/exposed.js +1 -1
- package/dist/bin/gorm.js +1 -1
- package/dist/bin/hekireki.js +18 -12
- package/dist/bin/kysely.js +1 -1
- package/dist/bin/openapi.js +1 -1
- package/dist/bin/pydantic.js +1 -1
- package/dist/bin/sea-orm.js +1 -1
- package/dist/bin/seed.js +1 -1
- package/dist/bin/sqlalchemy.js +1 -1
- package/dist/bin/typebox.js +1 -1
- package/dist/bin/valibot.js +1 -1
- package/dist/bin/zod-openapi-hono.d.ts +1 -0
- package/dist/bin/zod-openapi-hono.js +5 -0
- package/dist/bin/zod.js +1 -1
- package/dist/{bin-CPGRsAFR.js → bin-BcqPhgiX.js} +1149 -65
- package/dist/{discover-BOxkoGMk.js → discover-BKlX-LLS.js} +44 -34
- package/dist/{emit-CEF3yPYX.js → emit-BSQAIFiF.js} +2 -2
- package/dist/file-DOGnu_Q2.js +190 -0
- package/dist/{migrate-DMq3xNH-.js → migrate-BS6d_8aA.js} +4 -4
- package/dist/{native-engine-CY0OVgi3.js → native-engine-DcZUEqO8.js} +3 -3
- package/dist/{plan-5FxkaGBO.js → plan-BMypogKp.js} +323 -152
- package/dist/{run-Bs1aLLKy.js → run-BYq7BEVd.js} +6 -6
- package/dist/{schema-B_l4tAqI.js → schema-B7beUJic.js} +93 -49
- package/dist/{sql-DFjtK_8B.js → sql-BwL2BncN.js} +24 -24
- package/dist/{start-B9nw7W-E.js → start-s1j4PqUM.js} +12 -10
- package/package.json +16 -7
- package/dist/file-BAVQ-zst.js +0 -71
|
@@ -1,17 +1,123 @@
|
|
|
1
|
-
import { c as removePath, o as readDirectory, t as exists } from "./file-
|
|
2
|
-
import { A as
|
|
3
|
-
import { n as emitMany, r as emitRaw, t as emit } from "./emit-
|
|
4
|
-
import { a as makeOfflineSchemaEngineAdapter, c as makeSchema, d as erRelations, f as inferredERRelations, i as openSchemaEngine, l as annotatedERRelations, n as openNativeSchemaEngine, r as engineCommand, t as findSchemaEngineBinary, u as erKey } from "./native-engine-
|
|
1
|
+
import { c as removePath, o as readDirectory, s as readFile, t as exists, u as writeFile } from "./file-DOGnu_Q2.js";
|
|
2
|
+
import { $ as stripAnnotations, A as relationEnds, B as getStrings, C as isListDefault, D as manyToManyRelations, E as lengthArg, F as constraintName, H as indexPrefix, I as docBlockLines, J as makePascalCase, K as isSameList, L as extractObjectType, M as tableName, N as uuidDefaultVersion, O as primaryKeyFields$1, Q as schemaFromFields, R as getBool, S as isJoinSideA, T as isUlidDefault, U as isAnnotationLine, V as groupByModel, W as isFields, X as makeValidationExtractor, Y as makeSnakeCase, _ as fieldColumn, a as schemaText, b as isFunctionDefault, et as fmt, g as columnName, h as backRelation, i as readSchemaFiles, j as scalarFields, k as referentialActions, m as formatSql, q as lowerFirst, t as dialectOf, tt as fmtMarkdown, v as implicitJoinTables, w as isNowDefault$1, x as isImplicitManyToMany, y as isAutoincrement, z as getString } from "./schema-B7beUJic.js";
|
|
3
|
+
import { n as emitMany, r as emitRaw, t as emit } from "./emit-BSQAIFiF.js";
|
|
4
|
+
import { a as makeOfflineSchemaEngineAdapter, c as makeSchema, d as erRelations, f as inferredERRelations, i as openSchemaEngine, l as annotatedERRelations, n as openNativeSchemaEngine, r as engineCommand, t as findSchemaEngineBinary, u as erKey } from "./native-engine-DcZUEqO8.js";
|
|
5
5
|
import { a as splitStatements, t as MigrateConfigError } from "./errors-fAN1Og-7.js";
|
|
6
6
|
import { createRequire } from "node:module";
|
|
7
7
|
import { Data, Effect } from "effect";
|
|
8
8
|
import path from "node:path";
|
|
9
|
+
import { pathToFileURL } from "node:url";
|
|
9
10
|
import { layer } from "@effect/platform-node/NodeFileSystem";
|
|
10
11
|
import pkg from "@prisma/generator-helper";
|
|
11
12
|
import { graphlib, layout } from "@dagrejs/dagre";
|
|
12
13
|
import * as z from "zod";
|
|
13
14
|
import { Resvg } from "@resvg/resvg-js";
|
|
14
|
-
import {
|
|
15
|
+
import { parseSync } from "oxc-parser";
|
|
16
|
+
// src/constants/auth.ts
|
|
17
|
+
/**
|
|
18
|
+
* The kinds of `auth` the generator writes a module for: `jwt` (HS256 with `JWT_SECRET`), `jwks`
|
|
19
|
+
* (an asymmetric signature checked with the keys an issuer publishes at `JWKS_URI`) and
|
|
20
|
+
* `cloudflare-access` (the token Cloudflare Access puts in `Cf-Access-Jwt-Assertion`).
|
|
21
|
+
*
|
|
22
|
+
* Hekireki's own, stable: a kind joins the list with its module. The modules build on Hono's
|
|
23
|
+
* `hono/jwt` and `hono/jwk`; when hono is upgraded, check that `jwt()`, `jwk()` and
|
|
24
|
+
* `verifyWithJwks()` still take `verification` with `iss` and `aud`, and that `verify` still
|
|
25
|
+
* checks `exp` only when a token has it (`hono/dist/utils/jwt/jwt.js`), which is why the modules
|
|
26
|
+
* require it themselves.
|
|
27
|
+
*
|
|
28
|
+
* The `cloudflare-access` module names what Cloudflare owns: the header `Cf-Access-Jwt-Assertion`,
|
|
29
|
+
* the keys at `<team domain>/cdn-cgi/access/certs`, RS256, the team domain as `iss` and the
|
|
30
|
+
* Application Audience tag as `aud`. If Cloudflare changes one, check its guide "Validate JWTs"
|
|
31
|
+
* (developers.cloudflare.com, Cloudflare One, Access) against the module.
|
|
32
|
+
*/
|
|
33
|
+
const AUTH_KINDS = [
|
|
34
|
+
"jwt",
|
|
35
|
+
"jwks",
|
|
36
|
+
"cloudflare-access"
|
|
37
|
+
];
|
|
38
|
+
// src/constants/diagram.ts
|
|
39
|
+
const EDGE_LABEL_FONT_SIZE = 9.5;
|
|
40
|
+
/**
|
|
41
|
+
* Glyph advance as a fraction of the font size, for the monospace face captions and field rows
|
|
42
|
+
* are set in: what a label is measured, right-aligned and truncated by.
|
|
43
|
+
*/
|
|
44
|
+
const MONO_ADVANCE = .6;
|
|
45
|
+
const PALETTES = {
|
|
46
|
+
light: {
|
|
47
|
+
canvas: "#f7f8fb",
|
|
48
|
+
surface: "#ffffff",
|
|
49
|
+
ink: "#16181f",
|
|
50
|
+
muted: "#6b7084",
|
|
51
|
+
faint: "#9a9fb3",
|
|
52
|
+
lineStrong: "#cfd3e0",
|
|
53
|
+
accent: "#4f46e5",
|
|
54
|
+
node: "#1f2233",
|
|
55
|
+
nodeText: "#f4f5fa",
|
|
56
|
+
edge: "#9095ab",
|
|
57
|
+
dots: "#d4d4dc",
|
|
58
|
+
key: "#b45309",
|
|
59
|
+
unique: "#0f766e",
|
|
60
|
+
enumeration: "#7c3aed"
|
|
61
|
+
},
|
|
62
|
+
dark: {
|
|
63
|
+
canvas: "#0f1117",
|
|
64
|
+
surface: "#171a23",
|
|
65
|
+
ink: "#e6e8ef",
|
|
66
|
+
muted: "#9aa0b4",
|
|
67
|
+
faint: "#6b7189",
|
|
68
|
+
lineStrong: "#343a4a",
|
|
69
|
+
accent: "#7c74ff",
|
|
70
|
+
node: "#2a2f45",
|
|
71
|
+
nodeText: "#f4f5fa",
|
|
72
|
+
edge: "#6b7189",
|
|
73
|
+
dots: "#2a2f3d",
|
|
74
|
+
key: "#fbbf24",
|
|
75
|
+
unique: "#5eead4",
|
|
76
|
+
enumeration: "#c4b5fd"
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
// src/constants/zod-openapi-hono.ts
|
|
80
|
+
/**
|
|
81
|
+
* The rows a `GET /{resource}` answers: `limit` of them (20 when it is not given, never more than
|
|
82
|
+
* 100) after `offset`, so no request makes the app read a whole table.
|
|
83
|
+
*
|
|
84
|
+
* Hekireki's own, stable: the numbers are written into each document and route, where a user who
|
|
85
|
+
* needs others changes them.
|
|
86
|
+
*/
|
|
87
|
+
const LIST_LIMIT = {
|
|
88
|
+
default: 20,
|
|
89
|
+
max: 100
|
|
90
|
+
};
|
|
91
|
+
/** The response header that carries how many rows a list has in all, `limit` and `offset` aside. */
|
|
92
|
+
const TOTAL_COUNT_HEADER = "X-Total-Count";
|
|
93
|
+
/**
|
|
94
|
+
* The `@default` functions whose value the database or Prisma makes: a field with one of them is
|
|
95
|
+
* the server's to fill, so neither a `POST` nor a `PATCH` takes it (`@updatedAt` neither).
|
|
96
|
+
*
|
|
97
|
+
* May change with a Prisma release that adds a function (`ulid()` and `nanoid()` came in 5.x):
|
|
98
|
+
* when Prisma is upgraded, check the attribute functions of its schema reference, the `name` a
|
|
99
|
+
* DMMF field's `default` has for each.
|
|
100
|
+
*/
|
|
101
|
+
const GENERATED_DEFAULTS = /* @__PURE__ */ new Set([
|
|
102
|
+
"autoincrement",
|
|
103
|
+
"sequence",
|
|
104
|
+
"now",
|
|
105
|
+
"uuid",
|
|
106
|
+
"cuid",
|
|
107
|
+
"ulid",
|
|
108
|
+
"nanoid",
|
|
109
|
+
"dbgenerated"
|
|
110
|
+
]);
|
|
111
|
+
/**
|
|
112
|
+
* The `///` lines that keep a field from the API: `@api.hidden` neither answers nor takes it (a
|
|
113
|
+
* password hash), `@api.readonly` answers it and never takes it (a role the app grants).
|
|
114
|
+
*
|
|
115
|
+
* Hekireki's own, stable.
|
|
116
|
+
*/
|
|
117
|
+
const API_ACCESS_ANNOTATIONS = {
|
|
118
|
+
hidden: "@api.hidden",
|
|
119
|
+
readonly: "@api.readonly"
|
|
120
|
+
};
|
|
15
121
|
// src/utils/active-support.ts
|
|
16
122
|
const IRREGULARS$1 = [
|
|
17
123
|
["person", "people"],
|
|
@@ -1973,6 +2079,8 @@ function activeRecordModelFiles(models, enums, provider) {
|
|
|
1973
2079
|
var GeneratorConfigError = class extends Data.TaggedError("GeneratorConfigError") {};
|
|
1974
2080
|
/** The project has no query compiler hekireki can load, or it refused the schema. */
|
|
1975
2081
|
var QueryCompilerError = class extends Data.TaggedError("QueryCompilerError") {};
|
|
2082
|
+
/** Hono Takibi is not installed, or refused the document or the files it was to write. */
|
|
2083
|
+
var HonoTakibiError = class extends Data.TaggedError("HonoTakibiError") {};
|
|
1976
2084
|
// src/core/output.ts
|
|
1977
2085
|
/**
|
|
1978
2086
|
* The `output` the generator block names. Without one Prisma would write beside the schema, so
|
|
@@ -2033,9 +2141,7 @@ function validationSchemas(models, type, config) {
|
|
|
2033
2141
|
name: model.name,
|
|
2034
2142
|
fields: model.fields
|
|
2035
2143
|
}));
|
|
2036
|
-
const
|
|
2037
|
-
const annotation = config.extractValidation(field.documentation);
|
|
2038
|
-
if (annotation !== null) return annotation;
|
|
2144
|
+
const resolveElement = (field) => {
|
|
2039
2145
|
if (config.typeMapping) {
|
|
2040
2146
|
const mapped = config.typeMapping[field.type];
|
|
2041
2147
|
if (mapped) return mapped;
|
|
@@ -2046,6 +2152,13 @@ function validationSchemas(models, type, config) {
|
|
|
2046
2152
|
}
|
|
2047
2153
|
return null;
|
|
2048
2154
|
};
|
|
2155
|
+
const resolveValidation = (field) => {
|
|
2156
|
+
const annotation = config.extractValidation(field.documentation);
|
|
2157
|
+
if (annotation !== null) return annotation;
|
|
2158
|
+
const element = resolveElement(field);
|
|
2159
|
+
if (element === null) return null;
|
|
2160
|
+
return field.isList ? config.wrapList(element) : element;
|
|
2161
|
+
};
|
|
2049
2162
|
const modelFields = modelInfos.map((model) => model.fields.map((field) => ({
|
|
2050
2163
|
documentation: model.documentation,
|
|
2051
2164
|
modelName: model.name,
|
|
@@ -2087,6 +2200,9 @@ function makeAjvInfer(modelName) {
|
|
|
2087
2200
|
function makeAjvEnumExpression(values) {
|
|
2088
2201
|
return `{ enum: [${values.map((v) => `'${v}'`).join(", ")}] as const }`;
|
|
2089
2202
|
}
|
|
2203
|
+
function makeAjvListExpression(element) {
|
|
2204
|
+
return `{ type: 'array' as const, items: ${element} }`;
|
|
2205
|
+
}
|
|
2090
2206
|
const PRISMA_TO_AJV = {
|
|
2091
2207
|
String: "{ type: 'string' as const }",
|
|
2092
2208
|
Int: "{ type: 'integer' as const }",
|
|
@@ -2120,7 +2236,8 @@ function ajvSchemaCode(models, type, enums) {
|
|
|
2120
2236
|
schemas: makeAjvSchemas,
|
|
2121
2237
|
typeMapping: PRISMA_TO_AJV,
|
|
2122
2238
|
enums,
|
|
2123
|
-
formatEnum: makeAjvEnumExpression
|
|
2239
|
+
formatEnum: makeAjvEnumExpression,
|
|
2240
|
+
wrapList: makeAjvListExpression
|
|
2124
2241
|
});
|
|
2125
2242
|
}
|
|
2126
2243
|
// src/utils/extract-relations.ts
|
|
@@ -2167,6 +2284,11 @@ function makeArktypeProperties(fields) {
|
|
|
2167
2284
|
function makeArktypeEnumExpression(values) {
|
|
2168
2285
|
return `"${values.map((v) => `'${v}'`).join(" | ")}"`;
|
|
2169
2286
|
}
|
|
2287
|
+
/** `"string"` → `"string[]"`, `"'A' | 'B'"` → `"('A' | 'B')[]"`. */
|
|
2288
|
+
function makeArktypeListExpression(element) {
|
|
2289
|
+
const inner = element.slice(1, -1);
|
|
2290
|
+
return inner.includes("|") ? `"(${inner})[]"` : `"${inner}[]"`;
|
|
2291
|
+
}
|
|
2170
2292
|
const PRISMA_TO_ARKTYPE = {
|
|
2171
2293
|
String: "\"string\"",
|
|
2172
2294
|
Int: "\"number\"",
|
|
@@ -2197,7 +2319,8 @@ function arktypeSchemaCode(models, type, enums) {
|
|
|
2197
2319
|
schemas: makeArktypeSchemas,
|
|
2198
2320
|
typeMapping: PRISMA_TO_ARKTYPE,
|
|
2199
2321
|
enums,
|
|
2200
|
-
formatEnum: makeArktypeEnumExpression
|
|
2322
|
+
formatEnum: makeArktypeEnumExpression,
|
|
2323
|
+
wrapList: makeArktypeListExpression
|
|
2201
2324
|
});
|
|
2202
2325
|
}
|
|
2203
2326
|
// src/generator/arktype.ts
|
|
@@ -3757,47 +3880,6 @@ function django(options) {
|
|
|
3757
3880
|
return yield* emitRaw(code, resolved.dir, resolved.file);
|
|
3758
3881
|
});
|
|
3759
3882
|
}
|
|
3760
|
-
// src/constants/diagram.ts
|
|
3761
|
-
const EDGE_LABEL_FONT_SIZE = 9.5;
|
|
3762
|
-
/**
|
|
3763
|
-
* Glyph advance as a fraction of the font size, for the monospace face captions and field rows
|
|
3764
|
-
* are set in: what a label is measured, right-aligned and truncated by.
|
|
3765
|
-
*/
|
|
3766
|
-
const MONO_ADVANCE = .6;
|
|
3767
|
-
const PALETTES = {
|
|
3768
|
-
light: {
|
|
3769
|
-
canvas: "#f7f8fb",
|
|
3770
|
-
surface: "#ffffff",
|
|
3771
|
-
ink: "#16181f",
|
|
3772
|
-
muted: "#6b7084",
|
|
3773
|
-
faint: "#9a9fb3",
|
|
3774
|
-
lineStrong: "#cfd3e0",
|
|
3775
|
-
accent: "#4f46e5",
|
|
3776
|
-
node: "#1f2233",
|
|
3777
|
-
nodeText: "#f4f5fa",
|
|
3778
|
-
edge: "#9095ab",
|
|
3779
|
-
dots: "#d4d4dc",
|
|
3780
|
-
key: "#b45309",
|
|
3781
|
-
unique: "#0f766e",
|
|
3782
|
-
enumeration: "#7c3aed"
|
|
3783
|
-
},
|
|
3784
|
-
dark: {
|
|
3785
|
-
canvas: "#0f1117",
|
|
3786
|
-
surface: "#171a23",
|
|
3787
|
-
ink: "#e6e8ef",
|
|
3788
|
-
muted: "#9aa0b4",
|
|
3789
|
-
faint: "#6b7189",
|
|
3790
|
-
lineStrong: "#343a4a",
|
|
3791
|
-
accent: "#7c74ff",
|
|
3792
|
-
node: "#2a2f45",
|
|
3793
|
-
nodeText: "#f4f5fa",
|
|
3794
|
-
edge: "#6b7189",
|
|
3795
|
-
dots: "#2a2f3d",
|
|
3796
|
-
key: "#fbbf24",
|
|
3797
|
-
unique: "#5eead4",
|
|
3798
|
-
enumeration: "#c4b5fd"
|
|
3799
|
-
}
|
|
3800
|
-
};
|
|
3801
3883
|
// src/diagram/layout.ts
|
|
3802
3884
|
/** The fields a model node shows: everything but the relation fields. */
|
|
3803
3885
|
function diagramFields(model) {
|
|
@@ -9281,6 +9363,9 @@ function makeEffectProperties(fields) {
|
|
|
9281
9363
|
function makeEffectEnumExpression(values) {
|
|
9282
9364
|
return `Schema.Literal(${values.map((v) => `'${v}'`).join(", ")})`;
|
|
9283
9365
|
}
|
|
9366
|
+
function makeEffectListExpression(element) {
|
|
9367
|
+
return `Schema.Array(${element})`;
|
|
9368
|
+
}
|
|
9284
9369
|
const PRISMA_TO_EFFECT = {
|
|
9285
9370
|
String: "Schema.String",
|
|
9286
9371
|
Int: "Schema.Number",
|
|
@@ -9311,7 +9396,8 @@ function effectSchemaCode(models, type, enums) {
|
|
|
9311
9396
|
schemas: makeEffectSchemas,
|
|
9312
9397
|
typeMapping: PRISMA_TO_EFFECT,
|
|
9313
9398
|
enums,
|
|
9314
|
-
formatEnum: makeEffectEnumExpression
|
|
9399
|
+
formatEnum: makeEffectEnumExpression,
|
|
9400
|
+
wrapList: makeEffectListExpression
|
|
9315
9401
|
});
|
|
9316
9402
|
}
|
|
9317
9403
|
// src/generator/effect.ts
|
|
@@ -11851,7 +11937,7 @@ function property(indent, head, calls) {
|
|
|
11851
11937
|
function statement(indent, calls) {
|
|
11852
11938
|
return (resolve) => chainLines(indent, resolveCalls(calls, resolve));
|
|
11853
11939
|
}
|
|
11854
|
-
function delegate(indent, head, left, operator, right) {
|
|
11940
|
+
function delegate$1(indent, head, left, operator, right) {
|
|
11855
11941
|
return (resolve) => {
|
|
11856
11942
|
const single = `${indent}${head} ${resolve(left)} ${operator} ${resolve(right)}`;
|
|
11857
11943
|
return fits(single) ? [single] : [`${indent}${head} ${resolve(left)} ${operator}`, `${indent} ${resolve(right)}`];
|
|
@@ -12159,19 +12245,19 @@ function relationLines(plan, model, field) {
|
|
|
12159
12245
|
const outgoing = plan.foreignKeyOf(field);
|
|
12160
12246
|
if (outgoing) {
|
|
12161
12247
|
const target = plan.navigationOf(outgoing) === "table" ? tableRef(plan, model) : columnRef(plan, model, outgoing.from[0] ?? "");
|
|
12162
|
-
return delegate(" ", `${outgoing.from.some((from) => isKeyField(plan, model, from)) ? "val" : "var"} ${name} by`, entityRef(plan, outgoing.principal), outgoing.isRequired ? "referencedOn" : "optionalReferencedOn", target);
|
|
12248
|
+
return delegate$1(" ", `${outgoing.from.some((from) => isKeyField(plan, model, from)) ? "val" : "var"} ${name} by`, entityRef(plan, outgoing.principal), outgoing.isRequired ? "referencedOn" : "optionalReferencedOn", target);
|
|
12163
12249
|
}
|
|
12164
12250
|
const incoming = plan.inverseKeyOf(field);
|
|
12165
12251
|
if (incoming) {
|
|
12166
12252
|
const target = plan.navigationOf(incoming) === "table" ? tableRef(plan, incoming.dependent) : columnRef(plan, incoming.dependent, incoming.from[0] ?? "");
|
|
12167
12253
|
const operator = field.isList ? incoming.isRequired ? "referrersOn" : "optionalReferrersOn" : "optionalBackReferencedOn";
|
|
12168
|
-
return delegate(" ", `val ${name} by`, entityRef(plan, incoming.dependent), operator, target);
|
|
12254
|
+
return delegate$1(" ", `val ${name} by`, entityRef(plan, incoming.dependent), operator, target);
|
|
12169
12255
|
}
|
|
12170
12256
|
const m2m = plan.manyToMany.find((r) => r.a.model === model && r.a.field === field || r.b.model === model && r.b.field === field);
|
|
12171
12257
|
if (!m2m) return textLines([]);
|
|
12172
12258
|
const join = exprRef(local(plan.names.joins.get(m2m.relationName) ?? m2m.relationName));
|
|
12173
12259
|
const isA = m2m.a.model === model && m2m.a.field === field;
|
|
12174
|
-
if (m2m.a.model !== m2m.b.model) return delegate(" ", `var ${name} by`, entityRef(plan, isA ? m2m.b.model : m2m.a.model), "via", join);
|
|
12260
|
+
if (m2m.a.model !== m2m.b.model) return delegate$1(" ", `var ${name} by`, entityRef(plan, isA ? m2m.b.model : m2m.a.model), "via", join);
|
|
12175
12261
|
const [source, target] = isA ? ["a", "b"] : ["b", "a"];
|
|
12176
12262
|
return headerLines(" ", `var ${name} by ${entityRef(plan, model)}.via`, [`${join}.${source}`, `${join}.${target}`], "");
|
|
12177
12263
|
}
|
|
@@ -13835,7 +13921,7 @@ function kysely(options) {
|
|
|
13835
13921
|
});
|
|
13836
13922
|
}
|
|
13837
13923
|
// src/helper/openapi.ts
|
|
13838
|
-
const SCALAR = {
|
|
13924
|
+
const SCALAR$1 = {
|
|
13839
13925
|
Int: { type: "integer" },
|
|
13840
13926
|
BigInt: { type: "integer" },
|
|
13841
13927
|
Boolean: { type: "boolean" },
|
|
@@ -13848,7 +13934,7 @@ function storedEnumValues(enumName, enums) {
|
|
|
13848
13934
|
return enums.find((e) => e.name === enumName)?.values.map((v) => v.dbName ?? v.name);
|
|
13849
13935
|
}
|
|
13850
13936
|
/** The schema of one value in the column: its scalar type, or the enum's stored values. */
|
|
13851
|
-
function itemSchema(field, enums) {
|
|
13937
|
+
function itemSchema$1(field, enums) {
|
|
13852
13938
|
if (field.kind === "enum") {
|
|
13853
13939
|
const values = storedEnumValues(field.type, enums);
|
|
13854
13940
|
return values === void 0 ? { type: "string" } : {
|
|
@@ -13856,7 +13942,7 @@ function itemSchema(field, enums) {
|
|
|
13856
13942
|
enum: values
|
|
13857
13943
|
};
|
|
13858
13944
|
}
|
|
13859
|
-
return SCALAR[field.type] ?? { type: "string" };
|
|
13945
|
+
return SCALAR$1[field.type] ?? { type: "string" };
|
|
13860
13946
|
}
|
|
13861
13947
|
/**
|
|
13862
13948
|
* The column's `@default` as the `default` keyword, where it is a literal the schema can show: a
|
|
@@ -13891,7 +13977,7 @@ function defaultKeyword(field, enums) {
|
|
|
13891
13977
|
* ```
|
|
13892
13978
|
*/
|
|
13893
13979
|
function makeOpenApiColumn(field, enums) {
|
|
13894
|
-
const item = itemSchema(field, enums);
|
|
13980
|
+
const item = itemSchema$1(field, enums);
|
|
13895
13981
|
const shape = field.isList ? {
|
|
13896
13982
|
type: "array",
|
|
13897
13983
|
items: item
|
|
@@ -13952,7 +14038,7 @@ function makeOpenApiTable(model, models, enums) {
|
|
|
13952
14038
|
/** The schema of a model's primary key column, which a join table's column takes after. */
|
|
13953
14039
|
function keyType(model, enums) {
|
|
13954
14040
|
const key = model.fields.find((f) => f.isId);
|
|
13955
|
-
return key === void 0 ? { type: "string" } : itemSchema(key, enums);
|
|
14041
|
+
return key === void 0 ? { type: "string" } : itemSchema$1(key, enums);
|
|
13956
14042
|
}
|
|
13957
14043
|
/**
|
|
13958
14044
|
* The join table of each implicit many-to-many, `_<relationName>`, as Prisma Migrate makes it:
|
|
@@ -14103,7 +14189,7 @@ function makeOpenApiPaths(model, enums, resource) {
|
|
|
14103
14189
|
name: key.name,
|
|
14104
14190
|
in: "path",
|
|
14105
14191
|
required: true,
|
|
14106
|
-
schema: itemSchema(key, enums)
|
|
14192
|
+
schema: itemSchema$1(key, enums)
|
|
14107
14193
|
})),
|
|
14108
14194
|
get: {
|
|
14109
14195
|
tags: [model.name],
|
|
@@ -16420,6 +16506,9 @@ function makeTypeBoxProperties(fields) {
|
|
|
16420
16506
|
function makeTypeBoxEnumExpression(values) {
|
|
16421
16507
|
return `Type.Union([${values.map((v) => `Type.Literal('${v}')`).join(", ")}])`;
|
|
16422
16508
|
}
|
|
16509
|
+
function makeTypeBoxListExpression(element) {
|
|
16510
|
+
return `Type.Array(${element})`;
|
|
16511
|
+
}
|
|
16423
16512
|
const PRISMA_TO_TYPEBOX = {
|
|
16424
16513
|
String: "Type.String()",
|
|
16425
16514
|
Int: "Type.Integer()",
|
|
@@ -16450,7 +16539,8 @@ function typeboxSchemaCode(models, type, enums) {
|
|
|
16450
16539
|
schemas: makeTypeBoxSchemas,
|
|
16451
16540
|
typeMapping: PRISMA_TO_TYPEBOX,
|
|
16452
16541
|
enums,
|
|
16453
|
-
formatEnum: makeTypeBoxEnumExpression
|
|
16542
|
+
formatEnum: makeTypeBoxEnumExpression,
|
|
16543
|
+
wrapList: makeTypeBoxListExpression
|
|
16454
16544
|
});
|
|
16455
16545
|
}
|
|
16456
16546
|
// src/generator/typebox.ts
|
|
@@ -16475,6 +16565,9 @@ function makeValibotSchema(modelName, fields, objectType) {
|
|
|
16475
16565
|
function makeValibotEnumExpression(values) {
|
|
16476
16566
|
return `picklist([${values.map((v) => `'${v}'`).join(", ")}])`;
|
|
16477
16567
|
}
|
|
16568
|
+
function makeValibotListExpression(element) {
|
|
16569
|
+
return `array(v.${element})`;
|
|
16570
|
+
}
|
|
16478
16571
|
const PRISMA_TO_VALIBOT = {
|
|
16479
16572
|
String: "string()",
|
|
16480
16573
|
Int: "number()",
|
|
@@ -16505,7 +16598,8 @@ function valibotSchemaCode(models, type, enums) {
|
|
|
16505
16598
|
schemas: makeValibotSchemas,
|
|
16506
16599
|
typeMapping: PRISMA_TO_VALIBOT,
|
|
16507
16600
|
enums,
|
|
16508
|
-
formatEnum: makeValibotEnumExpression
|
|
16601
|
+
formatEnum: makeValibotEnumExpression,
|
|
16602
|
+
wrapList: makeValibotListExpression
|
|
16509
16603
|
});
|
|
16510
16604
|
}
|
|
16511
16605
|
// src/generator/valibot.ts
|
|
@@ -16520,6 +16614,988 @@ function valibot(options) {
|
|
|
16520
16614
|
return yield* emit(code, resolved.dir, resolved.file);
|
|
16521
16615
|
});
|
|
16522
16616
|
}
|
|
16617
|
+
// src/helper/zod-openapi-hono.ts
|
|
16618
|
+
/** The schema of one value a field holds, as Prisma Client reads it and the JSON answer carries it. */
|
|
16619
|
+
const SCALAR = {
|
|
16620
|
+
String: { type: "string" },
|
|
16621
|
+
Int: { type: "integer" },
|
|
16622
|
+
BigInt: { type: "integer" },
|
|
16623
|
+
Float: { type: "number" },
|
|
16624
|
+
Decimal: { type: "string" },
|
|
16625
|
+
Boolean: { type: "boolean" },
|
|
16626
|
+
DateTime: {
|
|
16627
|
+
type: "string",
|
|
16628
|
+
format: "date-time"
|
|
16629
|
+
},
|
|
16630
|
+
Json: {},
|
|
16631
|
+
Bytes: {
|
|
16632
|
+
type: "string",
|
|
16633
|
+
format: "byte"
|
|
16634
|
+
}
|
|
16635
|
+
};
|
|
16636
|
+
/** The fields Prisma Client reads and writes as values: scalars and enums, not relations. */
|
|
16637
|
+
function valueFields(model) {
|
|
16638
|
+
return model.fields.filter((f) => f.kind === "scalar" || f.kind === "enum");
|
|
16639
|
+
}
|
|
16640
|
+
/**
|
|
16641
|
+
* What a field's `///` comment keeps from the API: `hidden` for an `@api.hidden` line, `readonly`
|
|
16642
|
+
* for an `@api.readonly` one, undefined for a field the API answers and takes.
|
|
16643
|
+
*/
|
|
16644
|
+
function apiAccess(documentation) {
|
|
16645
|
+
const lines = new Set((documentation ?? "").split("\n").map((line) => line.trim()));
|
|
16646
|
+
if (lines.has(API_ACCESS_ANNOTATIONS.hidden)) return "hidden";
|
|
16647
|
+
if (lines.has(API_ACCESS_ANNOTATIONS.readonly)) return "readonly";
|
|
16648
|
+
}
|
|
16649
|
+
/** Whether the server fills the field: `@updatedAt`, or a `@default` the database or Prisma makes. */
|
|
16650
|
+
function isGenerated(field) {
|
|
16651
|
+
if (field.isUpdatedAt) return true;
|
|
16652
|
+
const value = field.default;
|
|
16653
|
+
return typeof value === "object" && value !== null && "name" in value && typeof value.name === "string" && GENERATED_DEFAULTS.has(value.name);
|
|
16654
|
+
}
|
|
16655
|
+
/** The value fields an answer carries: all but `@api.hidden`. */
|
|
16656
|
+
function answeredFields(model) {
|
|
16657
|
+
return valueFields(model).filter((f) => apiAccess(f.documentation) !== "hidden");
|
|
16658
|
+
}
|
|
16659
|
+
/**
|
|
16660
|
+
* The value fields a `POST` or a `PATCH` takes: all but `@api.hidden`, `@api.readonly` and those
|
|
16661
|
+
* the server fills (`@updatedAt`, `@default(autoincrement())`, `now()`, `uuid()`, …). Zod drops a
|
|
16662
|
+
* field the schema does not have, so a request cannot set one of them.
|
|
16663
|
+
*/
|
|
16664
|
+
function writableFields(model) {
|
|
16665
|
+
return valueFields(model).filter((f) => apiAccess(f.documentation) === void 0 && !isGenerated(f));
|
|
16666
|
+
}
|
|
16667
|
+
/** The schema of one value of the field: its scalar's, or the enum's members by Prisma's names. */
|
|
16668
|
+
function itemSchema(field, enums) {
|
|
16669
|
+
if (field.kind === "enum") {
|
|
16670
|
+
const values = enums.find((e) => e.name === field.type)?.values.map((v) => v.name);
|
|
16671
|
+
return values === void 0 ? { type: "string" } : {
|
|
16672
|
+
type: "string",
|
|
16673
|
+
enum: values
|
|
16674
|
+
};
|
|
16675
|
+
}
|
|
16676
|
+
return SCALAR[field.type] ?? { type: "string" };
|
|
16677
|
+
}
|
|
16678
|
+
/**
|
|
16679
|
+
* A field as Prisma Client has it: a list as an array (never null, an empty list is `[]`), an
|
|
16680
|
+
* optional field with `null` beside its type, and the prose of its `///` comment as `description`.
|
|
16681
|
+
*/
|
|
16682
|
+
function makeFieldSchema(field, enums) {
|
|
16683
|
+
const item = itemSchema(field, enums);
|
|
16684
|
+
const shape = field.isList ? {
|
|
16685
|
+
type: "array",
|
|
16686
|
+
items: item
|
|
16687
|
+
} : item;
|
|
16688
|
+
const description = stripAnnotations(field.documentation);
|
|
16689
|
+
const nullable = !field.isList && !field.isRequired && typeof shape.type === "string" ? { type: [shape.type, "null"] } : {};
|
|
16690
|
+
return {
|
|
16691
|
+
...shape,
|
|
16692
|
+
...nullable,
|
|
16693
|
+
...description === void 0 ? {} : { description }
|
|
16694
|
+
};
|
|
16695
|
+
}
|
|
16696
|
+
/** The fields a row is addressed by: `@id`, or `@@id`, or the first `@@unique`; none for a model without. */
|
|
16697
|
+
function keyFields(model) {
|
|
16698
|
+
const id = model.fields.filter((f) => f.isId);
|
|
16699
|
+
if (id.length > 0) return id;
|
|
16700
|
+
return (model.primaryKey?.fields ?? model.uniqueFields[0] ?? []).flatMap((name) => {
|
|
16701
|
+
const field = model.fields.find((f) => f.name === name);
|
|
16702
|
+
return field === void 0 ? [] : [field];
|
|
16703
|
+
});
|
|
16704
|
+
}
|
|
16705
|
+
/**
|
|
16706
|
+
* A row as Prisma Client reads it: every value field under its Prisma name, all of them present,
|
|
16707
|
+
* but those `@api.hidden` keeps from the answer. The model's `///` comment is its `description`.
|
|
16708
|
+
*/
|
|
16709
|
+
function makeRowSchema(model, enums) {
|
|
16710
|
+
const fields = answeredFields(model);
|
|
16711
|
+
const description = stripAnnotations(model.documentation);
|
|
16712
|
+
return {
|
|
16713
|
+
type: "object",
|
|
16714
|
+
properties: Object.fromEntries(fields.map((f) => [f.name, makeFieldSchema(f, enums)])),
|
|
16715
|
+
...fields.length === 0 ? {} : { required: fields.map((f) => f.name) },
|
|
16716
|
+
...description === void 0 ? {} : { description }
|
|
16717
|
+
};
|
|
16718
|
+
}
|
|
16719
|
+
/**
|
|
16720
|
+
* What a `POST` or a `PATCH` takes, the `data` of Prisma's unchecked input: the value fields the
|
|
16721
|
+
* client may write ({@link writableFields}), foreign keys among them. A create requires the fields
|
|
16722
|
+
* a row cannot do without (required, not a list, no `@default`, not `@updatedAt`); an update
|
|
16723
|
+
* requires nothing and leaves out the key the path names.
|
|
16724
|
+
*/
|
|
16725
|
+
function makeInputSchema(model, enums, kind) {
|
|
16726
|
+
const keys = new Set(keyFields(model).map((f) => f.name));
|
|
16727
|
+
const fields = writableFields(model).filter((f) => kind === "create" || !keys.has(f.name));
|
|
16728
|
+
const required = kind === "create" ? fields.filter((f) => f.isRequired && !f.isList && !f.hasDefaultValue && !f.isUpdatedAt).map((f) => f.name) : [];
|
|
16729
|
+
return {
|
|
16730
|
+
type: "object",
|
|
16731
|
+
properties: Object.fromEntries(fields.map((f) => [f.name, makeFieldSchema(f, enums)])),
|
|
16732
|
+
...required.length === 0 ? {} : { required }
|
|
16733
|
+
};
|
|
16734
|
+
}
|
|
16735
|
+
/** The operations of a model, named for it: `listOrderItems`, `createOrderItem`, … */
|
|
16736
|
+
function operationIds(model) {
|
|
16737
|
+
return {
|
|
16738
|
+
list: `list${pluralize(model.name)}`,
|
|
16739
|
+
create: `create${model.name}`,
|
|
16740
|
+
get: `get${model.name}`,
|
|
16741
|
+
update: `update${model.name}`,
|
|
16742
|
+
delete: `delete${model.name}`
|
|
16743
|
+
};
|
|
16744
|
+
}
|
|
16745
|
+
/** A reference to a schema of the document's components. */
|
|
16746
|
+
function ref(name) {
|
|
16747
|
+
return { $ref: `#/components/schemas/${name}` };
|
|
16748
|
+
}
|
|
16749
|
+
/** The JSON content of a request or a response. */
|
|
16750
|
+
function json(schema) {
|
|
16751
|
+
return { content: { "application/json": { schema } } };
|
|
16752
|
+
}
|
|
16753
|
+
/**
|
|
16754
|
+
* The CRUD of a model as path items under `resource`: `GET` and `POST /{resource}`, and for a
|
|
16755
|
+
* model with a key `GET`, `PATCH` and `DELETE /{resource}/{key}`, a path parameter per key
|
|
16756
|
+
* field named as the field is. The schemas are the model's (`User`, `UserCreate`, `UserUpdate`).
|
|
16757
|
+
*/
|
|
16758
|
+
function makePaths(model, enums, resource, schemas) {
|
|
16759
|
+
const ids = operationIds(model);
|
|
16760
|
+
const one = makeSnakeCase(model.name).replaceAll("_", " ");
|
|
16761
|
+
const many = pluralize(makeSnakeCase(model.name)).replaceAll("_", " ");
|
|
16762
|
+
const a = /^[aeiou]/u.test(one) ? `an ${one}` : `a ${one}`;
|
|
16763
|
+
const notFound = { "404": { description: `No ${one} has this key.` } };
|
|
16764
|
+
const collection = {
|
|
16765
|
+
get: {
|
|
16766
|
+
tags: [model.name],
|
|
16767
|
+
summary: `List ${many}`,
|
|
16768
|
+
operationId: ids.list,
|
|
16769
|
+
parameters: [{
|
|
16770
|
+
name: "limit",
|
|
16771
|
+
in: "query",
|
|
16772
|
+
required: false,
|
|
16773
|
+
description: `How many ${many} to answer, at most ${LIST_LIMIT.max}.`,
|
|
16774
|
+
schema: {
|
|
16775
|
+
type: "integer",
|
|
16776
|
+
minimum: 1,
|
|
16777
|
+
maximum: LIST_LIMIT.max,
|
|
16778
|
+
default: LIST_LIMIT.default
|
|
16779
|
+
}
|
|
16780
|
+
}, {
|
|
16781
|
+
name: "offset",
|
|
16782
|
+
in: "query",
|
|
16783
|
+
required: false,
|
|
16784
|
+
description: `How many ${many} to skip, in the order of the key.`,
|
|
16785
|
+
schema: {
|
|
16786
|
+
type: "integer",
|
|
16787
|
+
minimum: 0,
|
|
16788
|
+
default: 0
|
|
16789
|
+
}
|
|
16790
|
+
}],
|
|
16791
|
+
responses: { "200": {
|
|
16792
|
+
description: `The ${many}, at most \`limit\` of them after \`offset\`.`,
|
|
16793
|
+
headers: { [TOTAL_COUNT_HEADER]: {
|
|
16794
|
+
description: `How many ${many} there are in all.`,
|
|
16795
|
+
schema: {
|
|
16796
|
+
type: "integer",
|
|
16797
|
+
minimum: 0
|
|
16798
|
+
}
|
|
16799
|
+
} },
|
|
16800
|
+
...json({
|
|
16801
|
+
type: "array",
|
|
16802
|
+
items: ref(schemas.row)
|
|
16803
|
+
})
|
|
16804
|
+
} }
|
|
16805
|
+
},
|
|
16806
|
+
post: {
|
|
16807
|
+
tags: [model.name],
|
|
16808
|
+
summary: `Create ${a}`,
|
|
16809
|
+
operationId: ids.create,
|
|
16810
|
+
requestBody: {
|
|
16811
|
+
required: true,
|
|
16812
|
+
...json(ref(schemas.create))
|
|
16813
|
+
},
|
|
16814
|
+
responses: { "201": {
|
|
16815
|
+
description: `The ${one} made.`,
|
|
16816
|
+
...json(ref(schemas.row))
|
|
16817
|
+
} }
|
|
16818
|
+
}
|
|
16819
|
+
};
|
|
16820
|
+
const keys = keyFields(model);
|
|
16821
|
+
if (keys.length === 0) return [[`/${resource}`, collection]];
|
|
16822
|
+
const item = {
|
|
16823
|
+
parameters: keys.map((key) => ({
|
|
16824
|
+
name: key.name,
|
|
16825
|
+
in: "path",
|
|
16826
|
+
required: true,
|
|
16827
|
+
schema: itemSchema(key, enums)
|
|
16828
|
+
})),
|
|
16829
|
+
get: {
|
|
16830
|
+
tags: [model.name],
|
|
16831
|
+
summary: `Get ${a}`,
|
|
16832
|
+
operationId: ids.get,
|
|
16833
|
+
responses: {
|
|
16834
|
+
"200": {
|
|
16835
|
+
description: `The ${one}.`,
|
|
16836
|
+
...json(ref(schemas.row))
|
|
16837
|
+
},
|
|
16838
|
+
...notFound
|
|
16839
|
+
}
|
|
16840
|
+
},
|
|
16841
|
+
patch: {
|
|
16842
|
+
tags: [model.name],
|
|
16843
|
+
summary: `Update ${a}`,
|
|
16844
|
+
operationId: ids.update,
|
|
16845
|
+
requestBody: {
|
|
16846
|
+
required: true,
|
|
16847
|
+
...json(ref(schemas.update))
|
|
16848
|
+
},
|
|
16849
|
+
responses: {
|
|
16850
|
+
"200": {
|
|
16851
|
+
description: `The ${one} changed.`,
|
|
16852
|
+
...json(ref(schemas.row))
|
|
16853
|
+
},
|
|
16854
|
+
...notFound
|
|
16855
|
+
}
|
|
16856
|
+
},
|
|
16857
|
+
delete: {
|
|
16858
|
+
tags: [model.name],
|
|
16859
|
+
summary: `Delete ${a}`,
|
|
16860
|
+
operationId: ids.delete,
|
|
16861
|
+
responses: {
|
|
16862
|
+
"204": { description: `The ${one} is deleted.` },
|
|
16863
|
+
...notFound
|
|
16864
|
+
}
|
|
16865
|
+
}
|
|
16866
|
+
};
|
|
16867
|
+
return [[`/${resource}`, collection], [`/${resource}/${keys.map((key) => `{${key.name}}`).join("/")}`, item]];
|
|
16868
|
+
}
|
|
16869
|
+
/** How a value of the field leaves Prisma for JSON, where it has no JSON form of its own. */
|
|
16870
|
+
function encoder(field) {
|
|
16871
|
+
if (field.type === "BigInt") return (value) => `Number(${value})`;
|
|
16872
|
+
if (field.type === "Bytes") return (value) => `Buffer.from(${value}).toString('base64')`;
|
|
16873
|
+
}
|
|
16874
|
+
/** The row as the answer carries it: a bigint as a number, bytes as base64, the rest as it is. */
|
|
16875
|
+
function encodeRow(model, row) {
|
|
16876
|
+
const entries = answeredFields(model).flatMap((field) => {
|
|
16877
|
+
const encode = encoder(field);
|
|
16878
|
+
if (encode === void 0) return [];
|
|
16879
|
+
const value = `${row}.${field.name}`;
|
|
16880
|
+
const expression = field.isList ? `${value}.map((value) => ${encode("value")})` : field.isRequired ? encode(value) : `${value} === null ? null : ${encode(value)}`;
|
|
16881
|
+
return [`${field.name}: ${expression}`];
|
|
16882
|
+
});
|
|
16883
|
+
return entries.length === 0 ? row : `{ ...${row}, ${entries.join(", ")} }`;
|
|
16884
|
+
}
|
|
16885
|
+
/** The rows as the answer carries them. */
|
|
16886
|
+
function encodeRows(model, rows) {
|
|
16887
|
+
const row = encodeRow(model, "row");
|
|
16888
|
+
return row === "row" ? rows : `${rows}.map((row) => (${row}))`;
|
|
16889
|
+
}
|
|
16890
|
+
/** The bytes of a base64 string, as Prisma takes a Bytes field. */
|
|
16891
|
+
function bytes(value) {
|
|
16892
|
+
return `new Uint8Array(Buffer.from(${value}, 'base64'))`;
|
|
16893
|
+
}
|
|
16894
|
+
/**
|
|
16895
|
+
* The `data` option the handler hands Prisma: `data` itself, or, where the model has Bytes,
|
|
16896
|
+
* `data` with each Bytes field decoded from base64 back into bytes.
|
|
16897
|
+
*
|
|
16898
|
+
* @example
|
|
16899
|
+
* ```ts
|
|
16900
|
+
* await prisma.profile.create({
|
|
16901
|
+
* data: { ...data, avatar: data.avatar === undefined ? undefined : data.avatar === null ? null : ... },
|
|
16902
|
+
* })
|
|
16903
|
+
* ```
|
|
16904
|
+
*/
|
|
16905
|
+
function prismaData(model, kind) {
|
|
16906
|
+
const fields = writableFields(model).filter((field) => field.type === "Bytes");
|
|
16907
|
+
if (fields.length === 0) return "data";
|
|
16908
|
+
return `data: { ...data, ${fields.map((field) => {
|
|
16909
|
+
const value = `data.${field.name}`;
|
|
16910
|
+
const decoded = field.isList ? `${value}.map((value) => ${bytes("value")})` : field.isRequired ? bytes(value) : `${value} === null ? null : ${bytes(value)}`;
|
|
16911
|
+
const isPresent = kind === "create" && field.isRequired && !field.hasDefaultValue;
|
|
16912
|
+
return `${field.name}: ${isPresent ? decoded : `${value} === undefined ? undefined : ${decoded}`}`;
|
|
16913
|
+
}).join(", ")} }`;
|
|
16914
|
+
}
|
|
16915
|
+
/**
|
|
16916
|
+
* The request as one `data`: what the handler validated, the path and the body spread into one
|
|
16917
|
+
* object where it takes both, `const data = { ...c.req.valid('param'), ...c.req.valid('json') }`.
|
|
16918
|
+
* The body of an update holds no key field (and Zod drops one sent anyway), so the key in `data`
|
|
16919
|
+
* is always the one of the path.
|
|
16920
|
+
*/
|
|
16921
|
+
function readData(targets) {
|
|
16922
|
+
const reads = targets.map((target) => `c.req.valid('${target}')`);
|
|
16923
|
+
return `const data = ${reads.length === 1 ? reads.join("") : `{ ${reads.map((read) => `...${read}`).join(", ")} }`}`;
|
|
16924
|
+
}
|
|
16925
|
+
/** The `where` that finds the row by the key fields `data` holds: `{ orderId: data.orderId, sku: data.sku }`. */
|
|
16926
|
+
function keyWhere(keys) {
|
|
16927
|
+
return `{ ${keys.map((key) => `${key.name}: data.${key.name}`).join(", ")} }`;
|
|
16928
|
+
}
|
|
16929
|
+
/**
|
|
16930
|
+
* The `orderBy` of a list, by the key fields, so that `offset` pages through the rows in one order:
|
|
16931
|
+
* `, orderBy: [{ orderId: 'asc' }, { sku: 'asc' }]`, nothing for a model without a key.
|
|
16932
|
+
*/
|
|
16933
|
+
function keyOrder(keys) {
|
|
16934
|
+
return keys.length === 0 ? "" : `, orderBy: [${keys.map((key) => `{ ${key.name}: 'asc' }`).join(", ")}]`;
|
|
16935
|
+
}
|
|
16936
|
+
/**
|
|
16937
|
+
* The `omit` of every query, so the row Prisma answers lacks the `@api.hidden` fields:
|
|
16938
|
+
* `, omit: { passwordHash: true }`, nothing for a model without one.
|
|
16939
|
+
*/
|
|
16940
|
+
function hiddenOmit(model) {
|
|
16941
|
+
const hidden = valueFields(model).filter((f) => apiAccess(f.documentation) === "hidden");
|
|
16942
|
+
return hidden.length === 0 ? "" : `, omit: { ${hidden.map((field) => `${field.name}: true`).join(", ")} }`;
|
|
16943
|
+
}
|
|
16944
|
+
/** The model's delegate on the client: `prisma.orderItem`. */
|
|
16945
|
+
function delegate(model) {
|
|
16946
|
+
return `prisma.${model.name.charAt(0).toLowerCase()}${model.name.slice(1)}`;
|
|
16947
|
+
}
|
|
16948
|
+
/**
|
|
16949
|
+
* The body of each handler of a model by its operation id, calling Prisma Client as `prisma`. A
|
|
16950
|
+
* row is found by its key with `findFirst`, so a composite key needs no compound name, and a
|
|
16951
|
+
* `PATCH` or `DELETE` of a key no row has answers 404 rather than throwing.
|
|
16952
|
+
*/
|
|
16953
|
+
function makeHandlerBodies(model) {
|
|
16954
|
+
const ids = operationIds(model);
|
|
16955
|
+
const db = delegate(model);
|
|
16956
|
+
const create = prismaData(model, "create");
|
|
16957
|
+
const update = prismaData(model, "update");
|
|
16958
|
+
const omit = hiddenOmit(model);
|
|
16959
|
+
const collection = [[ids.list, [
|
|
16960
|
+
"const { limit, offset } = c.req.valid('query')",
|
|
16961
|
+
"const [rows, total] = await Promise.all([",
|
|
16962
|
+
`${db}.findMany({ take: limit, skip: offset${keyOrder(keyFields(model))}${omit} }),`,
|
|
16963
|
+
`${db}.count(),`,
|
|
16964
|
+
"])",
|
|
16965
|
+
`return c.json(${encodeRows(model, "rows")}, 200, { '${TOTAL_COUNT_HEADER}': String(total) })`
|
|
16966
|
+
]], [ids.create, [
|
|
16967
|
+
readData(["json"]),
|
|
16968
|
+
`const row = await ${db}.create({ ${create}${omit} })`,
|
|
16969
|
+
`return c.json(${encodeRow(model, "row")}, 201)`
|
|
16970
|
+
]]];
|
|
16971
|
+
const keys = keyFields(model);
|
|
16972
|
+
if (keys.length === 0) return collection.map(([id, lines]) => [id, lines.join("\n")]);
|
|
16973
|
+
const where = keyWhere(keys);
|
|
16974
|
+
const item = [
|
|
16975
|
+
[ids.get, [
|
|
16976
|
+
readData(["param"]),
|
|
16977
|
+
`const row = await ${db}.findFirst({ where: ${where}${omit} })`,
|
|
16978
|
+
"if (row === null) return c.body(null, 404)",
|
|
16979
|
+
`return c.json(${encodeRow(model, "row")}, 200)`
|
|
16980
|
+
]],
|
|
16981
|
+
[ids.update, [
|
|
16982
|
+
readData(["param", "json"]),
|
|
16983
|
+
`const { count } = await ${db}.updateMany({ where: ${where}, ${update} })`,
|
|
16984
|
+
"if (count === 0) return c.body(null, 404)",
|
|
16985
|
+
`const row = await ${db}.findFirstOrThrow({ where: ${where}${omit} })`,
|
|
16986
|
+
`return c.json(${encodeRow(model, "row")}, 200)`
|
|
16987
|
+
]],
|
|
16988
|
+
[ids.delete, [
|
|
16989
|
+
readData(["param"]),
|
|
16990
|
+
`const { count } = await ${db}.deleteMany({ where: ${where} })`,
|
|
16991
|
+
"if (count === 0) return c.body(null, 404)",
|
|
16992
|
+
"return c.body(null, 204)"
|
|
16993
|
+
]]
|
|
16994
|
+
];
|
|
16995
|
+
return [...collection, ...item].map(([id, lines]) => [id, lines.join("\n")]);
|
|
16996
|
+
}
|
|
16997
|
+
// src/generator/zod-openapi-hono.ts
|
|
16998
|
+
/** The names a model's schemas take: `User`, `UserCreate`, `UserUpdate`, a number added on a clash. */
|
|
16999
|
+
function schemaNames(models) {
|
|
17000
|
+
const names = allocate(models.flatMap((model) => [
|
|
17001
|
+
{
|
|
17002
|
+
key: `${model.name}:row`,
|
|
17003
|
+
candidate: model.name
|
|
17004
|
+
},
|
|
17005
|
+
{
|
|
17006
|
+
key: `${model.name}:create`,
|
|
17007
|
+
candidate: `${model.name}Create`
|
|
17008
|
+
},
|
|
17009
|
+
{
|
|
17010
|
+
key: `${model.name}:update`,
|
|
17011
|
+
candidate: `${model.name}Update`
|
|
17012
|
+
}
|
|
17013
|
+
]), [], (name) => name.toLowerCase());
|
|
17014
|
+
return (model) => ({
|
|
17015
|
+
row: names.get(`${model.name}:row`) ?? model.name,
|
|
17016
|
+
create: names.get(`${model.name}:create`) ?? `${model.name}Create`,
|
|
17017
|
+
update: names.get(`${model.name}:update`) ?? `${model.name}Update`
|
|
17018
|
+
});
|
|
17019
|
+
}
|
|
17020
|
+
/** The resource each model's paths are under: its name in plural kebab-case, `order-items`. */
|
|
17021
|
+
function resourcesOf(models) {
|
|
17022
|
+
const resources = allocate(models.map((model) => ({
|
|
17023
|
+
key: model.name,
|
|
17024
|
+
candidate: pluralize(makeSnakeCase(model.name)).replaceAll("_", "-")
|
|
17025
|
+
})), [], (name) => name);
|
|
17026
|
+
return (model) => resources.get(model.name) ?? model.name;
|
|
17027
|
+
}
|
|
17028
|
+
/**
|
|
17029
|
+
* The security scheme the document names for each kind of `auth`: a bearer JWT for `jwt` and
|
|
17030
|
+
* `jwks`, and for `cloudflare-access` the header Cloudflare Access puts its token in.
|
|
17031
|
+
*/
|
|
17032
|
+
function securityScheme(kind) {
|
|
17033
|
+
return kind === "cloudflare-access" ? {
|
|
17034
|
+
name: "cloudflareAccess",
|
|
17035
|
+
scheme: {
|
|
17036
|
+
type: "apiKey",
|
|
17037
|
+
in: "header",
|
|
17038
|
+
name: "Cf-Access-Jwt-Assertion"
|
|
17039
|
+
},
|
|
17040
|
+
missing: "No valid Cloudflare Access token."
|
|
17041
|
+
} : {
|
|
17042
|
+
name: "bearerAuth",
|
|
17043
|
+
scheme: {
|
|
17044
|
+
type: "http",
|
|
17045
|
+
scheme: "bearer",
|
|
17046
|
+
bearerFormat: "JWT"
|
|
17047
|
+
},
|
|
17048
|
+
missing: "No valid bearer token."
|
|
17049
|
+
};
|
|
17050
|
+
}
|
|
17051
|
+
/** Whether a YAML value is a map, as an operation or a set of responses is. */
|
|
17052
|
+
function isMap(value) {
|
|
17053
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
17054
|
+
}
|
|
17055
|
+
/** An operation that asks for the token, and says it answers 401 without one, 403 without a role. */
|
|
17056
|
+
function guardedOperation(operation, security) {
|
|
17057
|
+
const responses = operation.responses;
|
|
17058
|
+
return {
|
|
17059
|
+
...operation,
|
|
17060
|
+
security: [{ [security.name]: [] }],
|
|
17061
|
+
responses: {
|
|
17062
|
+
...isMap(responses) ? responses : {},
|
|
17063
|
+
"401": { description: security.missing },
|
|
17064
|
+
"403": { description: "The token holds none of the roles the API asks for." }
|
|
17065
|
+
}
|
|
17066
|
+
};
|
|
17067
|
+
}
|
|
17068
|
+
/** A path item with every operation guarded, its `parameters` as they are. */
|
|
17069
|
+
function guardedItem(item, security) {
|
|
17070
|
+
return Object.fromEntries(Object.entries(item).map(([key, value]) => key !== "parameters" && isMap(value) ? [key, guardedOperation(value, security)] : [key, value]));
|
|
17071
|
+
}
|
|
17072
|
+
/**
|
|
17073
|
+
* The OpenAPI 3.1 document of the CRUD of every model, shaped as Prisma Client reads and writes
|
|
17074
|
+
* the rows: fields under their Prisma names, enums by their members' names, a list never null.
|
|
17075
|
+
* Each model's paths are under its name in plural kebab-case (`/order-items`), and its schemas are
|
|
17076
|
+
* the row and what a `POST` and a `PATCH` take. With `auth`, every operation asks for the token
|
|
17077
|
+
* its kind takes (`bearerAuth`, or `cloudflareAccess`). Hono Takibi turns it into the routes.
|
|
17078
|
+
*/
|
|
17079
|
+
function zodOpenapiHonoDocument(datamodel, config) {
|
|
17080
|
+
const { models, enums } = datamodel;
|
|
17081
|
+
const names = schemaNames(models);
|
|
17082
|
+
const resource = resourcesOf(models);
|
|
17083
|
+
const security = config.auth === void 0 ? void 0 : securityScheme(config.auth);
|
|
17084
|
+
return {
|
|
17085
|
+
openapi: "3.1.0",
|
|
17086
|
+
info: {
|
|
17087
|
+
title: config.title,
|
|
17088
|
+
version: config.version
|
|
17089
|
+
},
|
|
17090
|
+
paths: Object.fromEntries(models.flatMap((model) => makePaths(model, enums, resource(model), names(model))).map(([path, item]) => [path, security ? guardedItem(item, security) : item])),
|
|
17091
|
+
components: {
|
|
17092
|
+
schemas: Object.fromEntries(models.flatMap((model) => {
|
|
17093
|
+
const name = names(model);
|
|
17094
|
+
return [
|
|
17095
|
+
[name.row, makeRowSchema(model, enums)],
|
|
17096
|
+
[name.create, makeInputSchema(model, enums, "create")],
|
|
17097
|
+
[name.update, makeInputSchema(model, enums, "update")]
|
|
17098
|
+
];
|
|
17099
|
+
})),
|
|
17100
|
+
...security ? { securitySchemes: { [security.name]: security.scheme } } : {}
|
|
17101
|
+
}
|
|
17102
|
+
};
|
|
17103
|
+
}
|
|
17104
|
+
/** The document as YAML. */
|
|
17105
|
+
function zodOpenapiHonoYaml(datamodel, config) {
|
|
17106
|
+
return toYaml(zodOpenapiHonoDocument(datamodel, config), { flow: ["type"] });
|
|
17107
|
+
}
|
|
17108
|
+
/** The paths the app guards with `auth`: every model's resource and what is under it. */
|
|
17109
|
+
function guardedPaths(datamodel) {
|
|
17110
|
+
const resource = resourcesOf(datamodel.models);
|
|
17111
|
+
return datamodel.models.map((model) => `/${resource(model)}/*`);
|
|
17112
|
+
}
|
|
17113
|
+
/** The body of every handler, by the operation id of its route. */
|
|
17114
|
+
function handlerBodies(datamodel) {
|
|
17115
|
+
return new Map(datamodel.models.flatMap((model) => makeHandlerBodies(model)));
|
|
17116
|
+
}
|
|
17117
|
+
/** A file's top-level statements, or none when it does not parse: a file is never patched half-read. */
|
|
17118
|
+
function statementsOf(code) {
|
|
17119
|
+
const { program, errors } = parseSync("file.ts", code, {
|
|
17120
|
+
lang: "ts",
|
|
17121
|
+
sourceType: "module"
|
|
17122
|
+
});
|
|
17123
|
+
return errors.length > 0 ? [] : program.body;
|
|
17124
|
+
}
|
|
17125
|
+
/** The `const` declarators of a statement, exported or not. */
|
|
17126
|
+
function declaratorsOf(statement) {
|
|
17127
|
+
const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
|
|
17128
|
+
return declaration?.type === "VariableDeclaration" ? declaration.declarations : [];
|
|
17129
|
+
}
|
|
17130
|
+
/** The name an identifier node has, or undefined for any other node. */
|
|
17131
|
+
function identifierName(node) {
|
|
17132
|
+
return node?.type === "Identifier" && "name" in node ? String(node.name) : void 0;
|
|
17133
|
+
}
|
|
17134
|
+
/** The text of a string literal node, or undefined for any other node. */
|
|
17135
|
+
function stringValue(node) {
|
|
17136
|
+
return node?.type === "Literal" && "value" in node && typeof node.value === "string" ? node.value : void 0;
|
|
17137
|
+
}
|
|
17138
|
+
/** Whether an import of the file brings in `name`. */
|
|
17139
|
+
function importsName(statements, name) {
|
|
17140
|
+
return statements.some((statement) => statement.type === "ImportDeclaration" && (statement.specifiers ?? []).some((specifier) => specifier.local.name === name));
|
|
17141
|
+
}
|
|
17142
|
+
/** `line` added after the last import of the file, or at its top when it has none. */
|
|
17143
|
+
function addImport(code, statements, line) {
|
|
17144
|
+
const last = statements.findLast((statement) => statement.type === "ImportDeclaration");
|
|
17145
|
+
return last === void 0 ? `${line}\n${code}` : `${code.slice(0, last.end)}\n${line}${code.slice(last.end)}`;
|
|
17146
|
+
}
|
|
17147
|
+
/**
|
|
17148
|
+
* The operation id of each route of the routes file Hono Takibi wrote, by the route's name:
|
|
17149
|
+
* `export const getUsersIdRoute = createRoute({ operationId: 'getUser', ... })` → `getUser`.
|
|
17150
|
+
*/
|
|
17151
|
+
function routeOperations(routes) {
|
|
17152
|
+
return new Map(statementsOf(routes).flatMap(declaratorsOf).flatMap((declarator) => {
|
|
17153
|
+
const name = identifierName(declarator.id);
|
|
17154
|
+
const init = declarator.init;
|
|
17155
|
+
if (name === void 0 || init?.type !== "CallExpression") return [];
|
|
17156
|
+
if (identifierName(init.callee) !== "createRoute") return [];
|
|
17157
|
+
const options = init.arguments[0];
|
|
17158
|
+
if (options?.type !== "ObjectExpression") return [];
|
|
17159
|
+
const operationId = options.properties.flatMap((property) => property.type === "Property" && identifierName(property.key) === "operationId" ? [stringValue(property.value)] : []).at(0);
|
|
17160
|
+
return operationId === void 0 ? [] : [[name, operationId]];
|
|
17161
|
+
}));
|
|
17162
|
+
}
|
|
17163
|
+
/** The route a `RouteHandler<typeof route>` annotation names. */
|
|
17164
|
+
function handledRoute(declarator) {
|
|
17165
|
+
const annotation = declarator.id.typeAnnotation?.typeAnnotation;
|
|
17166
|
+
if (annotation?.type !== "TSTypeReference") return void 0;
|
|
17167
|
+
if (identifierName(annotation.typeName) !== "RouteHandler") return void 0;
|
|
17168
|
+
const query = annotation.typeArguments?.params[0];
|
|
17169
|
+
return query?.type === "TSTypeQuery" ? identifierName(query.exprName) : void 0;
|
|
17170
|
+
}
|
|
17171
|
+
/**
|
|
17172
|
+
* A handler file Hono Takibi's template wrote, with each `RouteHandler` it left empty filled with
|
|
17173
|
+
* the body for the operation id of its route, and `prisma` imported from `prismaImport` when one
|
|
17174
|
+
* is filled. A handler is empty when nothing, not even a comment, is between its braces; one with
|
|
17175
|
+
* a body, written by a previous run or by hand, is kept as it is, as Hono Takibi keeps it.
|
|
17176
|
+
*/
|
|
17177
|
+
function fillHandlers(code, operations, bodies, prismaImport) {
|
|
17178
|
+
const statements = statementsOf(code);
|
|
17179
|
+
const fills = statements.flatMap(declaratorsOf).flatMap((declarator) => {
|
|
17180
|
+
const route = handledRoute(declarator);
|
|
17181
|
+
const init = declarator.init;
|
|
17182
|
+
if (route === void 0 || init?.type !== "ArrowFunctionExpression") return [];
|
|
17183
|
+
if (init.body.type !== "BlockStatement") return [];
|
|
17184
|
+
if (code.slice(init.body.start + 1, init.body.end - 1).trim() !== "") return [];
|
|
17185
|
+
const operationId = operations.get(route);
|
|
17186
|
+
const body = operationId === void 0 ? void 0 : bodies.get(operationId);
|
|
17187
|
+
return body === void 0 ? [] : [{
|
|
17188
|
+
start: init.start,
|
|
17189
|
+
end: init.end,
|
|
17190
|
+
body
|
|
17191
|
+
}];
|
|
17192
|
+
});
|
|
17193
|
+
if (fills.length === 0) return code;
|
|
17194
|
+
const filled = fills.reduceRight((text, fill) => `${text.slice(0, fill.start)}async (c) => {\n${fill.body}\n}${text.slice(fill.end)}`, code);
|
|
17195
|
+
return importsName(statements, "prisma") ? filled : addImport(filled, statementsOf(filled), `import { prisma } from '${prismaImport}'`);
|
|
17196
|
+
}
|
|
17197
|
+
/**
|
|
17198
|
+
* The app entry Hono Takibi wrote, with `auth` imported from `./auth` and run on every path of
|
|
17199
|
+
* `paths`, `app.use('/users/*', auth)` after the app is made or after the last such line. A path
|
|
17200
|
+
* already guarded is left as it is; a file without `new OpenAPIHono()` is left as it is.
|
|
17201
|
+
*/
|
|
17202
|
+
function guardPaths(code, paths) {
|
|
17203
|
+
const statements = statementsOf(code);
|
|
17204
|
+
const appStatement = statements[statements.findIndex((statement) => declaratorsOf(statement).some((declarator) => declarator.init?.type === "NewExpression" && identifierName(declarator.init.callee) === "OpenAPIHono"))];
|
|
17205
|
+
const app = appStatement === void 0 ? void 0 : declaratorsOf(appStatement)[0];
|
|
17206
|
+
const appName = app === void 0 ? void 0 : identifierName(app.id);
|
|
17207
|
+
if (appStatement === void 0 || appName === void 0) return code;
|
|
17208
|
+
const guards = statements.filter((statement) => {
|
|
17209
|
+
if (statement.type !== "ExpressionStatement") return false;
|
|
17210
|
+
const call = statement.expression;
|
|
17211
|
+
if (call.type !== "CallExpression" || call.callee.type !== "MemberExpression") return false;
|
|
17212
|
+
return identifierName(call.callee.object) === appName && identifierName(call.callee.property) === "use" && identifierName(call.arguments[1]) === "auth";
|
|
17213
|
+
});
|
|
17214
|
+
const guarded = new Set(guards.flatMap((statement) => statement.type === "ExpressionStatement" && statement.expression.type === "CallExpression" ? [stringValue(statement.expression.arguments[0])] : []));
|
|
17215
|
+
const missing = paths.filter((path) => !guarded.has(path));
|
|
17216
|
+
if (missing.length === 0) return code;
|
|
17217
|
+
const at = (guards.at(-1) ?? appStatement).end;
|
|
17218
|
+
const lines = missing.map((path) => `${appName}.use('${path}', auth)`).join("\n");
|
|
17219
|
+
const guardedCode = `${code.slice(0, at)}\n${guards.length === 0 ? "\n" : ""}${lines}${code.slice(at)}`;
|
|
17220
|
+
return importsName(statements, "auth") ? guardedCode : addImport(guardedCode, statementsOf(guardedCode), "import { auth } from './auth'");
|
|
17221
|
+
}
|
|
17222
|
+
/**
|
|
17223
|
+
* The claims every module checks after the signature, read from `c.get('jwtPayload')` (unknown
|
|
17224
|
+
* until read): `exp` and `iat`, which hono/jwt checks only when a token has them, and the roles a
|
|
17225
|
+
* token must hold one of. `roles` is what `REQUIRED_ROLES` starts as, with the comment that says
|
|
17226
|
+
* why.
|
|
17227
|
+
*/
|
|
17228
|
+
function claimChecks(roles) {
|
|
17229
|
+
return `/** A claim of the token's payload when it is a number, and undefined otherwise. */
|
|
17230
|
+
function numberClaim(payload: unknown, name: string) {
|
|
17231
|
+
if (typeof payload !== 'object' || payload === null) return undefined
|
|
17232
|
+
const value: unknown = Reflect.get(payload, name)
|
|
17233
|
+
return typeof value === 'number' ? value : undefined
|
|
17234
|
+
}
|
|
17235
|
+
|
|
17236
|
+
/** The 401 a token is refused with when it is missing or lacks a claim it must have. */
|
|
17237
|
+
function unauthorized(description: string) {
|
|
17238
|
+
return new HTTPException(401, {
|
|
17239
|
+
res: new Response('Unauthorized', {
|
|
17240
|
+
status: 401,
|
|
17241
|
+
headers: {
|
|
17242
|
+
'WWW-Authenticate': 'Bearer error="invalid_token",error_description="' + description + '"',
|
|
17243
|
+
},
|
|
17244
|
+
}),
|
|
17245
|
+
})
|
|
17246
|
+
}
|
|
17247
|
+
|
|
17248
|
+
/** The claim of the token that holds the roles of its user: a string, or an array of strings. */
|
|
17249
|
+
const ROLE_CLAIM = 'role'
|
|
17250
|
+
|
|
17251
|
+
${roles.comment}
|
|
17252
|
+
const REQUIRED_ROLES: readonly string[] = ${roles.value}
|
|
17253
|
+
|
|
17254
|
+
/** The roles the token's payload holds under ROLE_CLAIM. */
|
|
17255
|
+
function rolesOf(payload: unknown): readonly string[] {
|
|
17256
|
+
if (typeof payload !== 'object' || payload === null) return []
|
|
17257
|
+
const value: unknown = Reflect.get(payload, ROLE_CLAIM)
|
|
17258
|
+
if (typeof value === 'string') return [value]
|
|
17259
|
+
return Array.isArray(value) ? value.filter((role) => typeof role === 'string') : []
|
|
17260
|
+
}
|
|
17261
|
+
|
|
17262
|
+
/** Whether the token holds one of REQUIRED_ROLES, or none is asked for. */
|
|
17263
|
+
function hasRequiredRole(payload: unknown) {
|
|
17264
|
+
if (REQUIRED_ROLES.length === 0) return true
|
|
17265
|
+
return rolesOf(payload).some((role) => REQUIRED_ROLES.includes(role))
|
|
17266
|
+
}
|
|
17267
|
+
|
|
17268
|
+
/** The 403 a valid token is refused with when it lacks every role REQUIRED_ROLES names. */
|
|
17269
|
+
function forbidden() {
|
|
17270
|
+
return new HTTPException(403, { res: new Response('Forbidden', { status: 403 }) })
|
|
17271
|
+
}`;
|
|
17272
|
+
}
|
|
17273
|
+
/** `REQUIRED_ROLES` of a token any issuer signs: only an admin reaches the API until it says more. */
|
|
17274
|
+
const ADMIN_ONLY = {
|
|
17275
|
+
comment: `/**
|
|
17276
|
+
* The roles of which a token must hold one to reach the API, answered 403 otherwise. The API
|
|
17277
|
+
* writes every model, so only an admin reaches it until this says who else may; an empty list
|
|
17278
|
+
* lets any valid token through.
|
|
17279
|
+
*/`,
|
|
17280
|
+
value: "['admin']"
|
|
17281
|
+
};
|
|
17282
|
+
/**
|
|
17283
|
+
* The keys an issuer publishes as a JWKS, fetched and cached: `keysFor(uri, token)` answers the
|
|
17284
|
+
* cached keys, fetched again after ten minutes, or for a `kid` they lack at most once a minute.
|
|
17285
|
+
*/
|
|
17286
|
+
const JWKS_KEYS = `/** How long the keys fetched from the issuer are used before they are fetched again. */
|
|
17287
|
+
const JWKS_CACHE_SECONDS = 10 * 60
|
|
17288
|
+
|
|
17289
|
+
/** The least time between two fetches for a \`kid\` the cache lacks: no token hammers the issuer. */
|
|
17290
|
+
const JWKS_REFETCH_SECONDS = 60
|
|
17291
|
+
|
|
17292
|
+
let cache: { uri: string; keys: HonoJsonWebKey[]; fetchedAt: number } | undefined
|
|
17293
|
+
|
|
17294
|
+
/** The keys the issuer publishes, fetched and cached. */
|
|
17295
|
+
async function fetchKeys(uri: string) {
|
|
17296
|
+
const response = await fetch(uri)
|
|
17297
|
+
if (!response.ok) throw new Error('The issuer answered ' + response.status + ' for its keys')
|
|
17298
|
+
const body: unknown = await response.json()
|
|
17299
|
+
const keys: unknown =
|
|
17300
|
+
typeof body === 'object' && body !== null ? Reflect.get(body, 'keys') : undefined
|
|
17301
|
+
if (!Array.isArray(keys)) throw new Error('The issuer answered no keys')
|
|
17302
|
+
cache = { uri, keys, fetchedAt: Date.now() }
|
|
17303
|
+
return cache.keys
|
|
17304
|
+
}
|
|
17305
|
+
|
|
17306
|
+
/** The keys for a token: the cached ones, fetched again when they are old or lack its \`kid\`. */
|
|
17307
|
+
async function keysFor(uri: string, token: string | undefined) {
|
|
17308
|
+
if (cache === undefined || cache.uri !== uri) return fetchKeys(uri)
|
|
17309
|
+
const age = (Date.now() - cache.fetchedAt) / 1000
|
|
17310
|
+
if (age > JWKS_CACHE_SECONDS) return fetchKeys(uri)
|
|
17311
|
+
const kid = token === undefined ? undefined : decode(token).header.kid
|
|
17312
|
+
const known = cache.keys.some((key) => key.kid === kid)
|
|
17313
|
+
return known || age < JWKS_REFETCH_SECONDS ? cache.keys : fetchKeys(uri)
|
|
17314
|
+
}`;
|
|
17315
|
+
/**
|
|
17316
|
+
* `auth = "jwt"`: a JWT signed with HS256 by `JWT_SECRET`, from the issuer `JWT_ISSUER` for the
|
|
17317
|
+
* audience `JWT_AUDIENCE`, that has an `exp` at most an hour after its `iat` and the `admin`
|
|
17318
|
+
* role. hono/jwt checks `exp` and `iat` only when a token has them, so a token without them,
|
|
17319
|
+
* which would never expire, is refused here. A missing variable or a secret shorter than 32 bytes
|
|
17320
|
+
* fails every request.
|
|
17321
|
+
*/
|
|
17322
|
+
function jwtAuthModule() {
|
|
17323
|
+
return `import { env } from 'hono/adapter'
|
|
17324
|
+
import { createMiddleware } from 'hono/factory'
|
|
17325
|
+
import { HTTPException } from 'hono/http-exception'
|
|
17326
|
+
import { jwt } from 'hono/jwt'
|
|
17327
|
+
|
|
17328
|
+
/** The longest a token may live, from its \`iat\` to its \`exp\`: one issued for longer is refused. */
|
|
17329
|
+
const MAX_TOKEN_LIFETIME_SECONDS = 60 * 60
|
|
17330
|
+
|
|
17331
|
+
/** The fewest bytes \`JWT_SECRET\` may have: HS256 takes a key no shorter than its 32-byte hash. */
|
|
17332
|
+
const MIN_SECRET_BYTES = 32
|
|
17333
|
+
|
|
17334
|
+
${claimChecks(ADMIN_ONLY)}
|
|
17335
|
+
|
|
17336
|
+
/**
|
|
17337
|
+
* Lets a request through with a JWT in \`Authorization: Bearer <token>\`, signed with HS256 by the
|
|
17338
|
+
* secret \`JWT_SECRET\`, issued by \`JWT_ISSUER\` for \`JWT_AUDIENCE\`, with an \`exp\` at most
|
|
17339
|
+
* MAX_TOKEN_LIFETIME_SECONDS after its \`iat\`, and answers 401 otherwise; a token without one of
|
|
17340
|
+
* REQUIRED_ROLES is answered 403. The variables are read from the environment of the runtime
|
|
17341
|
+
* (\`process.env\` on Node, the bindings on Workers). Without one of them, or with a secret shorter
|
|
17342
|
+
* than MIN_SECRET_BYTES, every request fails with 500: the app never runs unguarded. A handler
|
|
17343
|
+
* reads the token's payload with \`c.get('jwtPayload')\`.
|
|
17344
|
+
*/
|
|
17345
|
+
export const auth = createMiddleware(async (c, next) => {
|
|
17346
|
+
const { JWT_SECRET, JWT_ISSUER, JWT_AUDIENCE } = env<{
|
|
17347
|
+
JWT_SECRET?: string
|
|
17348
|
+
JWT_ISSUER?: string
|
|
17349
|
+
JWT_AUDIENCE?: string
|
|
17350
|
+
}>(c)
|
|
17351
|
+
if (!JWT_SECRET || new TextEncoder().encode(JWT_SECRET).length < MIN_SECRET_BYTES) {
|
|
17352
|
+
throw new Error('JWT_SECRET must be a random secret of at least 32 bytes')
|
|
17353
|
+
}
|
|
17354
|
+
if (!JWT_ISSUER || !JWT_AUDIENCE) throw new Error('JWT_ISSUER and JWT_AUDIENCE must be set')
|
|
17355
|
+
const verify = jwt({
|
|
17356
|
+
secret: JWT_SECRET,
|
|
17357
|
+
alg: 'HS256',
|
|
17358
|
+
verification: { iss: JWT_ISSUER, aud: JWT_AUDIENCE },
|
|
17359
|
+
})
|
|
17360
|
+
return verify(c, async () => {
|
|
17361
|
+
// hono/jwt checks exp and iat only when the token has them: one without either never expires.
|
|
17362
|
+
const payload = c.get('jwtPayload')
|
|
17363
|
+
const exp = numberClaim(payload, 'exp')
|
|
17364
|
+
const iat = numberClaim(payload, 'iat')
|
|
17365
|
+
if (exp === undefined || iat === undefined) throw unauthorized('token without exp or iat')
|
|
17366
|
+
if (exp - iat > MAX_TOKEN_LIFETIME_SECONDS) throw unauthorized('token lives too long')
|
|
17367
|
+
if (!hasRequiredRole(payload)) throw forbidden()
|
|
17368
|
+
await next()
|
|
17369
|
+
})
|
|
17370
|
+
})
|
|
17371
|
+
`;
|
|
17372
|
+
}
|
|
17373
|
+
/**
|
|
17374
|
+
* `auth = "jwks"`: a JWT signed with an asymmetric key that the issuer publishes at `JWKS_URI`
|
|
17375
|
+
* (an identity provider: Auth0, Clerk, Okta), from `JWT_ISSUER` for `JWT_AUDIENCE`, that has an
|
|
17376
|
+
* `exp` and the `admin` role. The app holds no secret that signs a token.
|
|
17377
|
+
*/
|
|
17378
|
+
function jwksAuthModule() {
|
|
17379
|
+
return `import { env } from 'hono/adapter'
|
|
17380
|
+
import { createMiddleware } from 'hono/factory'
|
|
17381
|
+
import { HTTPException } from 'hono/http-exception'
|
|
17382
|
+
import { jwk } from 'hono/jwk'
|
|
17383
|
+
import { decode } from 'hono/jwt'
|
|
17384
|
+
import type { HonoJsonWebKey } from 'hono/utils/jwt/jws'
|
|
17385
|
+
|
|
17386
|
+
/** The algorithms a token may be signed with: asymmetric only, so no key here signs one. */
|
|
17387
|
+
const ALGORITHMS = ['RS256', 'PS256', 'ES256', 'EdDSA'] as const
|
|
17388
|
+
|
|
17389
|
+
${claimChecks(ADMIN_ONLY)}
|
|
17390
|
+
|
|
17391
|
+
${JWKS_KEYS}
|
|
17392
|
+
|
|
17393
|
+
/** \`JWKS_URI\` when it is https, or http on this machine (an issuer run for development). */
|
|
17394
|
+
function jwksUri(uri: string) {
|
|
17395
|
+
const url = new URL(uri)
|
|
17396
|
+
const local = url.hostname === 'localhost' || url.hostname === '127.0.0.1'
|
|
17397
|
+
if (url.protocol === 'https:' || (url.protocol === 'http:' && local)) return url.href
|
|
17398
|
+
throw new Error('JWKS_URI must be an https URL')
|
|
17399
|
+
}
|
|
17400
|
+
|
|
17401
|
+
/**
|
|
17402
|
+
* Lets a request through with a JWT in \`Authorization: Bearer <token>\`, signed with a key the
|
|
17403
|
+
* issuer publishes at \`JWKS_URI\`, issued by \`JWT_ISSUER\` for \`JWT_AUDIENCE\`, with an \`exp\`, and
|
|
17404
|
+
* answers 401 otherwise; a token without one of REQUIRED_ROLES is answered 403. The variables are
|
|
17405
|
+
* read from the environment of the runtime (\`process.env\` on Node, the bindings on Workers).
|
|
17406
|
+
* Without one of them every request fails with 500: the app never runs unguarded. A handler reads
|
|
17407
|
+
* the token's payload with \`c.get('jwtPayload')\`.
|
|
17408
|
+
*/
|
|
17409
|
+
export const auth = createMiddleware(async (c, next) => {
|
|
17410
|
+
const { JWKS_URI, JWT_ISSUER, JWT_AUDIENCE } = env<{
|
|
17411
|
+
JWKS_URI?: string
|
|
17412
|
+
JWT_ISSUER?: string
|
|
17413
|
+
JWT_AUDIENCE?: string
|
|
17414
|
+
}>(c)
|
|
17415
|
+
if (!JWKS_URI || !JWT_ISSUER || !JWT_AUDIENCE) {
|
|
17416
|
+
throw new Error('JWKS_URI, JWT_ISSUER and JWT_AUDIENCE must be set')
|
|
17417
|
+
}
|
|
17418
|
+
const uri = jwksUri(JWKS_URI)
|
|
17419
|
+
const verify = jwk({
|
|
17420
|
+
keys: (ctx) => keysFor(uri, ctx.req.header('Authorization')?.split(/\\s+/)[1]),
|
|
17421
|
+
alg: [...ALGORITHMS],
|
|
17422
|
+
verification: { iss: JWT_ISSUER, aud: JWT_AUDIENCE },
|
|
17423
|
+
})
|
|
17424
|
+
return verify(c, async () => {
|
|
17425
|
+
// hono/jwt checks exp only when the token has it: one without it never expires.
|
|
17426
|
+
const payload = c.get('jwtPayload')
|
|
17427
|
+
if (numberClaim(payload, 'exp') === undefined) throw unauthorized('token without exp')
|
|
17428
|
+
if (!hasRequiredRole(payload)) throw forbidden()
|
|
17429
|
+
await next()
|
|
17430
|
+
})
|
|
17431
|
+
})
|
|
17432
|
+
`;
|
|
17433
|
+
}
|
|
17434
|
+
/**
|
|
17435
|
+
* `auth = "cloudflare-access"`: the JWT Cloudflare Access puts in `Cf-Access-Jwt-Assertion` on a
|
|
17436
|
+
* request its policy let through, signed with RS256 by a key the team publishes at
|
|
17437
|
+
* `<team domain>/cdn-cgi/access/certs`, issued by the team domain for the application's AUD tag.
|
|
17438
|
+
* Access's token carries no role: its policy decides who passes, so `REQUIRED_ROLES` starts empty.
|
|
17439
|
+
* The signature is checked all the same, so a request that reaches the app around Access (its
|
|
17440
|
+
* `workers.dev` URL, the origin's own address) is refused.
|
|
17441
|
+
*/
|
|
17442
|
+
function cloudflareAccessAuthModule() {
|
|
17443
|
+
return `import { env } from 'hono/adapter'
|
|
17444
|
+
import { createMiddleware } from 'hono/factory'
|
|
17445
|
+
import { HTTPException } from 'hono/http-exception'
|
|
17446
|
+
import { decode, verifyWithJwks } from 'hono/jwt'
|
|
17447
|
+
import type { HonoJsonWebKey } from 'hono/utils/jwt/jws'
|
|
17448
|
+
|
|
17449
|
+
/** The header Cloudflare Access puts its token in, as it is, without \`Bearer\`. */
|
|
17450
|
+
const ACCESS_HEADER = 'Cf-Access-Jwt-Assertion'
|
|
17451
|
+
|
|
17452
|
+
/** The path under the team domain where Access publishes its keys. */
|
|
17453
|
+
const ACCESS_CERTS_PATH = '/cdn-cgi/access/certs'
|
|
17454
|
+
|
|
17455
|
+
${claimChecks({
|
|
17456
|
+
comment: `/**
|
|
17457
|
+
* The roles of which a token must hold one, answered 403 otherwise. Cloudflare Access's token
|
|
17458
|
+
* carries no role: its policy decides who reaches the app, so none is asked for here. Name roles
|
|
17459
|
+
* (and ROLE_CLAIM) when the identity provider's groups are passed into the token.
|
|
17460
|
+
*/`,
|
|
17461
|
+
value: "[]"
|
|
17462
|
+
})}
|
|
17463
|
+
|
|
17464
|
+
${JWKS_KEYS}
|
|
17465
|
+
|
|
17466
|
+
/** The team domain, \`https://<team>.cloudflareaccess.com\`, as the token's \`iss\` names it. */
|
|
17467
|
+
function teamDomain(domain: string) {
|
|
17468
|
+
const url = new URL(domain)
|
|
17469
|
+
if (url.protocol !== 'https:') throw new Error('CF_ACCESS_TEAM_DOMAIN must be an https URL')
|
|
17470
|
+
return url.origin
|
|
17471
|
+
}
|
|
17472
|
+
|
|
17473
|
+
/**
|
|
17474
|
+
* Lets a request through with the token Cloudflare Access puts in \`Cf-Access-Jwt-Assertion\`,
|
|
17475
|
+
* signed with a key the team publishes, issued by \`CF_ACCESS_TEAM_DOMAIN\` for the application
|
|
17476
|
+
* \`CF_ACCESS_AUD\` (its Application Audience tag), with an \`exp\`, and answers 401 otherwise. The
|
|
17477
|
+
* variables are read from the environment of the runtime (\`process.env\` on Node, the bindings
|
|
17478
|
+
* on Workers). Without one of them every request fails with 500: the app never runs unguarded. A
|
|
17479
|
+
* handler reads the token's payload (\`email\`, \`sub\`) with \`c.get('jwtPayload')\`.
|
|
17480
|
+
*/
|
|
17481
|
+
export const auth = createMiddleware(async (c, next) => {
|
|
17482
|
+
const { CF_ACCESS_TEAM_DOMAIN, CF_ACCESS_AUD } = env<{
|
|
17483
|
+
CF_ACCESS_TEAM_DOMAIN?: string
|
|
17484
|
+
CF_ACCESS_AUD?: string
|
|
17485
|
+
}>(c)
|
|
17486
|
+
if (!CF_ACCESS_TEAM_DOMAIN || !CF_ACCESS_AUD) {
|
|
17487
|
+
throw new Error('CF_ACCESS_TEAM_DOMAIN and CF_ACCESS_AUD must be set')
|
|
17488
|
+
}
|
|
17489
|
+
const issuer = teamDomain(CF_ACCESS_TEAM_DOMAIN)
|
|
17490
|
+
const token = c.req.header(ACCESS_HEADER)
|
|
17491
|
+
if (!token) throw unauthorized('no ' + ACCESS_HEADER)
|
|
17492
|
+
const payload = await keysFor(issuer + ACCESS_CERTS_PATH, token)
|
|
17493
|
+
.then((keys) =>
|
|
17494
|
+
verifyWithJwks(token, {
|
|
17495
|
+
keys,
|
|
17496
|
+
allowedAlgorithms: ['RS256'],
|
|
17497
|
+
verification: { iss: issuer, aud: CF_ACCESS_AUD },
|
|
17498
|
+
}),
|
|
17499
|
+
)
|
|
17500
|
+
.catch((error: unknown) => {
|
|
17501
|
+
// The keys not fetched is the app's failure (500); anything else is the token's (401).
|
|
17502
|
+
if (error instanceof Error && error.constructor === Error) throw error
|
|
17503
|
+
throw unauthorized('token verification failure')
|
|
17504
|
+
})
|
|
17505
|
+
// hono/jwt checks exp only when the token has it: one without it never expires.
|
|
17506
|
+
if (numberClaim(payload, 'exp') === undefined) throw unauthorized('token without exp')
|
|
17507
|
+
if (!hasRequiredRole(payload)) throw forbidden()
|
|
17508
|
+
c.set('jwtPayload', payload)
|
|
17509
|
+
await next()
|
|
17510
|
+
})
|
|
17511
|
+
`;
|
|
17512
|
+
}
|
|
17513
|
+
/**
|
|
17514
|
+
* The module the app guards its paths with, written once and the user's to change after, its
|
|
17515
|
+
* settings read from the environment of the runtime: `jwt` checks an HS256 signature with
|
|
17516
|
+
* `JWT_SECRET`, `jwks` an asymmetric one with the keys published at `JWKS_URI`, both on a JWT in
|
|
17517
|
+
* `Authorization: Bearer <token>`; `cloudflare-access` checks the token Cloudflare Access puts in
|
|
17518
|
+
* `Cf-Access-Jwt-Assertion` with the keys of the team.
|
|
17519
|
+
*/
|
|
17520
|
+
function authModule(kind) {
|
|
17521
|
+
if (kind === "jwt") return jwtAuthModule();
|
|
17522
|
+
if (kind === "jwks") return jwksAuthModule();
|
|
17523
|
+
return cloudflareAccessAuthModule();
|
|
17524
|
+
}
|
|
17525
|
+
// src/core/zod-openapi-hono.ts
|
|
17526
|
+
/** `prisma` as a file in `handlers/` imports it: a relative module one directory further up. */
|
|
17527
|
+
function fromHandlers(specifier) {
|
|
17528
|
+
return specifier.startsWith("./") || specifier.startsWith("../") ? path.posix.join("..", specifier) : specifier;
|
|
17529
|
+
}
|
|
17530
|
+
/** Runs Hono Takibi's template on the document, loaded only for this generator. */
|
|
17531
|
+
function honoTakibi(input, output) {
|
|
17532
|
+
return Effect.tryPromise({
|
|
17533
|
+
try: async () => {
|
|
17534
|
+
const { generate } = await import("hono-takibi/generate");
|
|
17535
|
+
return generate({
|
|
17536
|
+
input,
|
|
17537
|
+
output,
|
|
17538
|
+
template: { routeHandler: true }
|
|
17539
|
+
});
|
|
17540
|
+
},
|
|
17541
|
+
catch: (error) => new HonoTakibiError({ message: `Hekireki-ZodOpenAPIHono runs hono-takibi (npm install -D hono-takibi): ${error instanceof Error ? error.message : String(error)}` })
|
|
17542
|
+
});
|
|
17543
|
+
}
|
|
17544
|
+
/** Fills the empty handlers of one handler file, and leaves a file with none as it is. */
|
|
17545
|
+
function fillHandlerFile(file, operations, bodies, prismaImport) {
|
|
17546
|
+
return Effect.gen(function* () {
|
|
17547
|
+
const code = yield* readFile(file);
|
|
17548
|
+
const filled = fillHandlers(code, operations, bodies, prismaImport);
|
|
17549
|
+
if (filled !== code) yield* writeFile(file, yield* fmt(filled));
|
|
17550
|
+
});
|
|
17551
|
+
}
|
|
17552
|
+
/**
|
|
17553
|
+
* `auth.ts` of the kind `auth` names, written when it is not there and the user's after, and the
|
|
17554
|
+
* app entry with `auth` on every model's paths.
|
|
17555
|
+
*/
|
|
17556
|
+
function guardApp(output, kind, paths) {
|
|
17557
|
+
return Effect.gen(function* () {
|
|
17558
|
+
const module = path.join(output, "auth.ts");
|
|
17559
|
+
if (!(yield* exists(module))) yield* writeFile(module, authModule(kind));
|
|
17560
|
+
const entry = path.join(output, "index.ts");
|
|
17561
|
+
const code = yield* readFile(entry);
|
|
17562
|
+
const guarded = guardPaths(code, paths);
|
|
17563
|
+
if (guarded !== code) yield* writeFile(entry, yield* fmt(guarded));
|
|
17564
|
+
});
|
|
17565
|
+
}
|
|
17566
|
+
/**
|
|
17567
|
+
* The Hono app of the CRUD of every model, in the directory `output` names: `openapi.yaml`, the
|
|
17568
|
+
* document of the CRUD as Prisma Client has the rows, and what Hono Takibi's template makes of it
|
|
17569
|
+
* (`routes.ts`, `handlers/`, `index.ts`), each handler calling Prisma Client as `prisma`, which
|
|
17570
|
+
* the module `prisma` names exports. With `auth` (`jwt` or `jwks`), every operation asks for a
|
|
17571
|
+
* bearer JWT, which `auth.ts` checks on every model's paths.
|
|
17572
|
+
*/
|
|
17573
|
+
function zodOpenapiHono(options) {
|
|
17574
|
+
return Effect.gen(function* () {
|
|
17575
|
+
const output = yield* requireOutput(options, "Hekireki-ZodOpenAPIHono");
|
|
17576
|
+
if (path.extname(output) !== "") return yield* new GeneratorConfigError({ message: `output for Hekireki-ZodOpenAPIHono is the directory of the app, not a file: ${output}` });
|
|
17577
|
+
const config = options.generator.config ?? {};
|
|
17578
|
+
const prismaImport = getString(config.prisma) ?? "./prisma";
|
|
17579
|
+
const authOption = getString(config.auth);
|
|
17580
|
+
const auth = AUTH_KINDS.find((kind) => kind === authOption);
|
|
17581
|
+
if (authOption !== void 0 && auth === void 0) return yield* new GeneratorConfigError({ message: `auth for Hekireki-ZodOpenAPIHono must be one of ${AUTH_KINDS.map((kind) => `"${kind}"`).join(", ")}: ${authOption}` });
|
|
17582
|
+
const datamodel = options.dmmf.datamodel;
|
|
17583
|
+
const document = path.join(output, "openapi.yaml");
|
|
17584
|
+
yield* emitRaw(zodOpenapiHonoYaml(datamodel, {
|
|
17585
|
+
title: getString(config.title) ?? "Generated from schema.prisma",
|
|
17586
|
+
version: getString(config.version) ?? "1.0.0",
|
|
17587
|
+
...auth === void 0 ? {} : { auth }
|
|
17588
|
+
}), output, document);
|
|
17589
|
+
const routes = path.join(output, "routes.ts");
|
|
17590
|
+
yield* honoTakibi(document, routes);
|
|
17591
|
+
const operations = routeOperations(yield* readFile(routes));
|
|
17592
|
+
const bodies = handlerBodies(datamodel);
|
|
17593
|
+
const handlers = path.join(output, "handlers");
|
|
17594
|
+
const files = (yield* readDirectory(handlers)).filter((name) => name.endsWith(".ts"));
|
|
17595
|
+
yield* Effect.forEach(files, (name) => fillHandlerFile(path.join(handlers, name), operations, bodies, fromHandlers(prismaImport)), { discard: true });
|
|
17596
|
+
if (auth !== void 0) yield* guardApp(output, auth, guardedPaths(datamodel));
|
|
17597
|
+
});
|
|
17598
|
+
}
|
|
16523
17599
|
// src/helper/zod.ts
|
|
16524
17600
|
function makeZodInfer(modelName) {
|
|
16525
17601
|
return `export type ${modelName} = z.infer<typeof ${modelName}Schema>`;
|
|
@@ -16530,6 +17606,9 @@ function makeZodSchema(modelName, fields, objectType) {
|
|
|
16530
17606
|
function makeZodEnumExpression(values) {
|
|
16531
17607
|
return `enum([${values.map((v) => `'${v}'`).join(", ")}])`;
|
|
16532
17608
|
}
|
|
17609
|
+
function makeZodListExpression(element) {
|
|
17610
|
+
return `array(z.${element})`;
|
|
17611
|
+
}
|
|
16533
17612
|
const PRISMA_TO_ZOD = {
|
|
16534
17613
|
String: "string()",
|
|
16535
17614
|
Int: "number()",
|
|
@@ -16560,7 +17639,8 @@ function zodSchemaCode(models, type, zodVersion, enums) {
|
|
|
16560
17639
|
schemas: makeZodSchemas,
|
|
16561
17640
|
typeMapping: PRISMA_TO_ZOD,
|
|
16562
17641
|
enums,
|
|
16563
|
-
formatEnum: makeZodEnumExpression
|
|
17642
|
+
formatEnum: makeZodEnumExpression,
|
|
17643
|
+
wrapList: makeZodListExpression
|
|
16564
17644
|
});
|
|
16565
17645
|
}
|
|
16566
17646
|
// src/generator/zod.ts
|
|
@@ -16668,6 +17748,10 @@ const GENERATORS = {
|
|
|
16668
17748
|
zod: {
|
|
16669
17749
|
prettyName: "Hekireki-Zod",
|
|
16670
17750
|
handler: zod
|
|
17751
|
+
},
|
|
17752
|
+
"zod-openapi-hono": {
|
|
17753
|
+
prettyName: "Hekireki-ZodOpenAPIHono",
|
|
17754
|
+
handler: zodOpenapiHono
|
|
16671
17755
|
}
|
|
16672
17756
|
};
|
|
16673
17757
|
function registerGenerator(name) {
|