@askdb/introspect 0.3.0-beta.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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may accept and charge a
167
+ fee for, the acceptance of support, warranty, indemnity, or
168
+ other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Yahya Gilany
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
200
+ implied. See the License for the specific language governing
201
+ permissions and limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,10 @@
1
+ AskDB
2
+ Copyright 2026 Yahya Gilany
3
+
4
+ This product includes software developed by Yahya Gilany and contributors.
5
+
6
+ Licensed under the Apache License, Version 2.0 (the "License");
7
+ you may not use this file except in compliance with the License.
8
+ You may obtain a copy of the License at
9
+
10
+ http://www.apache.org/licenses/LICENSE-2.0
package/README.md ADDED
@@ -0,0 +1,56 @@
1
+ # `@askdb/introspect`
2
+
3
+ Engine-agnostic introspection orchestrator for AskDB. Defines the `Connector` contract and turns the integration package's `SqlSchema` output into a Schema v2 directory.
4
+
5
+ > Status: pre-1.0. `@askdb/introspect` itself does not bundle any engine support — integration packages (e.g. `@askdb/postgres`, `@askdb/prisma`) supply connectors and input shapes.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pnpm add @askdb/introspect @askdb/core
11
+ # Plus an integration package for the engine you're targeting, e.g.:
12
+ pnpm add @askdb/postgres pg
13
+ # Or for Prisma schema-file introspection:
14
+ pnpm add @askdb/prisma
15
+ ```
16
+
17
+ ## Programmatic usage
18
+
19
+ ```ts
20
+ import { introspect } from "@askdb/introspect";
21
+ import { createPostgresCatalogQueryRunner, createPostgresConnector } from "@askdb/postgres";
22
+
23
+ const result = await introspect(
24
+ { mode: "live", runner: createPostgresCatalogQueryRunner(process.env.DATABASE_URL!) },
25
+ { outDir: "./my-app.schema", schemaId: "my-app" },
26
+ { connector: createPostgresConnector() },
27
+ );
28
+ ```
29
+
30
+ The output directory contains a physical Schema v2 artifact (`schema.json`) plus the Phase 5 describable layer.
31
+
32
+ For Prisma projects, use `@askdb/prisma` to read schema files without connecting to the database:
33
+
34
+ ```ts
35
+ import { introspect } from "@askdb/introspect";
36
+ import { createPrismaConnector } from "@askdb/prisma";
37
+
38
+ const result = await introspect(
39
+ { schemaPath: "./prisma", schemaId: "my-app" },
40
+ { outDir: "./my-app.schema", schemaId: "my-app" },
41
+ { connector: createPrismaConnector() },
42
+ );
43
+ ```
44
+
45
+ ## CLI
46
+
47
+ The user-facing CLI for introspection ships in the [`askdb`](https://www.npmjs.com/package/askdb) package as `askdb introspect`. `@askdb/introspect` does not provide a standalone binary.
48
+
49
+ ## Implementing a new connector
50
+
51
+ A `Connector<TInput>` has two methods:
52
+
53
+ - `describe(input: TInput): Promise<IntrospectionResult>` — the integration's input shape goes through unchanged.
54
+ - `templates?(): SqlTemplateBundle` — optional; only relevant for engines that introspect via catalog SQL.
55
+
56
+ The integration package owns its own input type (e.g. `PostgresIntrospectionInput`, `PrismaIntrospectionInput`). `@askdb/introspect` does not assume a live catalog runner exists, a bundle path exists, a schema-file path exists, or a template suite exists.
@@ -0,0 +1,5 @@
1
+ export type { SqlSchema, SqlNamespace, SqlTable, SqlColumn, SqlForeignKey, SqlForeignKeyAction, SqlUnique, SqlIndex, SqlCheck, SqlEnum, SqlSequence, SqlView, IntrospectionFilters, IntrospectionResult, IntrospectionWarning, SqlTemplate, SqlTemplateBundle, CatalogQueryResult, CatalogQueryRunner, Connector, } from "./types.js";
2
+ export type { RenderOptions, RenderResult } from "./render/types.js";
3
+ export { introspect, type IntrospectOptions, type IntrospectResult, } from "./introspect.js";
4
+ export { renderToSchemaV2, toV2SchemaJson, compactPostgresType } from "./render/render.js";
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,SAAS,EACT,YAAY,EACZ,QAAQ,EACR,SAAS,EACT,aAAa,EACb,mBAAmB,EACnB,SAAS,EACT,QAAQ,EACR,QAAQ,EACR,OAAO,EACP,WAAW,EACX,OAAO,EACP,oBAAoB,EACpB,mBAAmB,EACnB,oBAAoB,EACpB,WAAW,EACX,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,EAClB,SAAS,GACV,MAAM,YAAY,CAAC;AAEpB,YAAY,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAErE,OAAO,EACL,UAAU,EACV,KAAK,iBAAiB,EACtB,KAAK,gBAAgB,GACtB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { introspect, } from "./introspect.js";
2
+ export { renderToSchemaV2, toV2SchemaJson, compactPostgresType } from "./render/render.js";
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAyBA,OAAO,EACL,UAAU,GAGX,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC"}
@@ -0,0 +1,24 @@
1
+ import type { Connector, IntrospectionResult } from "./types.js";
2
+ import type { RenderOptions, RenderResult } from "./render/types.js";
3
+ /**
4
+ * Options for the introspection orchestrator. The `connector` is the integration package's
5
+ * `Connector` (e.g. `createPostgresConnector()` from `@askdb/postgres`). Engine-agnostic
6
+ * introspect has no default — callers wire up the integration explicitly.
7
+ */
8
+ export type IntrospectOptions<TInput> = {
9
+ connector: Connector<TInput>;
10
+ };
11
+ export type IntrospectResult = IntrospectionResult & {
12
+ /** Present when `renderOptions` was supplied; points at the written `schema.json`. */
13
+ render?: RenderResult;
14
+ };
15
+ /**
16
+ * Run an integration connector against the given input and (optionally) render the result
17
+ * into a Schema v2 directory.
18
+ *
19
+ * The input shape is owned by the integration package — for `@askdb/postgres` it is
20
+ * `PostgresIntrospectionInput` (live or from-export). For a future Prisma integration it
21
+ * would be a `schema.prisma` file path.
22
+ */
23
+ export declare function introspect<TInput>(input: TInput, renderOptions: RenderOptions | undefined, options: IntrospectOptions<TInput>): Promise<IntrospectResult>;
24
+ //# sourceMappingURL=introspect.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"introspect.d.ts","sourceRoot":"","sources":["../src/introspect.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AACjE,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAGrE;;;;GAIG;AACH,MAAM,MAAM,iBAAiB,CAAC,MAAM,IAAI;IACtC,SAAS,EAAE,SAAS,CAAC,MAAM,CAAC,CAAC;CAC9B,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG,mBAAmB,GAAG;IACnD,sFAAsF;IACtF,MAAM,CAAC,EAAE,YAAY,CAAC;CACvB,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAsB,UAAU,CAAC,MAAM,EACrC,KAAK,EAAE,MAAM,EACb,aAAa,EAAE,aAAa,GAAG,SAAS,EACxC,OAAO,EAAE,iBAAiB,CAAC,MAAM,CAAC,GACjC,OAAO,CAAC,gBAAgB,CAAC,CAW3B"}
@@ -0,0 +1,21 @@
1
+ import { renderToSchemaV2 } from "./render/render.js";
2
+ /**
3
+ * Run an integration connector against the given input and (optionally) render the result
4
+ * into a Schema v2 directory.
5
+ *
6
+ * The input shape is owned by the integration package — for `@askdb/postgres` it is
7
+ * `PostgresIntrospectionInput` (live or from-export). For a future Prisma integration it
8
+ * would be a `schema.prisma` file path.
9
+ */
10
+ export async function introspect(input, renderOptions, options) {
11
+ const result = await options.connector.describe(input);
12
+ if (!renderOptions)
13
+ return result;
14
+ const render = renderToSchemaV2(result.schema, renderOptions);
15
+ return {
16
+ ...result,
17
+ warnings: [...result.warnings, ...render.warnings],
18
+ render,
19
+ };
20
+ }
21
+ //# sourceMappingURL=introspect.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"introspect.js","sourceRoot":"","sources":["../src/introspect.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAgBtD;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAC9B,KAAa,EACb,aAAwC,EACxC,OAAkC;IAElC,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,SAAS,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IAEvD,IAAI,CAAC,aAAa;QAAE,OAAO,MAAM,CAAC;IAElC,MAAM,MAAM,GAAG,gBAAgB,CAAC,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IAC9D,OAAO;QACL,GAAG,MAAM;QACT,QAAQ,EAAE,CAAC,GAAG,MAAM,CAAC,QAAQ,EAAE,GAAG,MAAM,CAAC,QAAQ,CAAC;QAClD,MAAM;KACP,CAAC;AACJ,CAAC"}
@@ -0,0 +1,34 @@
1
+ import { type V2SchemaJson } from "@askdb/core";
2
+ import type { SqlSchema } from "../types.js";
3
+ import type { RenderOptions, RenderResult } from "./types.js";
4
+ /**
5
+ * Render a `SqlSchema` to a Schema v2 directory.
6
+ *
7
+ * Clean writes and ID-anchored re-introspection merges write `schema.json`
8
+ * only. The describable layer (`tables/*.md`, `concepts.md`) is read only for
9
+ * orphan detection when `existingArtifactDir` is supplied.
10
+ *
11
+ * Determinism contract (requirements.md §5):
12
+ * - Schemas alphabetical at the source (the connector already produces
13
+ * this); tables alphabetical by `(schema, name)` in the emitted v2 file.
14
+ * - Columns in `ordinalPosition` order.
15
+ * - FKs sorted by constraint name; `relationships[]` derived in the same
16
+ * order so the file is byte-identical across runs.
17
+ *
18
+ * Output format: `JSON.stringify(value, null, 2) + "\n"` (matches the
19
+ * hand-authored Phase 5 fixtures).
20
+ */
21
+ export declare function renderToSchemaV2(schema: SqlSchema, options: RenderOptions): RenderResult;
22
+ /**
23
+ * Pure-function form of {@link renderToSchemaV2} — exposed so callers (and
24
+ * M6's merge) can produce the V2 JSON without writing it to disk.
25
+ */
26
+ export declare function toV2SchemaJson(schema: SqlSchema, schemaId: string): V2SchemaJson;
27
+ /**
28
+ * Map Postgres `format_type` strings to the short names AskDB Schema v2
29
+ * uses in its hand-authored fixtures. Only the standard SQL ↔ pg-short-name
30
+ * aliases are touched; unknown strings (and length/precision modifiers)
31
+ * pass through unchanged.
32
+ */
33
+ export declare function compactPostgresType(dataType: string, _udtName: string): string;
34
+ //# sourceMappingURL=render.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render.d.ts","sourceRoot":"","sources":["../../src/render/render.ts"],"names":[],"mappings":"AAQA,OAAO,EAEL,KAAK,YAAY,EAGlB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAIV,SAAS,EAEV,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE9D;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,SAAS,EACjB,OAAO,EAAE,aAAa,GACrB,YAAY,CAad;AA2HD;;;GAGG;AACH,wBAAgB,cAAc,CAC5B,MAAM,EAAE,SAAS,EACjB,QAAQ,EAAE,MAAM,GACf,YAAY,CAqBd;AAkED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CACjC,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,MAAM,GACf,MAAM,CAaR"}
@@ -0,0 +1,225 @@
1
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync, } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { parseTableMarkdown, } from "@askdb/core";
4
+ /**
5
+ * Render a `SqlSchema` to a Schema v2 directory.
6
+ *
7
+ * Clean writes and ID-anchored re-introspection merges write `schema.json`
8
+ * only. The describable layer (`tables/*.md`, `concepts.md`) is read only for
9
+ * orphan detection when `existingArtifactDir` is supplied.
10
+ *
11
+ * Determinism contract (requirements.md §5):
12
+ * - Schemas alphabetical at the source (the connector already produces
13
+ * this); tables alphabetical by `(schema, name)` in the emitted v2 file.
14
+ * - Columns in `ordinalPosition` order.
15
+ * - FKs sorted by constraint name; `relationships[]` derived in the same
16
+ * order so the file is byte-identical across runs.
17
+ *
18
+ * Output format: `JSON.stringify(value, null, 2) + "\n"` (matches the
19
+ * hand-authored Phase 5 fixtures).
20
+ */
21
+ export function renderToSchemaV2(schema, options) {
22
+ const warnings = [];
23
+ const fresh = toV2SchemaJson(schema, options.schemaId);
24
+ const v2 = options.existingArtifactDir
25
+ ? mergeWithExistingArtifact(fresh, options.existingArtifactDir, warnings)
26
+ : fresh;
27
+ mkdirSync(options.outDir, { recursive: true });
28
+ const schemaJsonPath = resolve(options.outDir, "schema.json");
29
+ const body = JSON.stringify(v2, null, 2) + "\n";
30
+ writeFileSync(schemaJsonPath, body, "utf8");
31
+ return { schemaJsonPath, warnings };
32
+ }
33
+ function mergeWithExistingArtifact(fresh, existingArtifactDir, warnings) {
34
+ const existing = readExistingPhysical(existingArtifactDir);
35
+ const existingTables = new Map(existing.tables.map((table) => [table.id, table]));
36
+ const existingColumns = new Map();
37
+ for (const table of existing.tables) {
38
+ for (const column of table.columns) {
39
+ existingColumns.set(column.id, column);
40
+ }
41
+ }
42
+ for (const table of fresh.tables) {
43
+ const existingTable = existingTables.get(table.id);
44
+ if (existingTable?.sensitive !== undefined) {
45
+ table.sensitive = existingTable.sensitive;
46
+ }
47
+ for (const column of table.columns) {
48
+ const existingColumn = existingColumns.get(column.id);
49
+ if (existingColumn) {
50
+ if (existingColumn.sensitive !== undefined) {
51
+ column.sensitive = existingColumn.sensitive;
52
+ }
53
+ }
54
+ else {
55
+ warnings.push({ code: "new_column", id: column.id, tableId: table.id });
56
+ }
57
+ }
58
+ }
59
+ warnings.push(...findOrphanWarnings(existingArtifactDir, fresh));
60
+ return fresh;
61
+ }
62
+ function readExistingPhysical(existingArtifactDir) {
63
+ const schemaJsonPath = resolve(existingArtifactDir, "schema.json");
64
+ const parsed = JSON.parse(readFileSync(schemaJsonPath, "utf8"));
65
+ return assertV2SchemaJson(parsed, schemaJsonPath);
66
+ }
67
+ function assertV2SchemaJson(value, filePath) {
68
+ if (!isRecord(value) || value.version !== 2) {
69
+ throw new Error(`@askdb/introspect: invalid Schema v2 file at ${filePath}`);
70
+ }
71
+ if (typeof value.schemaId !== "string" || !Array.isArray(value.tables)) {
72
+ throw new Error(`@askdb/introspect: invalid Schema v2 file at ${filePath}`);
73
+ }
74
+ for (const table of value.tables) {
75
+ if (!isRecord(table) ||
76
+ typeof table.id !== "string" ||
77
+ typeof table.name !== "string" ||
78
+ typeof table.schema !== "string" ||
79
+ !Array.isArray(table.columns)) {
80
+ throw new Error(`@askdb/introspect: invalid Schema v2 table in ${filePath}`);
81
+ }
82
+ for (const column of table.columns) {
83
+ if (!isRecord(column) ||
84
+ typeof column.id !== "string" ||
85
+ typeof column.name !== "string" ||
86
+ typeof column.type !== "string" ||
87
+ typeof column.nullable !== "boolean") {
88
+ throw new Error(`@askdb/introspect: invalid Schema v2 column in ${filePath}`);
89
+ }
90
+ }
91
+ }
92
+ return value;
93
+ }
94
+ function isRecord(value) {
95
+ return typeof value === "object" && value !== null && !Array.isArray(value);
96
+ }
97
+ function findOrphanWarnings(existingArtifactDir, fresh) {
98
+ const tableIds = new Set(fresh.tables.map((table) => table.id));
99
+ const columnIds = new Set(fresh.tables.flatMap((table) => table.columns.map((column) => column.id)));
100
+ const tableDir = join(existingArtifactDir, "tables");
101
+ if (!existsSync(tableDir))
102
+ return [];
103
+ const warnings = [];
104
+ const seen = new Set();
105
+ for (const entry of readdirSync(tableDir)) {
106
+ if (!entry.endsWith(".md"))
107
+ continue;
108
+ const filePath = join(tableDir, entry);
109
+ const relativeFile = `tables/${entry}`;
110
+ const parsed = parseTableMarkdown(readFileSync(filePath, "utf8"), filePath);
111
+ appendOrphanWarning(parsed.frontmatter.id, relativeFile, tableIds, warnings, seen);
112
+ for (const column of parsed.frontmatter.columns ?? []) {
113
+ appendOrphanWarning(column.id, relativeFile, columnIds, warnings, seen);
114
+ }
115
+ }
116
+ return warnings;
117
+ }
118
+ function appendOrphanWarning(id, file, validIds, warnings, seen) {
119
+ const key = `${file}\0${id}`;
120
+ if (validIds.has(id) || seen.has(key))
121
+ return;
122
+ seen.add(key);
123
+ warnings.push({ code: "orphan_id", id, file });
124
+ }
125
+ /**
126
+ * Pure-function form of {@link renderToSchemaV2} — exposed so callers (and
127
+ * M6's merge) can produce the V2 JSON without writing it to disk.
128
+ */
129
+ export function toV2SchemaJson(schema, schemaId) {
130
+ const tables = [];
131
+ for (const ns of schema.schemas) {
132
+ for (const t of ns.tables) {
133
+ tables.push(toV2Table(t));
134
+ }
135
+ }
136
+ tables.sort((a, b) => {
137
+ const aSchema = a.schema;
138
+ const bSchema = b.schema;
139
+ if (aSchema !== bSchema)
140
+ return aSchema.localeCompare(bSchema);
141
+ return a.name.localeCompare(b.name);
142
+ });
143
+ return {
144
+ version: 2,
145
+ schemaId,
146
+ tables,
147
+ };
148
+ }
149
+ function toV2Table(table) {
150
+ const columns = table.columns
151
+ .slice()
152
+ .sort((a, b) => a.ordinalPosition - b.ordinalPosition)
153
+ .map(toV2Column);
154
+ const v2Table = {
155
+ id: table.id,
156
+ name: table.name,
157
+ schema: table.schema,
158
+ sensitive: false,
159
+ columns,
160
+ };
161
+ const relationships = buildRelationships(table);
162
+ if (relationships.length > 0) {
163
+ v2Table.relationships = relationships;
164
+ }
165
+ return v2Table;
166
+ }
167
+ function toV2Column(column) {
168
+ // Field order matches the Phase 5 hand-authored fixtures:
169
+ // id, name, type, nullable, [primaryKey], sensitive.
170
+ return {
171
+ id: column.id,
172
+ name: column.name,
173
+ type: compactPostgresType(column.dataType, column.udtName),
174
+ nullable: column.nullable,
175
+ ...(column.primaryKey ? { primaryKey: true } : {}),
176
+ sensitive: false,
177
+ };
178
+ }
179
+ function buildRelationships(table) {
180
+ const out = [];
181
+ // FKs are already sorted by constraint name in the connector — preserve.
182
+ for (const fk of table.foreignKeys) {
183
+ appendFkRelationships(out, table, fk);
184
+ }
185
+ return out;
186
+ }
187
+ function appendFkRelationships(acc, table, fk) {
188
+ const local = fk.columns;
189
+ const referenced = fk.references.columns;
190
+ // The connector guarantees both lists have equal length and the same
191
+ // declared (conkey/confkey) order — emit one relationship per pair.
192
+ const len = Math.min(local.length, referenced.length);
193
+ for (let i = 0; i < len; i++) {
194
+ acc.push({
195
+ from: `${table.id}#${local[i]}`,
196
+ to: `table:${fk.references.schema}.${fk.references.table}#${referenced[i]}`,
197
+ });
198
+ }
199
+ }
200
+ /**
201
+ * Map Postgres `format_type` strings to the short names AskDB Schema v2
202
+ * uses in its hand-authored fixtures. Only the standard SQL ↔ pg-short-name
203
+ * aliases are touched; unknown strings (and length/precision modifiers)
204
+ * pass through unchanged.
205
+ */
206
+ export function compactPostgresType(dataType, _udtName) {
207
+ if (dataType === "timestamp with time zone")
208
+ return "timestamptz";
209
+ if (dataType === "time with time zone")
210
+ return "timetz";
211
+ if (dataType === "timestamp without time zone")
212
+ return "timestamp";
213
+ if (dataType === "time without time zone")
214
+ return "time";
215
+ if (dataType.startsWith("character varying")) {
216
+ return dataType.replace("character varying", "varchar");
217
+ }
218
+ if (dataType === "character")
219
+ return "char";
220
+ if (dataType.startsWith("character(")) {
221
+ return dataType.replace("character(", "char(");
222
+ }
223
+ return dataType;
224
+ }
225
+ //# sourceMappingURL=render.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render.js","sourceRoot":"","sources":["../../src/render/render.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,SAAS,EACT,YAAY,EACZ,WAAW,EACX,aAAa,GACd,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EACL,kBAAkB,GAInB,MAAM,aAAa,CAAC;AAUrB;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,UAAU,g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QAC7C,OAAO,QAAQ,CAAC,OAAO,CAAC,mBAAmB,EAAE,SAAS,CAAC,CAAC;IAC1D,CAAC;IACD,IAAI,QAAQ,KAAK,WAAW;QAAE,OAAO,MAAM,CAAC;IAC5C,IAAI,QAAQ,CAAC,UAAU,CAAC,YAAY,CAAC,EAAE,CAAC;QACtC,OAAO,QAAQ,CAAC,OAAO,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC;IACjD,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC"}
@@ -0,0 +1,18 @@
1
+ import type { IntrospectionWarning } from "../types.js";
2
+ export type RenderOptions = {
3
+ /** Output directory, typically `"<schemaId>.schema/"`. */
4
+ outDir: string;
5
+ schemaId: string;
6
+ /**
7
+ * When present, ID-anchored merge runs against this directory's existing
8
+ * `schema.json`. Sensitive flags are preserved; the describable layer
9
+ * (`tables/*.md`, `concepts.md`) is read for orphan-warning detection only
10
+ * and is **never** modified.
11
+ */
12
+ existingArtifactDir?: string;
13
+ };
14
+ export type RenderResult = {
15
+ schemaJsonPath: string;
16
+ warnings: IntrospectionWarning[];
17
+ };
18
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/render/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAExD,MAAM,MAAM,aAAa,GAAG;IAC1B,0DAA0D;IAC1D,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB;;;;;OAKG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC9B,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG;IACzB,cAAc,EAAE,MAAM,CAAC;IACvB,QAAQ,EAAE,oBAAoB,EAAE,CAAC;CAClC,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/render/types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,192 @@
1
+ /**
2
+ * Intermediate representation produced by every connector. Renders into a
3
+ * Schema v2 `schema.json`. See docs/specs/phase-6-introspection/requirements.md §2.
4
+ */
5
+ export type SqlSchema = {
6
+ schemaId: string;
7
+ schemas: SqlNamespace[];
8
+ };
9
+ export type SqlNamespace = {
10
+ name: string;
11
+ tables: SqlTable[];
12
+ views: SqlView[];
13
+ enums: SqlEnum[];
14
+ sequences: SqlSequence[];
15
+ };
16
+ export type SqlTable = {
17
+ /** "table:<schema>.<name>" (or "table:<name>" in public per Schema v2 ID conventions). */
18
+ id: string;
19
+ schema: string;
20
+ name: string;
21
+ /** pg_description-derived; surfaced as informational only. */
22
+ comment?: string;
23
+ columns: SqlColumn[];
24
+ primaryKey?: {
25
+ columns: string[];
26
+ };
27
+ /** Ordered by constraint name; column lists preserve `pg_constraint.conkey` order. */
28
+ foreignKeys: SqlForeignKey[];
29
+ uniqueConstraints: SqlUnique[];
30
+ indexes: SqlIndex[];
31
+ /** Captured but not yet emitted into Schema v2. */
32
+ checkConstraints: SqlCheck[];
33
+ rowLevelSecurity?: {
34
+ enabled: boolean;
35
+ };
36
+ };
37
+ export type SqlColumn = {
38
+ /** "table:<schema>.<name>#<col>". */
39
+ id: string;
40
+ name: string;
41
+ ordinalPosition: number;
42
+ /** Canonical Postgres type string (e.g. "uuid", "text", "numeric(10,2)", "timestamp with time zone"). */
43
+ dataType: string;
44
+ /** Raw udt_name for arrays / enums. */
45
+ udtName: string;
46
+ nullable: boolean;
47
+ primaryKey: boolean;
48
+ defaultExpression?: string;
49
+ comment?: string;
50
+ };
51
+ export type SqlForeignKeyAction = "no action" | "restrict" | "cascade" | "set null" | "set default";
52
+ export type SqlForeignKey = {
53
+ name: string;
54
+ /** Preserves pg_constraint.conkey order — multi-column FK fix. */
55
+ columns: string[];
56
+ references: {
57
+ schema: string;
58
+ table: string;
59
+ /** Preserves pg_constraint.confkey order. */
60
+ columns: string[];
61
+ };
62
+ onDelete?: SqlForeignKeyAction;
63
+ onUpdate?: SqlForeignKeyAction;
64
+ };
65
+ export type SqlUnique = {
66
+ name: string;
67
+ columns: string[];
68
+ };
69
+ export type SqlIndex = {
70
+ name: string;
71
+ columns: string[];
72
+ /** Index expression text when the index is on an expression rather than a plain column. */
73
+ expressions?: string[];
74
+ unique: boolean;
75
+ /** pg_am.amname (e.g. "btree", "gin", "gist"). */
76
+ method: string;
77
+ };
78
+ export type SqlCheck = {
79
+ name: string;
80
+ /** Constraint expression text from pg_get_constraintdef. */
81
+ expression: string;
82
+ };
83
+ export type SqlEnum = {
84
+ schema: string;
85
+ name: string;
86
+ /** Preserves pg_enum.enumsortorder. */
87
+ values: string[];
88
+ };
89
+ export type SqlSequence = {
90
+ schema: string;
91
+ name: string;
92
+ dataType: string;
93
+ startValue: string;
94
+ increment: string;
95
+ minValue?: string;
96
+ maxValue?: string;
97
+ cycle: boolean;
98
+ };
99
+ export type SqlView = {
100
+ schema: string;
101
+ name: string;
102
+ definition: string;
103
+ columns: SqlColumn[];
104
+ };
105
+ export type IntrospectionFilters = {
106
+ /** Include-list; default `["public"]`. */
107
+ schemas?: string[];
108
+ /**
109
+ * Always excludes `information_schema`, `pg_catalog`, `pg_toast*`, `pg_temp_*`
110
+ * regardless of this list; entries here are additive.
111
+ */
112
+ excludeSchemas?: string[];
113
+ /** Glob patterns; matches against `"<schema>.<name>"`. */
114
+ tables?: string[];
115
+ };
116
+ export type IntrospectionWarning = {
117
+ code: "orphan_id";
118
+ id: string;
119
+ file: string;
120
+ } | {
121
+ code: "new_column";
122
+ id: string;
123
+ tableId: string;
124
+ } | {
125
+ code: "unsupported_type";
126
+ column: string;
127
+ type: string;
128
+ } | {
129
+ code: "view_with_array_columns";
130
+ view: string;
131
+ columns: string[];
132
+ } | {
133
+ code: "ambiguous_filter";
134
+ filter: string;
135
+ };
136
+ export type IntrospectionResult = {
137
+ schema: SqlSchema;
138
+ warnings: IntrospectionWarning[];
139
+ isEmpty: boolean;
140
+ /** Keyed by `"table:<schema>.<view>"`. */
141
+ viewDefinitions: Record<string, string>;
142
+ };
143
+ /**
144
+ * Generic catalog query template. Integration packages (e.g. `@askdb/postgres`) own the
145
+ * concrete set of template names; the engine-agnostic introspect package treats names as
146
+ * opaque strings used for bundle-file mapping and header validation.
147
+ */
148
+ export type SqlTemplate = {
149
+ name: string;
150
+ /** Parameterized SQL string. The connector binds params at run time. */
151
+ sql: string;
152
+ /**
153
+ * Stable ordered column list emitted by the SQL — used by the bundle reader
154
+ * to validate CSV headers and to coerce JSON rows.
155
+ */
156
+ columns: readonly string[];
157
+ };
158
+ export type SqlTemplateBundle = {
159
+ /** Engine identifier (e.g. `"postgres"`, `"mysql"`). Set by the integration package. */
160
+ engine: string;
161
+ /** Schema/version of the template suite. Bumped whenever templates change shape. */
162
+ version: number;
163
+ templates: readonly SqlTemplate[];
164
+ };
165
+ /**
166
+ * Row shape returned by a connector's catalog query runner.
167
+ *
168
+ * This is intentionally scoped to introspection. It is for connector-owned
169
+ * catalog templates, not for running generated user SQL.
170
+ */
171
+ export type CatalogQueryResult = {
172
+ columns: string[];
173
+ rows: unknown[][];
174
+ };
175
+ /**
176
+ * Introspection-only query port used by live connectors to run documented
177
+ * catalog SQL templates.
178
+ */
179
+ export type CatalogQueryRunner = (sql: string, params?: ReadonlyArray<unknown>) => Promise<CatalogQueryResult>;
180
+ /**
181
+ * Engine-agnostic introspection connector. Each integration package (`@askdb/postgres`,
182
+ * a future `@askdb/mysql`, `@askdb/prisma`, ...) exports its own connector and its own
183
+ * input shape; the introspect orchestrator just hands the input through.
184
+ *
185
+ * `templates()` is optional — integrations like Prisma that read schema files do not have
186
+ * a catalog template suite.
187
+ */
188
+ export interface Connector<TInput = unknown> {
189
+ describe(input: TInput): Promise<IntrospectionResult>;
190
+ templates?(): SqlTemplateBundle;
191
+ }
192
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version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,EAAE,OAAO,CAAC;IACjB,0CAA0C;IAC1C,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACzC,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,WAAW,GAAG;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,wEAAwE;IACxE,GAAG,EAAE,MAAM,CAAC;IACZ;;;OAGG;IACH,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;CAC5B,CAAC;AAEF,MAAM,MAAM,iBAAiB,GAAG;IAC9B,wFAAwF;IACxF,MAAM,EAAE,MAAM,CAAC;IACf,oFAAoF;IACpF,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,SAAS,WAAW,EAAE,CAAC;CACnC,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,IAAI,EAAE,OAAO,EAAE,EAAE,CAAC;CACnB,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,kBAAkB,GAAG,CAC/B,GAAG,EAAE,MAAM,EACX,MAAM,CAAC,EAAE,aAAa,CAAC,OAAO,CAAC,KAC5B,OAAO,CAAC,kBAAkB,CAAC,CAAC;AAEjC;;;;;;;GAOG;AACH,MAAM,WAAW,SAAS,CAAC,MAAM,GAAG,OAAO;IACzC,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAAC;IACtD,SAAS,CAAC,IAAI,iBAAiB,CAAC;CACjC"}
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@askdb/introspect",
3
+ "version": "0.3.0-beta.1",
4
+ "description": "AskDB schema introspection: engine-agnostic Connector contract + orchestrator + Schema v2 renderer. Integration packages (e.g. @askdb/postgres) supply connectors.",
5
+ "keywords": [
6
+ "askdb",
7
+ "introspection",
8
+ "schema",
9
+ "schema-v2"
10
+ ],
11
+ "homepage": "https://github.com/Ygilany/AskDB#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/Ygilany/AskDB/issues"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/Ygilany/AskDB.git",
18
+ "directory": "packages/introspect"
19
+ },
20
+ "license": "Apache-2.0",
21
+ "author": "Yahya Gilany",
22
+ "type": "module",
23
+ "main": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.js"
29
+ }
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "README.md",
34
+ "LICENSE",
35
+ "NOTICE"
36
+ ],
37
+ "engines": {
38
+ "node": ">=20"
39
+ },
40
+ "dependencies": {
41
+ "@askdb/core": "0.5.0-beta.0"
42
+ },
43
+ "devDependencies": {
44
+ "typescript": "^5.7.3",
45
+ "vitest": "^3.0.9"
46
+ },
47
+ "scripts": {
48
+ "build": "tsc -p tsconfig.build.json",
49
+ "lint": "tsc -p tsconfig.build.json --noEmit",
50
+ "test": "vitest run --config ../../vitest.config.ts"
51
+ }
52
+ }