@kozou/codegen 0.0.1 → 0.2.1

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,65 @@
1
1
  # @kozou/codegen
2
2
 
3
- Placeholder publish. The real experimental release lands via CI shortly.
3
+ > **Experimental (Kozou v0.2).** API and output may change without notice
4
+ > while the package is stabilising.
5
+
6
+ Kozou's TypeScript codegen. Given a `SchemaContext` (from `@kozou/introspect`
7
+ + `@kozou/core`), it emits one `export interface` per table and view —
8
+ the JSON row shape a client receives from `@kozou/api` — driven entirely by
9
+ your PostgreSQL DDL + `COMMENT` metadata.
10
+
11
+ This is the compiler-native half of Kozou's type story (Kozou v0.2 design
12
+ spec §5.2). It is a pure, offline function — no database connection or
13
+ running API is required to generate the row types.
14
+
15
+ ## Scope
16
+
17
+ Row / entity shapes only. The full API client surface (paths, query
18
+ parameters, request/response envelopes, pagination, embeds) is better served
19
+ by running an OpenAPI generator such as
20
+ [`openapi-typescript`](https://github.com/openapi-ts/openapi-typescript)
21
+ against `@kozou/api`'s `GET /openapi.json`, so this package does **not**
22
+ reimplement that.
23
+
24
+ ## Type mapping
25
+
26
+ Interfaces describe the JSON shape returned by `@kozou/api` (node-postgres
27
+ defaults, after JSON serialization):
28
+
29
+ - `numeric` / `bigint` → `string` (precision is preserved as text)
30
+ - date / time / timestamp → `string` (ISO 8601)
31
+ - `json` / `jsonb` → `unknown`
32
+ - array columns → `T[]`
33
+ - `CHECK (... IN (...))` / enum types → an inline string-literal union
34
+ - anything unrecognised → `unknown`
35
+ - nullable columns → `| null`
36
+
37
+ ## Library use
38
+
39
+ ```ts
40
+ import { emitRowTypes } from '@kozou/codegen';
41
+
42
+ // `schema` is a SchemaContext from @kozou/introspect + @kozou/core.
43
+ const ts = emitRowTypes(schema); // pass { header: false } to drop the banner
44
+ ```
45
+
46
+ ## CLI
47
+
48
+ The `kozou` CLI drives `emitRowTypes` through `kozou codegen`. This package
49
+ is an **optional companion** — it is not bundled with the `kozou` CLI — so
50
+ install it alongside `kozou` (or run from a source / workspace checkout):
51
+
52
+ ```bash
53
+ npm install kozou @kozou/codegen
54
+
55
+ DATABASE_URL=postgres://kozou:kozou@localhost:5432/kozou \
56
+ kozou codegen --output src/db-types.ts
57
+ ```
58
+
59
+ `--output -` (the default) writes to stdout; `--config <path>` points at a
60
+ `kozou.config.yaml`. Without `@kozou/codegen` installed, `kozou codegen`
61
+ exits with a message telling you to install it.
62
+
63
+ ## License
64
+
65
+ Apache 2.0
@@ -0,0 +1,7 @@
1
+ import type { SchemaContext } from '@kozou/core';
2
+ export type EmitOptions = {
3
+ /** Emit the leading "generated by kozou" banner. Default: true. */
4
+ header?: boolean;
5
+ };
6
+ export declare function emitRowTypes(schema: SchemaContext, opts?: EmitOptions): string;
7
+ //# sourceMappingURL=emitRowTypes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"emitRowTypes.d.ts","sourceRoot":"","sources":["../src/emitRowTypes.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,aAAa,EAA4C,MAAM,aAAa,CAAC;AAG3F,MAAM,MAAM,WAAW,GAAG;IACxB,mEAAmE;IACnE,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB,CAAC;AAWF,wBAAgB,YAAY,CAAC,MAAM,EAAE,aAAa,EAAE,IAAI,GAAE,WAAgB,GAAG,MAAM,CAWlF"}
@@ -0,0 +1,100 @@
1
+ // Emit a TypeScript module of row / entity types from a SchemaContext.
2
+ //
3
+ // This is the compiler-native half of Kozou's type story (Kozou v0.2 spec
4
+ // §5.2): one `export interface` per table and view, describing the JSON row a
5
+ // client receives from @kozou/api. It is a pure function — no I/O — so the
6
+ // `kozou codegen` CLI (and tests) drive it directly.
7
+ //
8
+ // Scope: row / entity shapes only. The full API client surface (paths, query
9
+ // params, request/response envelopes, pagination, embeds) is better served by
10
+ // running an OpenAPI generator (e.g. openapi-typescript) against @kozou/api's
11
+ // `GET /openapi.json`, so this package does not reimplement that.
12
+ import { mapColumnType } from './mapType.js';
13
+ const BANNER = [
14
+ '// Generated by `kozou codegen` from PostgreSQL DDL + COMMENT. Do not edit by hand.',
15
+ '//',
16
+ '// Each interface is the JSON row shape returned by @kozou/api: `numeric` /',
17
+ '// `bigint` are strings (node-postgres preserves precision), and temporal',
18
+ '// columns are ISO strings. For the full API client surface, run an OpenAPI',
19
+ "// generator against @kozou/api's `GET /openapi.json`.",
20
+ ].join('\n');
21
+ export function emitRowTypes(schema, opts = {}) {
22
+ const resources = [...schema.tables, ...schema.views];
23
+ const nameFor = buildNamer(resources);
24
+ const blocks = resources.map((r) => renderInterface(r, nameFor(r)));
25
+ const parts = [];
26
+ if (opts.header !== false)
27
+ parts.push(BANNER);
28
+ parts.push(...blocks);
29
+ // A single trailing newline, no matter how many blocks there are.
30
+ return parts.join('\n\n') + '\n';
31
+ }
32
+ function renderInterface(resource, name) {
33
+ const lines = [];
34
+ const doc = jsDoc(resource.description, 0);
35
+ if (doc)
36
+ lines.push(doc);
37
+ lines.push(`export interface ${name} {`);
38
+ for (const column of resource.columns) {
39
+ lines.push(renderField(column));
40
+ }
41
+ lines.push('}');
42
+ return lines.join('\n');
43
+ }
44
+ function renderField(column) {
45
+ const lines = [];
46
+ const doc = jsDoc(column.description, 2);
47
+ if (doc)
48
+ lines.push(doc);
49
+ const type = mapColumnType(column) + (column.nullable ? ' | null' : '');
50
+ lines.push(` ${propertyKey(column.name)}: ${type};`);
51
+ return lines.join('\n');
52
+ }
53
+ /** Render a COMMENT body as a JSDoc block indented by `indent` spaces, or null
54
+ * when there is nothing to say. */
55
+ function jsDoc(description, indent) {
56
+ if (description === null)
57
+ return null;
58
+ const trimmed = description.trim();
59
+ if (trimmed === '')
60
+ return null;
61
+ const pad = ' '.repeat(indent);
62
+ const body = trimmed.split('\n').map((line) => `${pad} * ${line.trimEnd()}`.trimEnd());
63
+ return [`${pad}/**`, ...body, `${pad} */`].join('\n');
64
+ }
65
+ /** A bare property key when the column name is a plain identifier, otherwise a
66
+ * quoted key so the output is always valid TypeScript. */
67
+ function propertyKey(name) {
68
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : quotePropertyKey(name);
69
+ }
70
+ function quotePropertyKey(name) {
71
+ return `'${name.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
72
+ }
73
+ /** Resolve each resource to a unique interface name: PascalCase of the bare
74
+ * name, qualified with the schema only when the bare name collides. */
75
+ function buildNamer(resources) {
76
+ const bareCounts = new Map();
77
+ for (const r of resources) {
78
+ const bare = pascalCase(r.name);
79
+ bareCounts.set(bare, (bareCounts.get(bare) ?? 0) + 1);
80
+ }
81
+ return (r) => {
82
+ const bare = pascalCase(r.name);
83
+ if ((bareCounts.get(bare) ?? 0) > 1) {
84
+ return `${pascalCase(r.schema)}${bare}`;
85
+ }
86
+ return bare;
87
+ };
88
+ }
89
+ /** Convert an arbitrary SQL identifier to PascalCase, splitting on any run of
90
+ * non-alphanumeric characters and guarding against a leading digit. */
91
+ function pascalCase(identifier) {
92
+ const segments = identifier.split(/[^A-Za-z0-9]+/).filter((s) => s.length > 0);
93
+ const pascal = segments
94
+ .map((s) => s.charAt(0).toUpperCase() + s.slice(1))
95
+ .join('');
96
+ if (pascal === '')
97
+ return '_';
98
+ return /^[0-9]/.test(pascal) ? `_${pascal}` : pascal;
99
+ }
100
+ //# sourceMappingURL=emitRowTypes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"emitRowTypes.js","sourceRoot":"","sources":["../src/emitRowTypes.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,EAAE;AACF,0EAA0E;AAC1E,8EAA8E;AAC9E,2EAA2E;AAC3E,qDAAqD;AACrD,EAAE;AACF,6EAA6E;AAC7E,8EAA8E;AAC9E,8EAA8E;AAC9E,kEAAk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C,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAC/E,MAAM,MAAM,GAAG,QAAQ;SACpB,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;SAClD,IAAI,CAAC,EAAE,CAAC,CAAC;IACZ,IAAI,MAAM,KAAK,EAAE;QAAE,OAAO,GAAG,CAAC;IAC9B,OAAO,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC;AACvD,CAAC"}
@@ -0,0 +1,3 @@
1
+ export { emitRowTypes, type EmitOptions } from './emitRowTypes.js';
2
+ export { mapColumnType, mapDataType } from './mapType.js';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,KAAK,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { emitRowTypes } from './emitRowTypes.js';
2
+ export { mapColumnType, mapDataType } from './mapType.js';
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAoB,MAAM,mBAAmB,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC"}
@@ -0,0 +1,12 @@
1
+ import type { ColumnContext } from '@kozou/core';
2
+ /** A column with an enum domain renders as a union of string literals; every
3
+ * other column maps by its PostgreSQL `dataType`. The result never includes
4
+ * `| null` — the caller appends that based on `nullable`. */
5
+ export declare function mapColumnType(column: ColumnContext): string;
6
+ /** Map a `format_type(...)` string to a TypeScript type, resolving any array
7
+ * suffix to `T[]` and stripping precision/length modifiers first. */
8
+ export declare function mapDataType(dataType: string): string;
9
+ /** Render a string as a single-quoted TypeScript string literal, escaping the
10
+ * backslash and single-quote characters. */
11
+ export declare function quoteStringLiteral(value: string): string;
12
+ //# sourceMappingURL=mapType.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mapType.d.ts","sourceRoot":"","sources":["../src/mapType.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAEjD;;8DAE8D;AAC9D,wBAAgB,aAAa,CAAC,MAAM,EAAE,aAAa,GAAG,MAAM,CAK3D;AAED;sEACsE;AACtE,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAmBpD;AA6DD;6CAC6C;AAC7C,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAExD"}
@@ -0,0 +1,99 @@
1
+ // Map a ColumnContext to the TypeScript type that best describes the value a
2
+ // client receives from @kozou/api — i.e. the JSON shape after node-postgres
3
+ // has parsed the row and the response has been serialized. This is why a few
4
+ // mappings may surprise: node-postgres returns `numeric` and `bigint` as
5
+ // strings (to avoid precision loss), and temporal types arrive as ISO strings
6
+ // once a Date has gone through JSON.stringify.
7
+ //
8
+ // Input is the `dataType` produced by @kozou/introspect via PostgreSQL's
9
+ // `format_type(...)`, so the names are the SQL-standard long forms
10
+ // ("character varying", "timestamp with time zone", "double precision", …),
11
+ // optionally carrying a precision/length and a trailing `[]` for arrays.
12
+ /** A column with an enum domain renders as a union of string literals; every
13
+ * other column maps by its PostgreSQL `dataType`. The result never includes
14
+ * `| null` — the caller appends that based on `nullable`. */
15
+ export function mapColumnType(column) {
16
+ if (column.enumValues && column.enumValues.length > 0) {
17
+ return column.enumValues.map(quoteStringLiteral).join(' | ');
18
+ }
19
+ return mapDataType(column.dataType);
20
+ }
21
+ /** Map a `format_type(...)` string to a TypeScript type, resolving any array
22
+ * suffix to `T[]` and stripping precision/length modifiers first. */
23
+ export function mapDataType(dataType) {
24
+ let base = dataType.trim();
25
+ // Peel a (single-level) array suffix; PostgreSQL renders multi-dimensional
26
+ // arrays with the same element type, so `T[]` is the faithful TS shape.
27
+ let isArray = false;
28
+ while (base.endsWith('[]')) {
29
+ isArray = true;
30
+ base = base.slice(0, -2).trim();
31
+ }
32
+ // Drop every `(...)` modifier ("numeric(12,2)", "timestamp(6) with time
33
+ // zone", "character varying(255)") and normalize whitespace + case. The
34
+ // paren stripping is a linear scan rather than a regex so it stays O(n) on
35
+ // adversarial input like a long run of "(" (no super-linear backtracking).
36
+ const normalized = collapseWhitespace(stripParenGroups(base)).toLowerCase();
37
+ const element = SCALAR_TYPE_MAP[normalized] ?? 'unknown';
38
+ return isArray ? `${element}[]` : element;
39
+ }
40
+ /** Remove every parenthesized group (including nested ones), keeping only the
41
+ * characters at paren-depth zero. Single linear pass, no backtracking. */
42
+ function stripParenGroups(input) {
43
+ let out = '';
44
+ let depth = 0;
45
+ for (const ch of input) {
46
+ if (ch === '(') {
47
+ depth += 1;
48
+ }
49
+ else if (ch === ')') {
50
+ if (depth > 0)
51
+ depth -= 1;
52
+ }
53
+ else if (depth === 0) {
54
+ out += ch;
55
+ }
56
+ }
57
+ return out;
58
+ }
59
+ /** Collapse runs of whitespace to a single space and trim. `\s+` (unanchored,
60
+ * single repetition) matches linearly, so this is not a ReDoS vector. */
61
+ function collapseWhitespace(input) {
62
+ return input.replace(/\s+/g, ' ').trim();
63
+ }
64
+ const SCALAR_TYPE_MAP = {
65
+ // Textual + identifier types.
66
+ uuid: 'string',
67
+ text: 'string',
68
+ 'character varying': 'string',
69
+ character: 'string',
70
+ '"char"': 'string',
71
+ bpchar: 'string',
72
+ citext: 'string',
73
+ name: 'string',
74
+ // Integers and floats fit in a JS number.
75
+ smallint: 'number',
76
+ integer: 'number',
77
+ real: 'number',
78
+ 'double precision': 'number',
79
+ // node-postgres returns these as strings to preserve precision/range.
80
+ numeric: 'string',
81
+ bigint: 'string',
82
+ boolean: 'boolean',
83
+ // Temporal values arrive as ISO strings once a Date is JSON-serialized.
84
+ date: 'string',
85
+ 'timestamp without time zone': 'string',
86
+ 'timestamp with time zone': 'string',
87
+ 'time without time zone': 'string',
88
+ 'time with time zone': 'string',
89
+ interval: 'string',
90
+ // Structured payloads are parsed objects of an unknown shape.
91
+ json: 'unknown',
92
+ jsonb: 'unknown',
93
+ };
94
+ /** Render a string as a single-quoted TypeScript string literal, escaping the
95
+ * backslash and single-quote characters. */
96
+ export function quoteStringLiteral(value) {
97
+ return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
98
+ }
99
+ //# sourceMappingURL=mapType.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mapType.js","sourceRoot":"","sources":["../src/mapType.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,4EAA4E;AAC5E,6EAA6E;AAC7E,yEAAyE;AACzE,8EAA8E;AAC9E,+CAA+C;AAC/C,EAAE;AACF,yEAAyE;AACzE,mEAAmE;AACnE,4EAA4E;AAC5E,yEAAyE;AAIzE;;8DAE8D;AAC9D,MAAM,UAAU,aAAa,CAAC,MAAqB;IACjD,IAAI,MAAM,CAAC,UAAU,IAAI,MAAM,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACtD,OAAO,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC/D,CAAC;IACD,OAAO,WAAW,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AACtC,CAAC;AAED;sEACsE;AACtE,MAAM,UAAU,WAAW,CAAC,QAAgB;IAC1C,IAAI,IAAI,GAAG,QAAQ,CAAC,IAAI,EAAE,CAAC;IAE3B,2EAA2E;IAC3E,wEAAwE;IACxE,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IAAI,EAAE,QAAQ;IACd,IAAI,EAAE,QAAQ;IACd,mBAAmB,EAAE,QAAQ;IAC7B,SAAS,EAAE,QAAQ;IACnB,QAAQ,EAAE,QAAQ;IAClB,MAAM,EAAE,QAAQ;IAChB,MAAM,EAAE,QAAQ;IAChB,IAAI,EAAE,QAAQ;IAEd,0CAA0C;IAC1C,QAAQ,EAAE,QAAQ;IAClB,OAAO,EAAE,QAAQ;IACjB,IAAI,EAAE,QAAQ;IACd,kBAAkB,EAAE,QAAQ;IAE5B,sEAAsE;IACtE,OAAO,EAAE,QAAQ;IACjB,MAAM,EAAE,QAAQ;IAEhB,OAAO,EAAE,SAAS;IAElB,wEAAwE;IACxE,IAAI,EAAE,QAAQ;IACd,6BAA6B,EAAE,QAAQ;IACvC,0BAA0B,EAAE,QAAQ;IACpC,wBAAwB,EAAE,QAAQ;IAClC,qBAAqB,EAAE,QAAQ;IAC/B,QAAQ,EAAE,QAAQ;IAElB,8DAA8D;IAC9D,IAAI,EAAE,SAAS;IACf,KAAK,EAAE,SAAS;CACjB,CAAC;AAEF;6CAC6C;AAC7C,MAAM,UAAU,kBAAkB,CAAC,KAAa;IAC9C,OAAO,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,GAAG,CAAC;AAClE,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,44 @@
1
1
  {
2
2
  "name": "@kozou/codegen",
3
- "version": "0.0.1",
4
- "description": "Placeholder; the experimental 0.2.1 release lands via CI shortly.",
3
+ "version": "0.2.1",
4
+ "description": "Kozou TypeScript codegen: emit row / entity types from a SchemaContext (Kozou v0.2 spec §5.2, experimental).",
5
5
  "license": "Apache-2.0",
6
- "publishConfig": { "access": "public" }
7
- }
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/kozou-dev/kozou.git",
9
+ "directory": "packages/codegen"
10
+ },
11
+ "homepage": "https://kozou.org",
12
+ "bugs": {
13
+ "url": "https://github.com/kozou-dev/kozou/issues"
14
+ },
15
+ "type": "module",
16
+ "main": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "import": "./dist/index.js",
21
+ "types": "./dist/index.d.ts"
22
+ },
23
+ "./package.json": "./package.json"
24
+ },
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "publishConfig": {
29
+ "access": "public",
30
+ "provenance": true
31
+ },
32
+ "dependencies": {
33
+ "@kozou/core": "0.2.1"
34
+ },
35
+ "devDependencies": {
36
+ "typescript": "^6.0.3",
37
+ "@kozou/introspect": "0.2.1"
38
+ },
39
+ "scripts": {
40
+ "typecheck": "tsc -p tsconfig.test.json",
41
+ "build": "tsc",
42
+ "test": "vitest run --coverage"
43
+ }
44
+ }