@szdatatalk/sqlward-glue 0.0.0-stage → 0.3.2

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
+ 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 notices, patent notices,
102
+ trademark notices, and attribution notices from the Source
103
+ form of the Work, excluding those notices that do not pertain
104
+ to any part of 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 Derivative Works 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 notice 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 reasonable and customary use in describing the
141
+ origin of the Work and 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
+ applicable law and appropriateness of using or redistributing the
151
+ Work and assume any risks associated with Your exercise of permissions
152
+ 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 Contributor be liable
158
+ for damages, including any direct, indirect, special, incidental, or
159
+ consequential damages of any kind, arising out of this License or out
160
+ of the use or inability to use the Work (including but not limited to
161
+ loss of data or data being rendered inaccurate or losses sustained by
162
+ You or third parties or a failure of the Work or any other software),
163
+ even if such Contributor has been advised of the possibility of such
164
+ 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, or indemnity
169
+ terms for Your component or your distribution. However, in accepting
170
+ such obligations, You may act only on Your own behalf and on Your
171
+ sole responsibility, and not on behalf of any other Contributor, and
172
+ only if You agree to indemnify, defend, and hold each Contributor
173
+ harmless for any liability incurred by, or claims asserted against,
174
+ such Contributor by reason of your accepting any such warranty or
175
+ 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 loss-free notice to 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 filename be included in the same "printed page" as the
187
+ copyright notice for easier identification within third-party
188
+ notices.
189
+
190
+ Copyright 2026 SqlWard Contributors
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,39 @@
1
- # Temporary Holding Version
1
+ # `@szdatatalk/sqlward-glue`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Bounded Node.js glue layer over the native Rust `sqlward` CLI (`v0.3.0`).
4
+
5
+ Provides:
6
+
7
+ - **Strict JSON parsing**: `decodeUtf8Strict`, `parseStrictJson` with byte/depth caps and duplicate-key rejection.
8
+ - **Canonical JSON & SHA-256**: `canonicalJson`, `canonicalSha256` for deterministic digests.
9
+ - **Bounded native CLI invocation**: `runAnalyzeJson` spawns `sqlward analyze-json` with `shell: false`, empty environment, timeout, and stdin/stdout byte caps.
10
+ - **JSON Schema compilation**: `compileSchema` powered by `ajv`.
11
+ - **dbt project bundle analysis**: `@szdatatalk/sqlward-glue/dbt` (`analyzeDbtBundle`).
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ npm install @szdatatalk/sqlward-glue
17
+ ```
18
+
19
+ Requires Node.js >= 20.
20
+
21
+ ## Quick start
22
+
23
+ ```js
24
+ import { canonicalSha256, parseStrictJson, runAnalyzeJson } from "@szdatatalk/sqlward-glue";
25
+
26
+ const digest = canonicalSha256({ b: 2, a: 1 });
27
+ const result = await runAnalyzeJson({
28
+ binary: "/path/to/sqlward",
29
+ request: {
30
+ dialect: "postgres",
31
+ sql: "INSERT INTO dws.out (id) SELECT id FROM ods.src",
32
+ },
33
+ });
34
+ console.log(digest, result);
35
+ ```
36
+
37
+ ## License
38
+
39
+ Apache-2.0
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@szdatatalk/sqlward-glue",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.2",
4
+ "repository": {
5
+ "type": "git",
6
+ "url": "git+https://github.com/shygoly/sqlward.git",
7
+ "directory": "packages/glue"
8
+ },
9
+ "homepage": "https://github.com/shygoly/sqlward#readme",
10
+ "bugs": {
11
+ "url": "https://github.com/shygoly/sqlward/issues"
12
+ },
13
+ "description": "Node.js glue layer over the Rust native SqlWard CLI (strict JSON, canonical digests, bounded child process).",
14
+ "type": "module",
15
+ "main": "./src/index.mjs",
16
+ "exports": {
17
+ ".": "./src/index.mjs",
18
+ "./dbt": "./src/dbt/pilot.mjs"
19
+ },
20
+ "files": [
21
+ "src/**",
22
+ "README.md",
23
+ "LICENSE"
24
+ ],
25
+ "keywords": [
26
+ "sqlward",
27
+ "sql",
28
+ "lineage",
29
+ "dbt",
30
+ "canonical-json",
31
+ "data-governance"
32
+ ],
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "scripts": {
37
+ "test": "node --test"
38
+ },
39
+ "engines": {
40
+ "node": ">=20"
41
+ },
42
+ "license": "Apache-2.0",
43
+ "dependencies": {
44
+ "ajv": "8.20.0"
45
+ }
46
+ }
@@ -0,0 +1,84 @@
1
+ // Canonical JSON profile `lineagekit-canonical-json/v1`.
2
+ //
3
+ // Follows RFC 8785 (JCS) for the value domain used by glue payloads:
4
+ // - object keys sorted by UTF-16 code units, no whitespace;
5
+ // - strings serialized with JSON.stringify (JCS escaping);
6
+ // - numbers must be finite and serialized with ECMAScript Number#toString
7
+ // (-0 is emitted as 0);
8
+ // - undefined, functions, symbols, bigint and non-plain objects are rejected.
9
+ // Floats are NOT covered by cross-language equality with the Rust
10
+ // `canonical_json_sha256` helper (serde compact output); see the OpenSpec proposal.
11
+
12
+ import { createHash } from 'node:crypto';
13
+ import { fail } from './errors.mjs';
14
+ import { DEFAULT_MAX_DEPTH } from './strict-json.mjs';
15
+
16
+ export const CANONICAL_JSON_PROFILE = 'lineagekit-canonical-json/v1';
17
+
18
+ /**
19
+ * @param {unknown} value
20
+ * @param {{ maxDepth?: number }} [options]
21
+ * @returns {string}
22
+ */
23
+ export function canonicalJson(value, options = {}) {
24
+ const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;
25
+ return encode(value, 1, maxDepth);
26
+ }
27
+
28
+ /**
29
+ * @param {unknown} value
30
+ * @param {{ maxDepth?: number }} [options]
31
+ * @returns {string} lowercase hex SHA-256 of the UTF-8 canonical bytes
32
+ */
33
+ export function canonicalSha256(value, options = {}) {
34
+ return createHash('sha256').update(canonicalJson(value, options), 'utf8').digest('hex');
35
+ }
36
+
37
+ function encode(value, depth, maxDepth) {
38
+ if (depth > maxDepth) fail('DEPTH_EXCEEDED', 'canonical JSON nesting depth exceeds maximum');
39
+ if (value === null) return 'null';
40
+ switch (typeof value) {
41
+ case 'boolean':
42
+ return value ? 'true' : 'false';
43
+ case 'string':
44
+ assertWellFormed(value);
45
+ return JSON.stringify(value);
46
+ case 'number':
47
+ if (!Number.isFinite(value)) fail('NON_FINITE_NUMBER', 'non-finite numbers cannot be canonicalized');
48
+ return Object.is(value, -0) ? '0' : String(value);
49
+ case 'object':
50
+ if (Array.isArray(value)) {
51
+ return `[${value.map((item) => encode(item, depth + 1, maxDepth)).join(',')}]`;
52
+ }
53
+ return encodeObject(value, depth, maxDepth);
54
+ default:
55
+ return fail('UNSUPPORTED_TYPE', 'value type cannot be canonicalized');
56
+ }
57
+ }
58
+
59
+ function encodeObject(value, depth, maxDepth) {
60
+ const proto = Object.getPrototypeOf(value);
61
+ if (proto !== Object.prototype && proto !== null) fail('UNSUPPORTED_TYPE', 'only plain objects can be canonicalized');
62
+ const keys = Object.keys(value).sort();
63
+ const parts = keys.map((key) => {
64
+ assertWellFormed(key);
65
+ return `${JSON.stringify(key)}:${encode(value[key], depth + 1, maxDepth)}`;
66
+ });
67
+ return `{${parts.join(',')}}`;
68
+ }
69
+
70
+ function assertWellFormed(text) {
71
+ // Reject lone surrogates: they have no valid UTF-8 encoding and would hash differently across runtimes.
72
+ for (let i = 0; i < text.length; i += 1) {
73
+ const code = text.charCodeAt(i);
74
+ if (code >= 0xd800 && code <= 0xdbff) {
75
+ const next = text.charCodeAt(i + 1);
76
+ if (next >= 0xdc00 && next <= 0xdfff) {
77
+ i += 1;
78
+ continue;
79
+ }
80
+ fail('LONE_SURROGATE', 'lone surrogate cannot be canonicalized');
81
+ }
82
+ if (code >= 0xdc00 && code <= 0xdfff) fail('LONE_SURROGATE', 'lone surrogate cannot be canonicalized');
83
+ }
84
+ }
@@ -0,0 +1,76 @@
1
+ // Offline loader for a local dbt artifact directory.
2
+ //
3
+ // Reads only four fixed file names, rejects symlinks and non-regular files,
4
+ // enforces a byte cap before reading, decodes UTF-8 strictly and parses JSON
5
+ // with the strict reader. Never runs dbt, Jinja or SQL.
6
+
7
+ import { lstatSync, readFileSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+ import { fail } from '../errors.mjs';
10
+ import { decodeUtf8Strict, parseStrictJson } from '../strict-json.mjs';
11
+
12
+ export const DEFAULT_MAX_ARTIFACT_BYTES = 8 * 1024 * 1024;
13
+
14
+ const SPECS = Object.freeze({
15
+ manifest: {
16
+ file: 'manifest.json',
17
+ required: true,
18
+ version: /^https:\/\/schemas\.getdbt\.com\/dbt\/manifest\/v(10|11|12)\.json$/,
19
+ },
20
+ catalog: {
21
+ file: 'catalog.json',
22
+ required: false,
23
+ version: /^https:\/\/schemas\.getdbt\.com\/dbt\/catalog\/v1\.json$/,
24
+ },
25
+ runResults: {
26
+ file: 'run_results.json',
27
+ required: false,
28
+ version: /^https:\/\/schemas\.getdbt\.com\/dbt\/run-results\/v[456]\.json$/,
29
+ },
30
+ sources: {
31
+ file: 'sources.json',
32
+ required: false,
33
+ version: /^https:\/\/schemas\.getdbt\.com\/dbt\/sources\/v3\.json$/,
34
+ },
35
+ });
36
+
37
+ /**
38
+ * @param {string} dir local directory containing dbt artifacts
39
+ * @param {{ maxArtifactBytes?: number }} [options]
40
+ * @returns {{ manifest: object, catalog: object|null, runResults: object|null, sources: object|null }}
41
+ */
42
+ export function loadBundle(dir, options = {}) {
43
+ if (typeof dir !== 'string' || dir.length === 0) fail('INVALID_BUNDLE_DIR', 'bundle directory is required');
44
+ const maxBytes = options.maxArtifactBytes ?? DEFAULT_MAX_ARTIFACT_BYTES;
45
+ // Trailing separators make lstat follow a symlink, so strip them before the check.
46
+ const bare = dir.length > 1 ? dir.replace(/[\\/]+$/, '') : dir;
47
+ const dirStat = lstatSync(bare, { throwIfNoEntry: false });
48
+ if (!dirStat || !dirStat.isDirectory() || dirStat.isSymbolicLink()) {
49
+ fail('BUNDLE_DIR_INVALID', 'bundle path must be a real directory');
50
+ }
51
+ const out = {};
52
+ for (const [key, spec] of Object.entries(SPECS)) {
53
+ out[key] = loadArtifact(dir, spec, maxBytes);
54
+ }
55
+ return out;
56
+ }
57
+
58
+ function loadArtifact(dir, spec, maxBytes) {
59
+ const path = join(dir, spec.file);
60
+ const st = lstatSync(path, { throwIfNoEntry: false });
61
+ if (!st) {
62
+ if (spec.required) fail('ARTIFACT_MISSING', `required artifact missing: ${spec.file}`);
63
+ return null;
64
+ }
65
+ if (!st.isFile()) fail('ARTIFACT_NOT_REGULAR_FILE', `artifact is not a regular file: ${spec.file}`);
66
+ if (st.size > maxBytes) fail('INPUT_TOO_LARGE', `artifact exceeds byte limit: ${spec.file}`);
67
+
68
+ const bytes = readFileSync(path);
69
+ const text = decodeUtf8Strict(bytes, { maxBytes });
70
+ const value = parseStrictJson(text, { maxBytes });
71
+ const version = value?.metadata?.dbt_schema_version;
72
+ if (typeof version !== 'string' || !spec.version.test(version)) {
73
+ fail('UNSUPPORTED_ARTIFACT_VERSION', `unsupported schema version for ${spec.file}`);
74
+ }
75
+ return value;
76
+ }
@@ -0,0 +1,475 @@
1
+ // dbt non-SQL pilot (offline). Reads local dbt artifacts, keeps declared,
2
+ // inferred and observed facts in separate namespaces, and delegates every SQL
3
+ // statement to the Rust CLI `analyze-json`. Node never parses SQL, never runs
4
+ // Jinja and never echoes SQL text, descriptions or run messages into output.
5
+ //
6
+ // Fail-closed rules (each one has a regression test):
7
+ // - a model's compiled SQL is sent as exactly one statement (maxStatements: 1);
8
+ // - physical relations are matched only in canonical lowercase form without dots;
9
+ // - ephemeral models are never physical relations and are reachable only through
10
+ // the `__dbt__cte__<name>` convention AND an explicit depends_on edge;
11
+ // - duplicate unique_id across manifest groups blocks the id;
12
+ // - quoted identifiers, quoted SQL and Oracle (case-folding to upper) are not analyzed;
13
+ // - non-OK native status and notes are surfaced as diagnostics.
14
+
15
+ import { canonicalSha256 } from '../canonical-json.mjs';
16
+ import { fail } from '../errors.mjs';
17
+ import { runAnalyzeJson } from '../rust-cli.mjs';
18
+ import { loadBundle } from './artifacts.mjs';
19
+
20
+ export const DBT_PILOT_CONTRACT = 'dbt-node-pilot/v0';
21
+
22
+ /** Dialects accepted by the Rust `analyze-json` adapter (native/ worker). */
23
+ export const PILOT_SQL_DIALECTS = Object.freeze([
24
+ 'postgres', 'mysql', 'doris', 'starrocks', 'oracle', 'spark', 'hive', 'tsql',
25
+ ]);
26
+
27
+ /** Limits sent with every SQL call; recorded in the pilot output. One statement per model. */
28
+ export const PILOT_SQL_LIMITS = Object.freeze({
29
+ profile: 'private',
30
+ maxInputBytes: 2_000_000,
31
+ maxStatements: 1,
32
+ maxEdges: 50_000,
33
+ maxWallMs: 30_000,
34
+ maxMemoryMb: 0,
35
+ maxHttpBodyBytes: 4 * 1024 * 1024,
36
+ isolateProcess: false,
37
+ });
38
+
39
+ const IDENT = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
40
+ const CANONICAL_PART = /^[a-z_][a-z0-9_]{0,127}$/;
41
+ const SAFE_TOKEN = /^[A-Za-z0-9_.-]{1,256}$/;
42
+ const QUOTE_CHARS = /["`[\]]/;
43
+ const CTE_PREFIX = '__dbt__cte__';
44
+
45
+ /**
46
+ * @param {{
47
+ * dir: string,
48
+ * binary?: string,
49
+ * dialect?: string,
50
+ * sql?: boolean,
51
+ * timeoutMs?: number,
52
+ * maxArtifactBytes?: number,
53
+ * }} options
54
+ */
55
+ export async function analyzeDbtBundle(options) {
56
+ const {
57
+ dir,
58
+ binary,
59
+ dialect,
60
+ sql = true,
61
+ timeoutMs = 30_000,
62
+ maxArtifactBytes,
63
+ } = options ?? {};
64
+
65
+ const bundle = loadBundle(dir, { maxArtifactBytes });
66
+ const diagnostics = [];
67
+ const counts = {
68
+ nodes: 0,
69
+ models: 0,
70
+ nonModelNodes: 0,
71
+ declaredEdges: 0,
72
+ observedRecords: 0,
73
+ sqlCalls: 0,
74
+ sqlOk: 0,
75
+ sqlNotOk: 0,
76
+ sqlFailed: 0,
77
+ ephemeralSkipped: 0,
78
+ inferredEdges: 0,
79
+ diagnostics: 0,
80
+ };
81
+
82
+ const adapterRaw = str(bundle.manifest.metadata?.adapter_type);
83
+ const dialectName = dialect ?? adapterRaw ?? null;
84
+ const nodes = buildNodes(bundle.manifest, diagnostics);
85
+ const relationIndex = buildRelationIndex(nodes);
86
+ const declared = buildDeclared(nodes, diagnostics);
87
+ const observed = buildObserved(bundle, nodes, diagnostics);
88
+
89
+ let inferred = [];
90
+ if (sql) {
91
+ if (typeof binary !== 'string' || binary.length === 0) fail('INVALID_BINARY', 'native binary path is required');
92
+ inferred = await buildInferred({
93
+ nodes,
94
+ relationIndex,
95
+ catalog: bundle.catalog,
96
+ binary,
97
+ dialectName,
98
+ timeoutMs,
99
+ diagnostics,
100
+ counts,
101
+ });
102
+ }
103
+
104
+ const nodesOut = [...nodes.values()]
105
+ .sort(byId)
106
+ .map((n) => ({ unique_id: n.unique_id, resource_type: n.resource_type, relation: n.relation }));
107
+
108
+ counts.nodes = nodesOut.length;
109
+ counts.models = nodesOut.filter((n) => n.resource_type === 'model').length;
110
+ counts.nonModelNodes = nodesOut.length - counts.models;
111
+ counts.declaredEdges = declared.length;
112
+ counts.observedRecords = observed.length;
113
+ counts.inferredEdges = inferred.length;
114
+ counts.diagnostics = diagnostics.length;
115
+
116
+ const sortedDiagnostics = [...diagnostics].sort(byDiagnostic);
117
+
118
+ return {
119
+ contract: DBT_PILOT_CONTRACT,
120
+ adapter: adapterRaw === null ? null : safeToken(adapterRaw),
121
+ dialect: dialectName === null ? null : safeToken(dialectName),
122
+ sqlEnabled: sql,
123
+ limits: sql ? { ...PILOT_SQL_LIMITS } : null,
124
+ nodes: nodesOut,
125
+ namespaces: { declared, inferred, observed },
126
+ diagnostics: sortedDiagnostics,
127
+ counts,
128
+ digests: {
129
+ nodes: canonicalSha256(nodesOut),
130
+ declared: canonicalSha256(declared),
131
+ inferred: canonicalSha256(inferred),
132
+ observed: canonicalSha256(observed),
133
+ },
134
+ };
135
+ }
136
+
137
+ function buildNodes(manifest, diagnostics) {
138
+ const map = new Map();
139
+ const blocked = new Set();
140
+
141
+ // Resource types the pilot does not model are reported, never turned into edges.
142
+ if (isPlainObject(manifest.semantic_models)) {
143
+ for (const key of Object.keys(manifest.semantic_models)) {
144
+ diagnostics.push({ code: 'UNSUPPORTED_RESOURCE', subject: safeToken(key), detail: 'semantic_model' });
145
+ }
146
+ }
147
+
148
+ for (const group of ['nodes', 'sources', 'exposures']) {
149
+ const entries = manifest[group] ?? {};
150
+ if (!isPlainObject(entries)) {
151
+ diagnostics.push({ code: 'MALFORMED_MANIFEST_GROUP', subject: group, detail: null });
152
+ continue;
153
+ }
154
+ for (const key of Object.keys(entries)) {
155
+ const entry = entries[key];
156
+ const id = str(entry?.unique_id);
157
+ if (id === null || id !== key) {
158
+ diagnostics.push({ code: 'ID_MISMATCH', subject: safeToken(key), detail: null });
159
+ continue;
160
+ }
161
+ if (map.has(id) || blocked.has(id)) {
162
+ // The same id in two groups is ambiguous: block it rather than let one overwrite the other.
163
+ diagnostics.push({ code: 'DUPLICATE_UNIQUE_ID', subject: safeToken(id), detail: null });
164
+ map.delete(id);
165
+ blocked.add(id);
166
+ continue;
167
+ }
168
+
169
+ const resourceType = str(entry.resource_type) ?? 'unknown';
170
+ const name = str(entry.name);
171
+ const nameForRelation = group === 'sources'
172
+ ? str(entry.identifier) ?? name
173
+ : str(entry.alias) ?? name;
174
+ const parts = resourceType === 'exposure'
175
+ ? null
176
+ : [str(entry.database), str(entry.schema), nameForRelation];
177
+ const relation = parts !== null && parts.every((p) => p !== null) ? parts.join('.') : null;
178
+ const relationKey = parts !== null && parts.every((p) => p !== null && CANONICAL_PART.test(p))
179
+ ? relation
180
+ : null;
181
+ if (relation !== null && relationKey === null) {
182
+ diagnostics.push({ code: 'NON_CANONICAL_RELATION', subject: safeToken(id), detail: null });
183
+ }
184
+
185
+ let dependsOn = [];
186
+ if (entry.depends_on !== undefined) {
187
+ const list = entry.depends_on?.nodes ?? [];
188
+ if (Array.isArray(list) && list.every((d) => typeof d === 'string')) {
189
+ dependsOn = list;
190
+ } else {
191
+ diagnostics.push({ code: 'MALFORMED_DEPENDS_ON', subject: safeToken(id), detail: null });
192
+ }
193
+ }
194
+
195
+ map.set(id, {
196
+ unique_id: id,
197
+ resource_type: resourceType,
198
+ name,
199
+ relation,
200
+ relationKey,
201
+ ephemeral: resourceType === 'model' && str(entry.config?.materialized) === 'ephemeral',
202
+ dependsOn,
203
+ compiledCode: str(entry.compiled_code),
204
+ database: str(entry.database),
205
+ schema: str(entry.schema),
206
+ alias: str(entry.alias),
207
+ quoted: isPlainObject(entry.quoting)
208
+ && ['database', 'schema', 'identifier'].some((k) => entry.quoting[k] === true),
209
+ });
210
+ }
211
+ }
212
+ return map;
213
+ }
214
+
215
+ function buildRelationIndex(nodes) {
216
+ // Ephemeral models are not physical relations; they must not shadow real tables.
217
+ const index = new Map();
218
+ // Non-canonical relations (mixed case, dots) that fold onto a canonical key are a
219
+ // collision the native lower-casing cannot resolve; such keys are never mapped.
220
+ index.shadowed = new Set();
221
+ for (const node of nodes.values()) {
222
+ if (node.relation !== null && node.relationKey === null && !node.ephemeral) {
223
+ index.shadowed.add(node.relation.toLowerCase());
224
+ }
225
+ if (node.relationKey === null || node.ephemeral) continue;
226
+ const list = index.get(node.relationKey) ?? [];
227
+ list.push(node.unique_id);
228
+ index.set(node.relationKey, list);
229
+ }
230
+ return index;
231
+ }
232
+
233
+ function buildDeclared(nodes, diagnostics) {
234
+ const out = [];
235
+ for (const node of nodes.values()) {
236
+ const seen = new Set();
237
+ for (const dep of node.dependsOn) {
238
+ if (dep === node.unique_id) {
239
+ diagnostics.push({ code: 'SELF_DEPENDENCY', subject: safeToken(node.unique_id), detail: null });
240
+ continue;
241
+ }
242
+ if (seen.has(dep)) continue;
243
+ seen.add(dep);
244
+ if (nodes.has(dep)) {
245
+ out.push({
246
+ namespace: 'declared',
247
+ from_node: dep,
248
+ to_node: node.unique_id,
249
+ reason: 'MANIFEST_DEPENDS_ON',
250
+ relation: 'DIRECT',
251
+ });
252
+ } else {
253
+ diagnostics.push({ code: 'UNKNOWN_DEPENDENCY', subject: safeToken(node.unique_id), detail: safeToken(dep) });
254
+ }
255
+ }
256
+ }
257
+ return out.sort((a, b) => cmp(a.from_node, b.from_node) || cmp(a.to_node, b.to_node));
258
+ }
259
+
260
+ function buildObserved(bundle, nodes, diagnostics) {
261
+ const out = [];
262
+ const sources = [
263
+ ['runResults', 'run_result'],
264
+ ['sources', 'source_freshness'],
265
+ ];
266
+ for (const [artifact, kind] of sources) {
267
+ const results = bundle[artifact]?.results;
268
+ if (!Array.isArray(results)) continue;
269
+ for (const r of results) {
270
+ const id = str(r?.unique_id);
271
+ const status = str(r?.status);
272
+ if (id === null || status === null) {
273
+ diagnostics.push({ code: 'MALFORMED_RESULT', subject: kind, detail: null });
274
+ continue;
275
+ }
276
+ if (!nodes.has(id)) {
277
+ diagnostics.push({ code: 'UNKNOWN_RESULT_NODE', subject: safeToken(id), detail: null });
278
+ continue;
279
+ }
280
+ out.push({ namespace: 'observed', kind, node: id, status: safeToken(status) });
281
+ }
282
+ }
283
+ return out.sort((a, b) => cmp(a.node, b.node) || cmp(a.kind, b.kind));
284
+ }
285
+
286
+ async function buildInferred({ nodes, relationIndex, catalog, binary, dialectName, timeoutMs, diagnostics, counts }) {
287
+ if (!PILOT_SQL_DIALECTS.includes(dialectName)) {
288
+ diagnostics.push({ code: 'UNSUPPORTED_DIALECT', subject: safeToken(String(dialectName)), detail: null });
289
+ return [];
290
+ }
291
+ if (dialectName === 'oracle') {
292
+ // Oracle folds unquoted identifiers to upper case; the native adapter folds to lower case.
293
+ // Node cannot tell the two apart without parsing SQL, so no inferred edges are produced.
294
+ diagnostics.push({ code: 'CASE_FOLDING_UNSUPPORTED', subject: 'dialect', detail: 'oracle' });
295
+ return [];
296
+ }
297
+
298
+ const catalogNodes = isPlainObject(catalog?.nodes) ? catalog.nodes : {};
299
+ const cteByName = new Map();
300
+ for (const node of nodes.values()) {
301
+ if (node.ephemeral && node.name) {
302
+ const list = cteByName.get(node.name) ?? [];
303
+ list.push(node.unique_id);
304
+ cteByName.set(node.name, list);
305
+ }
306
+ }
307
+
308
+ const out = [];
309
+ const seen = new Set();
310
+ const models = [...nodes.values()].filter((n) => n.resource_type === 'model').sort(byId);
311
+
312
+ for (const node of nodes.values()) {
313
+ if (node.resource_type !== 'model' && node.compiledCode !== null) {
314
+ diagnostics.push({ code: 'NON_MODEL_SQL_NOT_ANALYZED', subject: safeToken(node.unique_id), detail: safeToken(node.resource_type) });
315
+ }
316
+ }
317
+
318
+ for (const node of models) {
319
+ const subject = safeToken(node.unique_id);
320
+ if (node.ephemeral) {
321
+ // Ephemeral models have no physical relation; they are reached only as CTEs of consumers.
322
+ counts.ephemeralSkipped += 1;
323
+ continue;
324
+ }
325
+ if (node.compiledCode === null) {
326
+ diagnostics.push({ code: 'NO_COMPILED_CODE', subject, detail: null });
327
+ continue;
328
+ }
329
+ if (QUOTE_CHARS.test(node.compiledCode)) {
330
+ // Quoted identifiers in SQL are case-sensitive; Node cannot tokenize SQL to tell them apart.
331
+ diagnostics.push({ code: 'QUOTED_IDENTIFIER_IN_SQL', subject, detail: null });
332
+ continue;
333
+ }
334
+ if (node.quoted) {
335
+ diagnostics.push({ code: 'QUOTED_IDENTIFIER_NOT_SUPPORTED', subject, detail: null });
336
+ continue;
337
+ }
338
+ const parts = [node.database, node.schema, node.alias ?? node.name];
339
+ if (!parts.every((p) => p !== null && IDENT.test(p))) {
340
+ diagnostics.push({ code: 'INVALID_IDENTIFIER', subject, detail: null });
341
+ continue;
342
+ }
343
+ if (node.relationKey === null) continue; // already reported by buildNodes
344
+ if ((relationIndex.get(node.relationKey) ?? []).length !== 1) {
345
+ diagnostics.push({ code: 'AMBIGUOUS_RELATION', subject, detail: null });
346
+ continue;
347
+ }
348
+ const columns = columnNames(catalogNodes[node.unique_id]);
349
+ if (columns === null) {
350
+ diagnostics.push({ code: 'MISSING_COLUMNS', subject, detail: null });
351
+ continue;
352
+ }
353
+
354
+ // The compiled SELECT is wrapped as an INSERT with the catalog column list so the
355
+ // native adapter has an explicit target. Only validated identifiers are interpolated;
356
+ // the compiled SQL is passed through unmodified and must be a single statement.
357
+ const sqlText = `INSERT INTO ${node.relationKey} (${columns.join(', ')}) ${node.compiledCode}`;
358
+ const request = { sql: sqlText, dialect: dialectName, limits: { ...PILOT_SQL_LIMITS } };
359
+
360
+ counts.sqlCalls += 1;
361
+ let result;
362
+ try {
363
+ result = await runAnalyzeJson({ binary, request, timeoutMs });
364
+ } catch (err) {
365
+ counts.sqlFailed += 1;
366
+ diagnostics.push({ code: 'SQL_CALL_FAILED', subject, detail: safeToken(String(err?.code ?? 'UNKNOWN')) });
367
+ continue;
368
+ }
369
+ if (!isPlainObject(result) || !Array.isArray(result.edges)) {
370
+ counts.sqlFailed += 1;
371
+ diagnostics.push({ code: 'SQL_RESULT_MALFORMED', subject, detail: null });
372
+ continue;
373
+ }
374
+ counts.sqlOk += 1;
375
+
376
+ if (result.status !== 'OK') {
377
+ counts.sqlNotOk += 1;
378
+ diagnostics.push({ code: 'SQL_NOT_OK', subject, detail: safeToken(String(result.status)) });
379
+ }
380
+ if (Array.isArray(result.notes)) {
381
+ for (const note of result.notes) {
382
+ diagnostics.push({ code: 'SQL_NOTE', subject, detail: safeToken(String(note)) });
383
+ }
384
+ }
385
+
386
+ for (const edge of result.edges) {
387
+ const srcRel = str(edge?.sourceTable);
388
+ const srcCol = str(edge?.sourceColumn);
389
+ const tgtRel = str(edge?.targetTable);
390
+ const tgtCol = str(edge?.targetColumn);
391
+ const dep = str(edge?.dependencyType);
392
+ if ([srcRel, srcCol, tgtRel, tgtCol, dep].some((v) => v === null)) {
393
+ diagnostics.push({ code: 'MALFORMED_EDGE', subject, detail: null });
394
+ continue;
395
+ }
396
+ if (tgtRel !== node.relationKey) {
397
+ diagnostics.push({ code: 'TARGET_MISMATCH', subject, detail: null });
398
+ continue;
399
+ }
400
+ const fromNode = resolveSource(srcRel, relationIndex, cteByName, node);
401
+ if (fromNode === null) {
402
+ diagnostics.push({ code: 'UNMAPPED_RELATION', subject, detail: safeToken(srcRel) });
403
+ continue;
404
+ }
405
+ const item = {
406
+ namespace: 'inferred',
407
+ from_node: fromNode,
408
+ from_column: srcCol,
409
+ to_node: node.unique_id,
410
+ to_column: tgtCol,
411
+ dependency_type: safeToken(dep),
412
+ reason: 'RUST_ANALYZE_JSON',
413
+ };
414
+ const key = `${item.from_node}\u0000${item.from_column}\u0000${item.to_node}\u0000${item.to_column}\u0000${item.dependency_type}`;
415
+ if (!seen.has(key)) {
416
+ seen.add(key);
417
+ out.push(item);
418
+ }
419
+ }
420
+ }
421
+
422
+ return out.sort((a, b) =>
423
+ cmp(a.from_node, b.from_node) || cmp(a.from_column, b.from_column)
424
+ || cmp(a.to_node, b.to_node) || cmp(a.to_column, b.to_column)
425
+ || cmp(a.dependency_type, b.dependency_type));
426
+ }
427
+
428
+ function resolveSource(relation, relationIndex, cteByName, model) {
429
+ if (relationIndex.shadowed?.has(relation)) return null;
430
+ const ids = relationIndex.get(relation);
431
+ if (ids && ids.length === 1) return ids[0];
432
+ if (relation.startsWith(CTE_PREFIX)) {
433
+ // A CTE name only maps to an ephemeral model that this model explicitly depends on.
434
+ const candidates = (cteByName.get(relation.slice(CTE_PREFIX.length)) ?? [])
435
+ .filter((id) => model.dependsOn.includes(id));
436
+ if (candidates.length === 1) return candidates[0];
437
+ }
438
+ return null;
439
+ }
440
+
441
+ function columnNames(catalogNode) {
442
+ const columns = catalogNode?.columns;
443
+ if (!isPlainObject(columns)) return null;
444
+ const list = Object.values(columns);
445
+ if (list.length === 0) return null;
446
+ const sorted = [...list].sort((a, b) => (a?.index ?? 0) - (b?.index ?? 0));
447
+ const names = sorted.map((c) => str(c?.name));
448
+ if (!names.every((n) => n !== null && IDENT.test(n))) return null;
449
+ return names;
450
+ }
451
+
452
+ function str(value) {
453
+ return typeof value === 'string' ? value : null;
454
+ }
455
+
456
+ function isPlainObject(value) {
457
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
458
+ }
459
+
460
+ function safeToken(value) {
461
+ return typeof value === 'string' && SAFE_TOKEN.test(value) ? value : '<invalid>';
462
+ }
463
+
464
+ function cmp(a, b) {
465
+ if (a === b) return 0;
466
+ return a < b ? -1 : 1;
467
+ }
468
+
469
+ function byId(a, b) {
470
+ return cmp(a.unique_id ?? a.id ?? '', b.unique_id ?? b.id ?? '');
471
+ }
472
+
473
+ function byDiagnostic(a, b) {
474
+ return cmp(a.code, b.code) || cmp(a.subject, b.subject) || cmp(a.detail ?? '', b.detail ?? '');
475
+ }
package/src/errors.mjs ADDED
@@ -0,0 +1,18 @@
1
+ // Sanitized error model for the glue layer. Messages are fixed strings and never
2
+ // include caller input, raw SQL, file paths or child-process output.
3
+
4
+ export class GlueError extends Error {
5
+ /**
6
+ * @param {string} code stable machine-readable code (UPPER_SNAKE_CASE)
7
+ * @param {string} message fixed human-readable message
8
+ */
9
+ constructor(code, message) {
10
+ super(message);
11
+ this.name = 'GlueError';
12
+ this.code = code;
13
+ }
14
+ }
15
+
16
+ export function fail(code, message) {
17
+ throw new GlueError(code, message);
18
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,17 @@
1
+ // Public entry points of the Node glue layer.
2
+
3
+ export { GlueError } from './errors.mjs';
4
+ export {
5
+ DEFAULT_MAX_BYTES,
6
+ DEFAULT_MAX_DEPTH,
7
+ decodeUtf8Strict,
8
+ parseStrictJson,
9
+ } from './strict-json.mjs';
10
+ export { CANONICAL_JSON_PROFILE, canonicalJson, canonicalSha256 } from './canonical-json.mjs';
11
+ export {
12
+ DEFAULT_MAX_STDIN_BYTES,
13
+ DEFAULT_MAX_STDOUT_BYTES,
14
+ DEFAULT_TIMEOUT_MS,
15
+ runAnalyzeJson,
16
+ } from './rust-cli.mjs';
17
+ export { compileSchema } from './schema.mjs';
@@ -0,0 +1,110 @@
1
+ // Bounded, shell-free client for the Rust native CLI (`sqlward analyze-json`).
2
+ //
3
+ // The binary path is supplied explicitly by the caller; PATH is never searched.
4
+ // The child runs with an empty environment, receives the request on stdin and
5
+ // must answer with one strict-JSON ChildAnalyzeResponse on stdout.
6
+
7
+ import { spawn } from 'node:child_process';
8
+ import { GlueError, fail } from './errors.mjs';
9
+ import { parseStrictJson } from './strict-json.mjs';
10
+
11
+ export const DEFAULT_TIMEOUT_MS = 10_000;
12
+ export const DEFAULT_MAX_STDOUT_BYTES = 4 * 1024 * 1024;
13
+ export const DEFAULT_MAX_STDIN_BYTES = 1024 * 1024;
14
+
15
+ /**
16
+ * @param {{
17
+ * binary: string,
18
+ * request: Record<string, unknown>,
19
+ * timeoutMs?: number,
20
+ * maxStdoutBytes?: number,
21
+ * maxStdinBytes?: number,
22
+ * }} options
23
+ * @returns {Promise<unknown>} the `result` field of a successful ChildAnalyzeResponse
24
+ */
25
+ export async function runAnalyzeJson(options) {
26
+ const {
27
+ binary,
28
+ request,
29
+ timeoutMs = DEFAULT_TIMEOUT_MS,
30
+ maxStdoutBytes = DEFAULT_MAX_STDOUT_BYTES,
31
+ maxStdinBytes = DEFAULT_MAX_STDIN_BYTES,
32
+ } = options;
33
+
34
+ if (typeof binary !== 'string' || binary.length === 0) {
35
+ fail('INVALID_BINARY', 'native binary path is required');
36
+ }
37
+ const payload = Buffer.from(JSON.stringify(request), 'utf8');
38
+ if (payload.byteLength > maxStdinBytes) fail('INPUT_TOO_LARGE', 'request exceeds configured byte limit');
39
+
40
+ return new Promise((resolve, reject) => {
41
+ const child = spawn(binary, ['analyze-json'], {
42
+ shell: false,
43
+ env: {},
44
+ stdio: ['pipe', 'pipe', 'ignore'],
45
+ windowsHide: true,
46
+ });
47
+
48
+ const chunks = [];
49
+ let total = 0;
50
+ let settled = false;
51
+
52
+ const settle = (fn, value) => {
53
+ if (settled) return;
54
+ settled = true;
55
+ clearTimeout(timer);
56
+ fn(value);
57
+ };
58
+
59
+ const killChild = () => {
60
+ try {
61
+ child.kill('SIGKILL');
62
+ } catch {
63
+ // already exited
64
+ }
65
+ };
66
+
67
+ const timer = setTimeout(() => {
68
+ killChild();
69
+ settle(reject, new GlueError('CHILD_TIMEOUT', 'native child process exceeded time limit'));
70
+ }, timeoutMs);
71
+
72
+ child.stdout.on('data', (chunk) => {
73
+ total += chunk.byteLength;
74
+ if (total > maxStdoutBytes) {
75
+ killChild();
76
+ settle(reject, new GlueError('CHILD_OUTPUT_TOO_LARGE', 'native child output exceeded byte limit'));
77
+ return;
78
+ }
79
+ chunks.push(chunk);
80
+ });
81
+
82
+ child.on('error', () => {
83
+ settle(reject, new GlueError('CHILD_SPAWN_FAILED', 'native child process could not be started'));
84
+ });
85
+
86
+ child.on('close', (code) => {
87
+ if (settled) return;
88
+ if (code !== 0) {
89
+ settle(reject, new GlueError('CHILD_EXIT_NONZERO', 'native child process failed'));
90
+ return;
91
+ }
92
+ try {
93
+ const text = Buffer.concat(chunks).toString('utf8');
94
+ const response = parseStrictJson(text, { maxBytes: maxStdoutBytes });
95
+ if (!response || typeof response !== 'object' || response.ok !== true) {
96
+ settle(reject, new GlueError('CHILD_RESPONSE_ERROR', 'native child returned an error response'));
97
+ return;
98
+ }
99
+ settle(resolve, response.result);
100
+ } catch (err) {
101
+ settle(reject, new GlueError(err?.code ?? 'CHILD_RESPONSE_INVALID', 'native child response is invalid'));
102
+ }
103
+ });
104
+
105
+ child.stdin.on('error', () => {
106
+ // EPIPE when the child exits early; the close handler reports the failure.
107
+ });
108
+ child.stdin.end(payload);
109
+ });
110
+ }
package/src/schema.mjs ADDED
@@ -0,0 +1,31 @@
1
+ // JSON Schema shape checks for glue payloads. ajv validates structure only and is
2
+ // always applied AFTER strict parsing; it is never used to parse untrusted text.
3
+
4
+ import Ajv from 'ajv';
5
+ import { fail } from './errors.mjs';
6
+
7
+ const ajv = new Ajv({
8
+ strict: true,
9
+ allErrors: false,
10
+ useDefaults: false,
11
+ removeAdditional: false,
12
+ coerceTypes: false,
13
+ allowUnionTypes: false,
14
+ });
15
+
16
+ const compiledCache = new WeakMap();
17
+
18
+ /**
19
+ * @param {object} schema JSON Schema (draft-07 or 2019-09 subset supported by ajv 8)
20
+ * @returns {(data: unknown) => true}
21
+ */
22
+ export function compileSchema(schema) {
23
+ if (compiledCache.has(schema)) return compiledCache.get(schema);
24
+ const validate = ajv.compile(schema);
25
+ const check = (data) => {
26
+ if (!validate(data)) fail('SCHEMA_INVALID', 'payload does not match schema');
27
+ return true;
28
+ };
29
+ compiledCache.set(schema, check);
30
+ return check;
31
+ }
@@ -0,0 +1,231 @@
1
+ // Strict JSON reader for untrusted input.
2
+ //
3
+ // Rejects what JSON.parse silently accepts or mangles: duplicate keys (at any
4
+ // depth), non-finite numbers, integer literals beyond Number.MAX_SAFE_INTEGER,
5
+ // lone surrogates, raw control characters inside strings, nesting deeper than
6
+ // maxDepth and input larger than maxBytes. Errors carry fixed codes and never
7
+ // echo the input.
8
+
9
+ import { fail } from './errors.mjs';
10
+
11
+ export const DEFAULT_MAX_DEPTH = 64;
12
+ export const DEFAULT_MAX_BYTES = 4 * 1024 * 1024;
13
+
14
+ const WS = new Set([0x20, 0x09, 0x0a, 0x0d]);
15
+
16
+ /**
17
+ * Decode bytes as UTF-8 strictly (invalid sequences fail closed).
18
+ * @param {Uint8Array} bytes
19
+ * @param {{ maxBytes?: number }} [options]
20
+ * @returns {string}
21
+ */
22
+ export function decodeUtf8Strict(bytes, options = {}) {
23
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
24
+ if (bytes.byteLength > maxBytes) fail('INPUT_TOO_LARGE', 'input exceeds configured byte limit');
25
+ try {
26
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: false }).decode(bytes);
27
+ } catch {
28
+ return fail('INVALID_UTF8', 'input is not valid UTF-8');
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Parse a JSON text with strict rules.
34
+ * @param {string} text
35
+ * @param {{ maxDepth?: number, maxBytes?: number }} [options]
36
+ * @returns {unknown}
37
+ */
38
+ export function parseStrictJson(text, options = {}) {
39
+ const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;
40
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
41
+ if (Buffer.byteLength(text, 'utf8') > maxBytes) {
42
+ fail('INPUT_TOO_LARGE', 'input exceeds configured byte limit');
43
+ }
44
+ const reader = new Reader(text, maxDepth);
45
+ reader.skipWs();
46
+ const value = reader.readValue(1);
47
+ reader.skipWs();
48
+ if (reader.pos !== text.length) fail('INVALID_JSON', 'unexpected trailing content');
49
+ return value;
50
+ }
51
+
52
+ class Reader {
53
+ /**
54
+ * @param {string} text
55
+ * @param {number} maxDepth
56
+ */
57
+ constructor(text, maxDepth) {
58
+ this.text = text;
59
+ this.pos = 0;
60
+ this.maxDepth = maxDepth;
61
+ }
62
+
63
+ skipWs() {
64
+ while (this.pos < this.text.length && WS.has(this.text.charCodeAt(this.pos))) this.pos += 1;
65
+ }
66
+
67
+ peek() {
68
+ return this.text.charAt(this.pos);
69
+ }
70
+
71
+ expect(ch) {
72
+ if (this.text.charAt(this.pos) !== ch) fail('INVALID_JSON', 'malformed JSON');
73
+ this.pos += 1;
74
+ }
75
+
76
+ /** @param {number} depth */
77
+ readValue(depth) {
78
+ if (depth > this.maxDepth) fail('DEPTH_EXCEEDED', 'JSON nesting depth exceeds maximum');
79
+ const ch = this.peek();
80
+ if (ch === '{') return this.readObject(depth);
81
+ if (ch === '[') return this.readArray(depth);
82
+ if (ch === '"') return this.readString();
83
+ if (this.text.startsWith('NaN', this.pos) || this.text.startsWith('Infinity', this.pos)
84
+ || this.text.startsWith('-Infinity', this.pos)) {
85
+ fail('NON_FINITE_NUMBER', 'non-finite numbers are not allowed');
86
+ }
87
+ if (ch === '-' || (ch >= '0' && ch <= '9')) return this.readNumber();
88
+ if (this.text.startsWith('true', this.pos)) return this.literal('true', true);
89
+ if (this.text.startsWith('false', this.pos)) return this.literal('false', false);
90
+ if (this.text.startsWith('null', this.pos)) return this.literal('null', null);
91
+ return fail('INVALID_JSON', 'malformed JSON');
92
+ }
93
+
94
+ literal(word, value) {
95
+ this.pos += word.length;
96
+ return value;
97
+ }
98
+
99
+ readObject(depth) {
100
+ this.expect('{');
101
+ const out = Object.create(null);
102
+ this.skipWs();
103
+ if (this.peek() === '}') {
104
+ this.pos += 1;
105
+ return out;
106
+ }
107
+ for (;;) {
108
+ this.skipWs();
109
+ if (this.peek() !== '"') fail('INVALID_JSON', 'malformed JSON object key');
110
+ const key = this.readString();
111
+ if (Object.prototype.hasOwnProperty.call(out, key)) {
112
+ fail('DUPLICATE_KEY', 'duplicate object key');
113
+ }
114
+ this.skipWs();
115
+ this.expect(':');
116
+ this.skipWs();
117
+ out[key] = this.readValue(depth + 1);
118
+ this.skipWs();
119
+ const next = this.peek();
120
+ if (next === ',') {
121
+ this.pos += 1;
122
+ continue;
123
+ }
124
+ if (next === '}') {
125
+ this.pos += 1;
126
+ return out;
127
+ }
128
+ return fail('INVALID_JSON', 'malformed JSON object');
129
+ }
130
+ }
131
+
132
+ readArray(depth) {
133
+ this.expect('[');
134
+ const out = [];
135
+ this.skipWs();
136
+ if (this.peek() === ']') {
137
+ this.pos += 1;
138
+ return out;
139
+ }
140
+ for (;;) {
141
+ this.skipWs();
142
+ out.push(this.readValue(depth + 1));
143
+ this.skipWs();
144
+ const next = this.peek();
145
+ if (next === ',') {
146
+ this.pos += 1;
147
+ continue;
148
+ }
149
+ if (next === ']') {
150
+ this.pos += 1;
151
+ return out;
152
+ }
153
+ return fail('INVALID_JSON', 'malformed JSON array');
154
+ }
155
+ }
156
+
157
+ readString() {
158
+ this.expect('"');
159
+ let out = '';
160
+ for (;;) {
161
+ if (this.pos >= this.text.length) fail('INVALID_JSON', 'unterminated string');
162
+ const code = this.text.charCodeAt(this.pos);
163
+ if (code === 0x22) {
164
+ this.pos += 1;
165
+ return out;
166
+ }
167
+ if (code < 0x20) fail('INVALID_JSON', 'raw control character in string');
168
+ if (code === 0x5c) {
169
+ out += this.readEscape();
170
+ continue;
171
+ }
172
+ if (code >= 0xd800 && code <= 0xdfff) {
173
+ // Only valid high+low pairs may appear raw in a JS string; lone surrogates fail closed.
174
+ const next = this.text.charCodeAt(this.pos + 1);
175
+ if (code <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) {
176
+ out += this.text.slice(this.pos, this.pos + 2);
177
+ this.pos += 2;
178
+ continue;
179
+ }
180
+ fail('LONE_SURROGATE', 'lone surrogate in string');
181
+ }
182
+ out += this.text.charAt(this.pos);
183
+ this.pos += 1;
184
+ }
185
+ }
186
+
187
+ readEscape() {
188
+ this.pos += 1; // consume backslash
189
+ const ch = this.peek();
190
+ const simple = { '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t' };
191
+ if (Object.prototype.hasOwnProperty.call(simple, ch)) {
192
+ this.pos += 1;
193
+ return simple[ch];
194
+ }
195
+ if (ch !== 'u') fail('INVALID_JSON', 'invalid escape sequence');
196
+ this.pos += 1; // consume 'u'
197
+ const unit = this.readHex4();
198
+ if (unit >= 0xd800 && unit <= 0xdbff) {
199
+ if (this.text.charAt(this.pos) !== '\\' || this.text.charAt(this.pos + 1) !== 'u') {
200
+ fail('LONE_SURROGATE', 'lone surrogate in string');
201
+ }
202
+ this.pos += 2;
203
+ const low = this.readHex4();
204
+ if (low < 0xdc00 || low > 0xdfff) fail('LONE_SURROGATE', 'lone surrogate in string');
205
+ return String.fromCharCode(unit, low);
206
+ }
207
+ if (unit >= 0xdc00 && unit <= 0xdfff) fail('LONE_SURROGATE', 'lone surrogate in string');
208
+ return String.fromCharCode(unit);
209
+ }
210
+
211
+ readHex4() {
212
+ const hex = this.text.slice(this.pos, this.pos + 4);
213
+ if (!/^[0-9a-fA-F]{4}$/.test(hex)) fail('INVALID_JSON', 'invalid unicode escape');
214
+ this.pos += 4;
215
+ return Number.parseInt(hex, 16);
216
+ }
217
+
218
+ readNumber() {
219
+ const match = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/.exec(this.text.slice(this.pos, this.pos + 400));
220
+ if (!match) fail('INVALID_JSON', 'malformed number');
221
+ const literal = match[0];
222
+ this.pos += literal.length;
223
+ const isInteger = match[2] === undefined && match[3] === undefined;
224
+ const value = Number(literal);
225
+ if (!Number.isFinite(value)) fail('NON_FINITE_NUMBER', 'non-finite numbers are not allowed');
226
+ if (isInteger && !Number.isSafeInteger(value)) {
227
+ fail('UNSAFE_INTEGER', 'integer literal exceeds safe integer range');
228
+ }
229
+ return value === 0 ? 0 : value;
230
+ }
231
+ }