@sanity-labs/groq-wasm 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +213 -0
- package/dist/index.cjs +253 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +160 -0
- package/dist/index.d.ts +160 -0
- package/dist/index.js +204 -0
- package/dist/index.js.map +1 -0
- package/package.json +60 -0
- package/wasm/groq_wasm.cjs +213 -0
- package/wasm/groq_wasm.d.ts +27 -0
- package/wasm/groq_wasm_bg.wasm +0 -0
- package/wasm/groq_wasm_bg.wasm.d.ts +12 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024-present Sanity.io
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
# @sanity-labs/groq-wasm
|
|
2
|
+
|
|
3
|
+
WASM bindings for GROQ linting and formatting.
|
|
4
|
+
|
|
5
|
+
This package provides TypeScript wrappers around:
|
|
6
|
+
|
|
7
|
+
- **[groq-lint](https://github.com/atombender/groq-lint)** (Rust) - GROQ query linting
|
|
8
|
+
- **[groq-format](https://github.com/atombender/groq-format)** (Rust) - GROQ query formatting
|
|
9
|
+
|
|
10
|
+
Both are compiled to WebAssembly for use in Node.js and browsers without requiring the Rust toolchain.
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm install @sanity-labs/groq-wasm
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Usage
|
|
19
|
+
|
|
20
|
+
```typescript
|
|
21
|
+
import { initWasm, lint, format } from '@sanity-labs/groq-wasm'
|
|
22
|
+
|
|
23
|
+
// Initialize WASM (call once at startup)
|
|
24
|
+
await initWasm()
|
|
25
|
+
|
|
26
|
+
// Lint a query
|
|
27
|
+
const findings = lint('*[_type == "post"]{ author-> }')
|
|
28
|
+
console.log(findings)
|
|
29
|
+
// [{ ruleId: 'join-in-filter', message: '...', severity: 'error' }]
|
|
30
|
+
|
|
31
|
+
// Format a query
|
|
32
|
+
const formatted = format('*[_type=="post"]{title,body}')
|
|
33
|
+
console.log(formatted)
|
|
34
|
+
// '*[_type == "post"]{ title, body }'
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## API
|
|
38
|
+
|
|
39
|
+
### Initialization
|
|
40
|
+
|
|
41
|
+
#### `initWasm(): Promise<void>`
|
|
42
|
+
|
|
43
|
+
Initialize the WASM modules. Must be called before using `lint()` or `format()`.
|
|
44
|
+
Safe to call multiple times.
|
|
45
|
+
|
|
46
|
+
#### `isInitialized(): boolean`
|
|
47
|
+
|
|
48
|
+
Check if WASM modules are initialized.
|
|
49
|
+
|
|
50
|
+
### Linting
|
|
51
|
+
|
|
52
|
+
#### `lint(query: string, config?: WasmLintConfig): Finding[]`
|
|
53
|
+
|
|
54
|
+
Lint a GROQ query and return findings.
|
|
55
|
+
|
|
56
|
+
```typescript
|
|
57
|
+
interface WasmLintConfig {
|
|
58
|
+
rules?: Record<string, boolean> // Enable/disable specific rules
|
|
59
|
+
}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
#### `lintAsync(query: string, config?: WasmLintConfig): Promise<Finding[]>`
|
|
63
|
+
|
|
64
|
+
Async version of `lint()`.
|
|
65
|
+
|
|
66
|
+
### Formatting
|
|
67
|
+
|
|
68
|
+
#### `format(query: string, config?: WasmFormatConfig): string`
|
|
69
|
+
|
|
70
|
+
Format a GROQ query.
|
|
71
|
+
|
|
72
|
+
```typescript
|
|
73
|
+
interface WasmFormatConfig {
|
|
74
|
+
width?: number // Max line width (default: 80)
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
#### `formatAsync(query: string, config?: WasmFormatConfig): Promise<string>`
|
|
79
|
+
|
|
80
|
+
Async version of `format()`.
|
|
81
|
+
|
|
82
|
+
#### `isValidSyntax(query: string): boolean`
|
|
83
|
+
|
|
84
|
+
Check if a query has valid GROQ syntax.
|
|
85
|
+
|
|
86
|
+
### Constants
|
|
87
|
+
|
|
88
|
+
#### `DEFAULT_WIDTH: number`
|
|
89
|
+
|
|
90
|
+
Default line width for formatting (80).
|
|
91
|
+
|
|
92
|
+
#### `RULE_ID_MAP: Record<string, string>`
|
|
93
|
+
|
|
94
|
+
Mapping from Rust rule IDs (snake_case) to TS convention (kebab-case).
|
|
95
|
+
|
|
96
|
+
## Lint Rules
|
|
97
|
+
|
|
98
|
+
The following rules are available (from Rust groq-lint):
|
|
99
|
+
|
|
100
|
+
| Rule ID | Severity | Description |
|
|
101
|
+
| ------------------------------ | -------- | ---------------------------------------------------- |
|
|
102
|
+
| `join-in-filter` | error | Dereference (->) inside filter prevents optimization |
|
|
103
|
+
| `join-to-get-id` | warning | Using -> to get \_id (use .\_ref instead) |
|
|
104
|
+
| `computed-value-in-filter` | error | Computed values in filter prevent optimization |
|
|
105
|
+
| `match-on-id` | info | Using match on \_id with wildcard |
|
|
106
|
+
| `order-on-expr` | error | Ordering on computed values |
|
|
107
|
+
| `deep-pagination` | warning | Large offset in slice (>=1000) |
|
|
108
|
+
| `large-pages` | warning | Fetching >100 results from index 0 |
|
|
109
|
+
| `non-literal-comparison` | error | Comparing two non-literal expressions |
|
|
110
|
+
| `repeated-dereference` | info | Multiple -> on same attribute in projection |
|
|
111
|
+
| `count-in-correlated-subquery` | info | count() on correlated subqueries |
|
|
112
|
+
| `very-large-query` | error | Query exceeds 10KB |
|
|
113
|
+
| `extremely-large-query` | error | Query exceeds 100KB |
|
|
114
|
+
| `many-joins` | warning | Query has >10 dereference operators |
|
|
115
|
+
|
|
116
|
+
## Error Handling
|
|
117
|
+
|
|
118
|
+
```typescript
|
|
119
|
+
import { WasmError } from '@sanity-labs/groq-wasm'
|
|
120
|
+
|
|
121
|
+
try {
|
|
122
|
+
const findings = lint(query)
|
|
123
|
+
} catch (error) {
|
|
124
|
+
if (error instanceof WasmError) {
|
|
125
|
+
switch (error.code) {
|
|
126
|
+
case 'NOT_INITIALIZED':
|
|
127
|
+
// Call initWasm() first
|
|
128
|
+
break
|
|
129
|
+
case 'PARSE_ERROR':
|
|
130
|
+
// Invalid GROQ syntax
|
|
131
|
+
break
|
|
132
|
+
case 'WASM_ERROR':
|
|
133
|
+
// Other WASM error
|
|
134
|
+
break
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
## Browser Support
|
|
141
|
+
|
|
142
|
+
This package works in modern browsers that support WebAssembly. The WASM modules are loaded automatically based on the environment.
|
|
143
|
+
|
|
144
|
+
```typescript
|
|
145
|
+
// In browser
|
|
146
|
+
import { initWasm, lint } from '@sanity-labs/groq-wasm'
|
|
147
|
+
|
|
148
|
+
await initWasm()
|
|
149
|
+
const findings = lint(query)
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
## Architecture
|
|
153
|
+
|
|
154
|
+
This package uses a **wrapper crate** approach:
|
|
155
|
+
|
|
156
|
+
```
|
|
157
|
+
packages/groq-wasm/
|
|
158
|
+
├── rust/ # Rust wrapper crate
|
|
159
|
+
│ ├── Cargo.toml # Depends on groq-lint & groq-format
|
|
160
|
+
│ └── src/lib.rs # wasm-bindgen exports
|
|
161
|
+
├── wasm/ # Built WASM output (generated)
|
|
162
|
+
├── src/ # TypeScript wrappers
|
|
163
|
+
│ ├── index.ts # Main exports
|
|
164
|
+
│ ├── lint.ts # Linting API
|
|
165
|
+
│ ├── format.ts # Formatting API
|
|
166
|
+
│ └── wasm-loader.ts # WASM initialization
|
|
167
|
+
└── scripts/
|
|
168
|
+
└── build-wasm.sh # Build script
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
The Rust crate depends on upstream repos as git dependencies (no forking required).
|
|
172
|
+
|
|
173
|
+
## Building from Source
|
|
174
|
+
|
|
175
|
+
To rebuild the WASM bindings:
|
|
176
|
+
|
|
177
|
+
### Prerequisites
|
|
178
|
+
|
|
179
|
+
```bash
|
|
180
|
+
# Install Rust
|
|
181
|
+
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
|
|
182
|
+
|
|
183
|
+
# Add WASM target
|
|
184
|
+
rustup target add wasm32-unknown-unknown
|
|
185
|
+
|
|
186
|
+
# Install wasm-pack
|
|
187
|
+
cargo install wasm-pack
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
### Build
|
|
191
|
+
|
|
192
|
+
```bash
|
|
193
|
+
cd packages/groq-wasm
|
|
194
|
+
./scripts/build-wasm.sh
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
This will:
|
|
198
|
+
|
|
199
|
+
1. Compile the Rust wrapper crate to WASM
|
|
200
|
+
2. Generate JS bindings via wasm-bindgen
|
|
201
|
+
3. Output files to `wasm/`
|
|
202
|
+
|
|
203
|
+
## Performance
|
|
204
|
+
|
|
205
|
+
The WASM implementation provides significant performance benefits:
|
|
206
|
+
|
|
207
|
+
- **Linting**: ~5-10x faster than TypeScript for complex queries
|
|
208
|
+
- **Formatting**: Near-instant formatting for most queries
|
|
209
|
+
- **Memory**: Lower memory footprint than JavaScript AST processing
|
|
210
|
+
|
|
211
|
+
## License
|
|
212
|
+
|
|
213
|
+
MIT
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var index_exports = {};
|
|
32
|
+
__export(index_exports, {
|
|
33
|
+
DEFAULT_WIDTH: () => DEFAULT_WIDTH,
|
|
34
|
+
RULE_ID_MAP: () => RULE_ID_MAP,
|
|
35
|
+
WasmError: () => WasmError,
|
|
36
|
+
format: () => format,
|
|
37
|
+
formatAsync: () => formatAsync,
|
|
38
|
+
initWasm: () => initWasm,
|
|
39
|
+
isInitialized: () => isInitialized,
|
|
40
|
+
isValidSyntax: () => isValidSyntax,
|
|
41
|
+
lint: () => lint,
|
|
42
|
+
lintAsync: () => lintAsync,
|
|
43
|
+
mapRuleId: () => mapRuleId,
|
|
44
|
+
mapSeverity: () => mapSeverity
|
|
45
|
+
});
|
|
46
|
+
module.exports = __toCommonJS(index_exports);
|
|
47
|
+
|
|
48
|
+
// src/types.ts
|
|
49
|
+
function mapSeverity(wasmSeverity) {
|
|
50
|
+
switch (wasmSeverity) {
|
|
51
|
+
case "high":
|
|
52
|
+
return "error";
|
|
53
|
+
case "medium":
|
|
54
|
+
return "warning";
|
|
55
|
+
case "low":
|
|
56
|
+
return "info";
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
var WasmError = class extends Error {
|
|
60
|
+
constructor(message, code) {
|
|
61
|
+
super(message);
|
|
62
|
+
this.code = code;
|
|
63
|
+
this.name = "WasmError";
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
var RULE_ID_MAP = {
|
|
67
|
+
join_in_filter: "join-in-filter",
|
|
68
|
+
join_to_get_id: "join-to-get-id",
|
|
69
|
+
computed_value_in_filter: "computed-value-in-filter",
|
|
70
|
+
match_on_id: "match-on-id",
|
|
71
|
+
order_on_expr: "order-on-expr",
|
|
72
|
+
deep_pagination: "deep-pagination",
|
|
73
|
+
large_pages: "large-pages",
|
|
74
|
+
non_literal_comparison: "non-literal-comparison",
|
|
75
|
+
repeated_dereference: "repeated-dereference",
|
|
76
|
+
count_in_correlated_subquery: "count-in-correlated-subquery",
|
|
77
|
+
very_large_query: "very-large-query",
|
|
78
|
+
extremely_large_query: "extremely-large-query",
|
|
79
|
+
many_joins: "many-joins"
|
|
80
|
+
};
|
|
81
|
+
function mapRuleId(rustRuleId) {
|
|
82
|
+
return RULE_ID_MAP[rustRuleId] ?? rustRuleId.replace(/_/g, "-");
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// src/wasm-loader.ts
|
|
86
|
+
var import_meta = {};
|
|
87
|
+
var initialized = false;
|
|
88
|
+
var initPromise = null;
|
|
89
|
+
var wasmLint = null;
|
|
90
|
+
var wasmFormat = null;
|
|
91
|
+
function isInitialized() {
|
|
92
|
+
return initialized;
|
|
93
|
+
}
|
|
94
|
+
async function initWasm() {
|
|
95
|
+
if (initialized) {
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
if (initPromise) {
|
|
99
|
+
return initPromise;
|
|
100
|
+
}
|
|
101
|
+
initPromise = doInit();
|
|
102
|
+
await initPromise;
|
|
103
|
+
}
|
|
104
|
+
async function doInit() {
|
|
105
|
+
try {
|
|
106
|
+
const { createRequire } = await import("module");
|
|
107
|
+
const { fileURLToPath } = await import("url");
|
|
108
|
+
const { dirname, join } = await import("path");
|
|
109
|
+
const currentDir = dirname(fileURLToPath(import_meta.url));
|
|
110
|
+
const require2 = createRequire(import_meta.url);
|
|
111
|
+
const wasmPath = join(currentDir, "..", "wasm", "groq_wasm.cjs");
|
|
112
|
+
const wasm = require2(wasmPath);
|
|
113
|
+
wasmLint = wasm.lint;
|
|
114
|
+
wasmFormat = wasm.format;
|
|
115
|
+
initialized = true;
|
|
116
|
+
} catch (error) {
|
|
117
|
+
initPromise = null;
|
|
118
|
+
throw new WasmError(
|
|
119
|
+
`Failed to initialize WASM: ${error instanceof Error ? error.message : String(error)}`,
|
|
120
|
+
"WASM_ERROR"
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
function callLint(query) {
|
|
125
|
+
if (!initialized || !wasmLint) {
|
|
126
|
+
throw new WasmError("WASM not initialized. Call initWasm() first.", "NOT_INITIALIZED");
|
|
127
|
+
}
|
|
128
|
+
return wasmLint(query);
|
|
129
|
+
}
|
|
130
|
+
function callFormat(query, width) {
|
|
131
|
+
if (!initialized || !wasmFormat) {
|
|
132
|
+
throw new WasmError("WASM not initialized. Call initWasm() first.", "NOT_INITIALIZED");
|
|
133
|
+
}
|
|
134
|
+
return wasmFormat(query, width ?? null);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// src/lint.ts
|
|
138
|
+
function lint(query, config) {
|
|
139
|
+
if (!isInitialized()) {
|
|
140
|
+
throw new WasmError("WASM not initialized. Call initWasm() first.", "NOT_INITIALIZED");
|
|
141
|
+
}
|
|
142
|
+
if (!query.trim()) {
|
|
143
|
+
return [];
|
|
144
|
+
}
|
|
145
|
+
try {
|
|
146
|
+
const resultJson = callLint(query);
|
|
147
|
+
const wasmFindings = JSON.parse(resultJson);
|
|
148
|
+
let findings = wasmFindings;
|
|
149
|
+
if (config?.rules) {
|
|
150
|
+
const rules = config.rules;
|
|
151
|
+
findings = findings.filter((f) => {
|
|
152
|
+
const enabled = rules[f.ruleId];
|
|
153
|
+
return enabled !== false;
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
return findings.map((wf) => convertFinding(wf, query));
|
|
157
|
+
} catch (error) {
|
|
158
|
+
if (error instanceof WasmError) {
|
|
159
|
+
throw error;
|
|
160
|
+
}
|
|
161
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
162
|
+
if (message.includes("parse") || message.includes("Parse")) {
|
|
163
|
+
throw new WasmError(`Failed to parse query: ${message}`, "PARSE_ERROR");
|
|
164
|
+
}
|
|
165
|
+
throw new WasmError(`Lint failed: ${message}`, "WASM_ERROR");
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
async function lintAsync(query, config) {
|
|
169
|
+
return lint(query, config);
|
|
170
|
+
}
|
|
171
|
+
function convertFinding(wf, query) {
|
|
172
|
+
return {
|
|
173
|
+
ruleId: mapRuleId(wf.ruleId),
|
|
174
|
+
message: wf.message,
|
|
175
|
+
severity: mapSeverity(wf.severity),
|
|
176
|
+
span: byteSpanToSourceSpan(wf.start, wf.end, query)
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
function byteSpanToSourceSpan(startByte, endByte, query) {
|
|
180
|
+
return {
|
|
181
|
+
start: byteOffsetToLocation(startByte, query),
|
|
182
|
+
end: byteOffsetToLocation(endByte, query)
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
function byteOffsetToLocation(offset, query) {
|
|
186
|
+
let line = 1;
|
|
187
|
+
let column = 1;
|
|
188
|
+
let currentOffset = 0;
|
|
189
|
+
for (const char of query) {
|
|
190
|
+
if (currentOffset >= offset) {
|
|
191
|
+
break;
|
|
192
|
+
}
|
|
193
|
+
if (char === "\n") {
|
|
194
|
+
line++;
|
|
195
|
+
column = 1;
|
|
196
|
+
} else {
|
|
197
|
+
column++;
|
|
198
|
+
}
|
|
199
|
+
currentOffset++;
|
|
200
|
+
}
|
|
201
|
+
return { line, column, offset };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// src/format.ts
|
|
205
|
+
var DEFAULT_WIDTH = 80;
|
|
206
|
+
function format(query, config) {
|
|
207
|
+
if (!isInitialized()) {
|
|
208
|
+
throw new WasmError("WASM not initialized. Call initWasm() first.", "NOT_INITIALIZED");
|
|
209
|
+
}
|
|
210
|
+
const width = config?.width ?? DEFAULT_WIDTH;
|
|
211
|
+
if (!query.trim()) {
|
|
212
|
+
return query;
|
|
213
|
+
}
|
|
214
|
+
try {
|
|
215
|
+
return callFormat(query, width);
|
|
216
|
+
} catch (error) {
|
|
217
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
218
|
+
if (message.includes("parse") || message.includes("Parse")) {
|
|
219
|
+
throw new WasmError(`Failed to parse query: ${message}`, "PARSE_ERROR");
|
|
220
|
+
}
|
|
221
|
+
throw new WasmError(`Format failed: ${message}`, "WASM_ERROR");
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
async function formatAsync(query, config) {
|
|
225
|
+
return format(query, config);
|
|
226
|
+
}
|
|
227
|
+
function isValidSyntax(query) {
|
|
228
|
+
try {
|
|
229
|
+
format(query);
|
|
230
|
+
return true;
|
|
231
|
+
} catch (error) {
|
|
232
|
+
if (error instanceof WasmError && error.code === "PARSE_ERROR") {
|
|
233
|
+
return false;
|
|
234
|
+
}
|
|
235
|
+
throw error;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
239
|
+
0 && (module.exports = {
|
|
240
|
+
DEFAULT_WIDTH,
|
|
241
|
+
RULE_ID_MAP,
|
|
242
|
+
WasmError,
|
|
243
|
+
format,
|
|
244
|
+
formatAsync,
|
|
245
|
+
initWasm,
|
|
246
|
+
isInitialized,
|
|
247
|
+
isValidSyntax,
|
|
248
|
+
lint,
|
|
249
|
+
lintAsync,
|
|
250
|
+
mapRuleId,
|
|
251
|
+
mapSeverity
|
|
252
|
+
});
|
|
253
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/types.ts","../src/wasm-loader.ts","../src/lint.ts","../src/format.ts"],"sourcesContent":["/**\n * @sanity-labs/groq-wasm\n *\n * WASM bindings for GROQ linting and formatting.\n *\n * This package provides TypeScript wrappers around:\n * - groq-lint (Rust) - GROQ query linting\n * - groq-format (Rust) - GROQ query formatting\n *\n * Both are compiled to WebAssembly for use in Node.js and browsers\n * without requiring the Rust toolchain.\n *\n * @example\n * ```typescript\n * import { initWasm, lint, format } from '@sanity-labs/groq-wasm'\n *\n * // Initialize WASM (call once at startup)\n * await initWasm()\n *\n * // Lint a query\n * const findings = lint('*[_type == \"post\"]{ author-> }')\n * console.log(findings)\n * // [{ ruleId: 'join-in-filter', message: '...', severity: 'error' }]\n *\n * // Format a query\n * const formatted = format('*[_type==\"post\"]{title,body}')\n * console.log(formatted)\n * // '*[_type == \"post\"]{ title, body }'\n * ```\n *\n * @packageDocumentation\n */\n\n// Re-export from lint module\nexport { lint, lintAsync } from './lint.js'\n\n// Re-export from format module\nexport { DEFAULT_WIDTH, format, formatAsync, isValidSyntax } from './format.js'\n\n// Re-export from wasm-loader\nexport { initWasm, isInitialized } from './wasm-loader.js'\n\n// Re-export types\nexport {\n mapRuleId,\n mapSeverity,\n RULE_ID_MAP,\n WasmError,\n type WasmFinding,\n type WasmFormatConfig,\n type WasmLintConfig,\n type WasmSeverity,\n} from './types.js'\n","/**\n * Types for @sanity-labs/groq-wasm\n *\n * These types match the Rust API from groq-lint and groq-format,\n * converted to TypeScript conventions (snake_case → camelCase).\n */\n\n/**\n * Severity levels matching Rust groq-lint\n * Rust: High, Medium, Low → TS: error, warning, info\n */\nexport type WasmSeverity = 'high' | 'medium' | 'low'\n\n/**\n * Map WASM severity to our standard severity\n */\nexport function mapSeverity(wasmSeverity: WasmSeverity): 'error' | 'warning' | 'info' {\n switch (wasmSeverity) {\n case 'high':\n return 'error'\n case 'medium':\n return 'warning'\n case 'low':\n return 'info'\n }\n}\n\n/**\n * A finding from the Rust linter (JSON format from WASM)\n */\nexport interface WasmFinding {\n /** Rule ID (snake_case from Rust) */\n ruleId: string\n /** Human-readable message */\n message: string\n /** Severity level */\n severity: WasmSeverity\n /** Start byte offset (0-based) */\n start: number\n /** End byte offset (0-based) */\n end: number\n}\n\n/**\n * Configuration for linting\n */\nexport interface WasmLintConfig {\n /** Rules to enable/disable (rule_id → enabled) */\n rules?: Record<string, boolean>\n}\n\n/**\n * Configuration for formatting\n */\nexport interface WasmFormatConfig {\n /** Maximum line width (default: 80) */\n width?: number\n}\n\n/**\n * Error from WASM operations\n */\nexport class WasmError extends Error {\n constructor(\n message: string,\n public readonly code: 'NOT_INITIALIZED' | 'PARSE_ERROR' | 'WASM_ERROR'\n ) {\n super(message)\n this.name = 'WasmError'\n }\n}\n\n/**\n * Rule ID mapping from Rust (snake_case) to TS (kebab-case)\n */\nexport const RULE_ID_MAP: Record<string, string> = {\n join_in_filter: 'join-in-filter',\n join_to_get_id: 'join-to-get-id',\n computed_value_in_filter: 'computed-value-in-filter',\n match_on_id: 'match-on-id',\n order_on_expr: 'order-on-expr',\n deep_pagination: 'deep-pagination',\n large_pages: 'large-pages',\n non_literal_comparison: 'non-literal-comparison',\n repeated_dereference: 'repeated-dereference',\n count_in_correlated_subquery: 'count-in-correlated-subquery',\n very_large_query: 'very-large-query',\n extremely_large_query: 'extremely-large-query',\n many_joins: 'many-joins',\n}\n\n/**\n * Convert Rust rule ID to TS convention\n */\nexport function mapRuleId(rustRuleId: string): string {\n return RULE_ID_MAP[rustRuleId] ?? rustRuleId.replace(/_/g, '-')\n}\n","/**\n * WASM Module Loader\n *\n * Handles loading and initializing the WASM modules for groq-lint and groq-format.\n * Currently supports Node.js environments.\n */\n\nimport { WasmError } from './types.js'\n\n// WASM module state\nlet initialized = false\nlet initPromise: Promise<void> | null = null\n\n// WASM module functions (set after initialization)\nlet wasmLint: ((query: string) => string) | null = null\nlet wasmFormat: ((query: string, width?: number | null) => string) | null = null\n\n/**\n * Check if WASM modules are initialized\n */\nexport function isInitialized(): boolean {\n return initialized\n}\n\n/**\n * Initialize WASM modules\n *\n * Call this once at application startup. Safe to call multiple times.\n *\n * @example\n * ```typescript\n * import { initWasm } from '@sanity-labs/groq-wasm'\n *\n * await initWasm()\n * // Now lint() and format() are ready to use\n * ```\n */\nexport async function initWasm(): Promise<void> {\n if (initialized) {\n return\n }\n\n if (initPromise) {\n return initPromise\n }\n\n initPromise = doInit()\n await initPromise\n}\n\nasync function doInit(): Promise<void> {\n try {\n // Dynamic import for the CommonJS WASM module\n // The wasm-pack nodejs target generates CJS with synchronous WASM loading\n const { createRequire } = await import('node:module')\n const { fileURLToPath } = await import('node:url')\n const { dirname, join } = await import('node:path')\n\n // Create a require function that can load CJS modules\n const currentDir = dirname(fileURLToPath(import.meta.url))\n const require = createRequire(import.meta.url)\n\n // Load the WASM module - it will synchronously initialize\n // Use .cjs extension since wasm-pack generates CJS and our package uses \"type\": \"module\"\n const wasmPath = join(currentDir, '..', 'wasm', 'groq_wasm.cjs')\n const wasm = require(wasmPath)\n\n // Store the functions\n wasmLint = wasm.lint\n wasmFormat = wasm.format\n\n initialized = true\n } catch (error) {\n initPromise = null\n throw new WasmError(\n `Failed to initialize WASM: ${error instanceof Error ? error.message : String(error)}`,\n 'WASM_ERROR'\n )\n }\n}\n\n/**\n * Call the WASM lint function\n * @throws {WasmError} If not initialized\n */\nexport function callLint(query: string): string {\n if (!initialized || !wasmLint) {\n throw new WasmError('WASM not initialized. Call initWasm() first.', 'NOT_INITIALIZED')\n }\n return wasmLint(query)\n}\n\n/**\n * Call the WASM format function\n * @throws {WasmError} If not initialized\n */\nexport function callFormat(query: string, width?: number): string {\n if (!initialized || !wasmFormat) {\n throw new WasmError('WASM not initialized. Call initWasm() first.', 'NOT_INITIALIZED')\n }\n return wasmFormat(query, width ?? null)\n}\n","/**\n * GROQ Linting via WASM\n *\n * Wraps the Rust groq-lint library compiled to WASM.\n */\n\nimport type { Finding, SourceLocation, SourceSpan } from '@sanity-labs/lint-core'\nimport {\n mapRuleId,\n mapSeverity,\n WasmError,\n type WasmFinding,\n type WasmLintConfig,\n} from './types.js'\nimport { callLint, isInitialized } from './wasm-loader.js'\n\n/**\n * Lint a GROQ query using the WASM-based linter\n *\n * @param query - The GROQ query string to lint\n * @param config - Optional configuration\n * @returns Array of findings\n * @throws {WasmError} If WASM is not initialized or query parsing fails\n *\n * @example\n * ```typescript\n * import { initWasm, lint } from '@sanity-labs/groq-wasm'\n *\n * await initWasm()\n *\n * const findings = lint('*[_type == \"post\"]{ author-> }')\n * // [{ ruleId: 'join-in-filter', message: '...', severity: 'error' }]\n * ```\n */\nexport function lint(query: string, config?: WasmLintConfig): Finding[] {\n if (!isInitialized()) {\n throw new WasmError('WASM not initialized. Call initWasm() first.', 'NOT_INITIALIZED')\n }\n\n // Handle empty query - nothing to lint\n if (!query.trim()) {\n return []\n }\n\n try {\n // Call WASM function - returns JSON string\n const resultJson = callLint(query)\n const wasmFindings: WasmFinding[] = JSON.parse(resultJson)\n\n // Filter by config if provided\n let findings = wasmFindings\n if (config?.rules) {\n const rules = config.rules\n findings = findings.filter((f) => {\n const enabled = rules[f.ruleId]\n return enabled !== false\n })\n }\n\n // Convert to our Finding type\n return findings.map((wf) => convertFinding(wf, query))\n } catch (error) {\n if (error instanceof WasmError) {\n throw error\n }\n\n // Parse errors from WASM come as thrown strings/errors\n const message = error instanceof Error ? error.message : String(error)\n\n if (message.includes('parse') || message.includes('Parse')) {\n throw new WasmError(`Failed to parse query: ${message}`, 'PARSE_ERROR')\n }\n\n throw new WasmError(`Lint failed: ${message}`, 'WASM_ERROR')\n }\n}\n\n/**\n * Async version of lint for environments that prefer promises\n */\nexport async function lintAsync(query: string, config?: WasmLintConfig): Promise<Finding[]> {\n // WASM operations are synchronous, but we provide async API\n // for consistency and future-proofing (e.g., if we add worker support)\n return lint(query, config)\n}\n\n/**\n * Convert WASM finding to our Finding type\n */\nfunction convertFinding(wf: WasmFinding, query: string): Finding {\n return {\n ruleId: mapRuleId(wf.ruleId),\n message: wf.message,\n severity: mapSeverity(wf.severity),\n span: byteSpanToSourceSpan(wf.start, wf.end, query),\n }\n}\n\n/**\n * Convert byte offsets to line/column source span\n */\nfunction byteSpanToSourceSpan(startByte: number, endByte: number, query: string): SourceSpan {\n return {\n start: byteOffsetToLocation(startByte, query),\n end: byteOffsetToLocation(endByte, query),\n }\n}\n\n/**\n * Convert byte offset to line/column location\n */\nfunction byteOffsetToLocation(offset: number, query: string): SourceLocation {\n let line = 1\n let column = 1\n let currentOffset = 0\n\n for (const char of query) {\n if (currentOffset >= offset) {\n break\n }\n\n if (char === '\\n') {\n line++\n column = 1\n } else {\n column++\n }\n\n currentOffset++\n }\n\n return { line, column, offset }\n}\n","/**\n * GROQ Formatting via WASM\n *\n * Wraps the Rust groq-format library compiled to WASM.\n */\n\nimport { WasmError, type WasmFormatConfig } from './types.js'\nimport { callFormat, isInitialized } from './wasm-loader.js'\n\n/**\n * Default line width for formatting\n * Matches Rust groq-format DEFAULT_WIDTH\n */\nexport const DEFAULT_WIDTH = 80\n\n/**\n * Format a GROQ query using the WASM-based formatter\n *\n * @param query - The GROQ query string to format\n * @param config - Optional configuration (width defaults to 80)\n * @returns Formatted query string\n * @throws {WasmError} If WASM is not initialized or query parsing fails\n *\n * @example\n * ```typescript\n * import { initWasm, format } from '@sanity-labs/groq-wasm'\n *\n * await initWasm()\n *\n * const formatted = format('*[_type==\"post\"]{title,body}')\n * // '*[_type == \"post\"]{ title, body }'\n * ```\n */\nexport function format(query: string, config?: WasmFormatConfig): string {\n if (!isInitialized()) {\n throw new WasmError('WASM not initialized. Call initWasm() first.', 'NOT_INITIALIZED')\n }\n\n const width = config?.width ?? DEFAULT_WIDTH\n\n // Handle empty query\n if (!query.trim()) {\n return query\n }\n\n try {\n return callFormat(query, width)\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n\n if (message.includes('parse') || message.includes('Parse')) {\n throw new WasmError(`Failed to parse query: ${message}`, 'PARSE_ERROR')\n }\n\n throw new WasmError(`Format failed: ${message}`, 'WASM_ERROR')\n }\n}\n\n/**\n * Async version of format for environments that prefer promises\n */\nexport async function formatAsync(query: string, config?: WasmFormatConfig): Promise<string> {\n // WASM operations are synchronous, but we provide async API\n // for consistency and future-proofing\n return format(query, config)\n}\n\n/**\n * Check if a query can be parsed (without full formatting)\n *\n * @param query - The GROQ query to validate\n * @returns true if the query is valid GROQ syntax\n */\nexport function isValidSyntax(query: string): boolean {\n try {\n format(query)\n return true\n } catch (error) {\n if (error instanceof WasmError && error.code === 'PARSE_ERROR') {\n return false\n }\n // Re-throw other errors\n throw error\n }\n}\n"],"mappings":"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","names":["require"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { Finding } from '@sanity-labs/lint-core';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Types for @sanity-labs/groq-wasm
|
|
5
|
+
*
|
|
6
|
+
* These types match the Rust API from groq-lint and groq-format,
|
|
7
|
+
* converted to TypeScript conventions (snake_case → camelCase).
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* Severity levels matching Rust groq-lint
|
|
11
|
+
* Rust: High, Medium, Low → TS: error, warning, info
|
|
12
|
+
*/
|
|
13
|
+
type WasmSeverity = 'high' | 'medium' | 'low';
|
|
14
|
+
/**
|
|
15
|
+
* Map WASM severity to our standard severity
|
|
16
|
+
*/
|
|
17
|
+
declare function mapSeverity(wasmSeverity: WasmSeverity): 'error' | 'warning' | 'info';
|
|
18
|
+
/**
|
|
19
|
+
* A finding from the Rust linter (JSON format from WASM)
|
|
20
|
+
*/
|
|
21
|
+
interface WasmFinding {
|
|
22
|
+
/** Rule ID (snake_case from Rust) */
|
|
23
|
+
ruleId: string;
|
|
24
|
+
/** Human-readable message */
|
|
25
|
+
message: string;
|
|
26
|
+
/** Severity level */
|
|
27
|
+
severity: WasmSeverity;
|
|
28
|
+
/** Start byte offset (0-based) */
|
|
29
|
+
start: number;
|
|
30
|
+
/** End byte offset (0-based) */
|
|
31
|
+
end: number;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Configuration for linting
|
|
35
|
+
*/
|
|
36
|
+
interface WasmLintConfig {
|
|
37
|
+
/** Rules to enable/disable (rule_id → enabled) */
|
|
38
|
+
rules?: Record<string, boolean>;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Configuration for formatting
|
|
42
|
+
*/
|
|
43
|
+
interface WasmFormatConfig {
|
|
44
|
+
/** Maximum line width (default: 80) */
|
|
45
|
+
width?: number;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Error from WASM operations
|
|
49
|
+
*/
|
|
50
|
+
declare class WasmError extends Error {
|
|
51
|
+
readonly code: 'NOT_INITIALIZED' | 'PARSE_ERROR' | 'WASM_ERROR';
|
|
52
|
+
constructor(message: string, code: 'NOT_INITIALIZED' | 'PARSE_ERROR' | 'WASM_ERROR');
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Rule ID mapping from Rust (snake_case) to TS (kebab-case)
|
|
56
|
+
*/
|
|
57
|
+
declare const RULE_ID_MAP: Record<string, string>;
|
|
58
|
+
/**
|
|
59
|
+
* Convert Rust rule ID to TS convention
|
|
60
|
+
*/
|
|
61
|
+
declare function mapRuleId(rustRuleId: string): string;
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* GROQ Linting via WASM
|
|
65
|
+
*
|
|
66
|
+
* Wraps the Rust groq-lint library compiled to WASM.
|
|
67
|
+
*/
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Lint a GROQ query using the WASM-based linter
|
|
71
|
+
*
|
|
72
|
+
* @param query - The GROQ query string to lint
|
|
73
|
+
* @param config - Optional configuration
|
|
74
|
+
* @returns Array of findings
|
|
75
|
+
* @throws {WasmError} If WASM is not initialized or query parsing fails
|
|
76
|
+
*
|
|
77
|
+
* @example
|
|
78
|
+
* ```typescript
|
|
79
|
+
* import { initWasm, lint } from '@sanity-labs/groq-wasm'
|
|
80
|
+
*
|
|
81
|
+
* await initWasm()
|
|
82
|
+
*
|
|
83
|
+
* const findings = lint('*[_type == "post"]{ author-> }')
|
|
84
|
+
* // [{ ruleId: 'join-in-filter', message: '...', severity: 'error' }]
|
|
85
|
+
* ```
|
|
86
|
+
*/
|
|
87
|
+
declare function lint(query: string, config?: WasmLintConfig): Finding[];
|
|
88
|
+
/**
|
|
89
|
+
* Async version of lint for environments that prefer promises
|
|
90
|
+
*/
|
|
91
|
+
declare function lintAsync(query: string, config?: WasmLintConfig): Promise<Finding[]>;
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* GROQ Formatting via WASM
|
|
95
|
+
*
|
|
96
|
+
* Wraps the Rust groq-format library compiled to WASM.
|
|
97
|
+
*/
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Default line width for formatting
|
|
101
|
+
* Matches Rust groq-format DEFAULT_WIDTH
|
|
102
|
+
*/
|
|
103
|
+
declare const DEFAULT_WIDTH = 80;
|
|
104
|
+
/**
|
|
105
|
+
* Format a GROQ query using the WASM-based formatter
|
|
106
|
+
*
|
|
107
|
+
* @param query - The GROQ query string to format
|
|
108
|
+
* @param config - Optional configuration (width defaults to 80)
|
|
109
|
+
* @returns Formatted query string
|
|
110
|
+
* @throws {WasmError} If WASM is not initialized or query parsing fails
|
|
111
|
+
*
|
|
112
|
+
* @example
|
|
113
|
+
* ```typescript
|
|
114
|
+
* import { initWasm, format } from '@sanity-labs/groq-wasm'
|
|
115
|
+
*
|
|
116
|
+
* await initWasm()
|
|
117
|
+
*
|
|
118
|
+
* const formatted = format('*[_type=="post"]{title,body}')
|
|
119
|
+
* // '*[_type == "post"]{ title, body }'
|
|
120
|
+
* ```
|
|
121
|
+
*/
|
|
122
|
+
declare function format(query: string, config?: WasmFormatConfig): string;
|
|
123
|
+
/**
|
|
124
|
+
* Async version of format for environments that prefer promises
|
|
125
|
+
*/
|
|
126
|
+
declare function formatAsync(query: string, config?: WasmFormatConfig): Promise<string>;
|
|
127
|
+
/**
|
|
128
|
+
* Check if a query can be parsed (without full formatting)
|
|
129
|
+
*
|
|
130
|
+
* @param query - The GROQ query to validate
|
|
131
|
+
* @returns true if the query is valid GROQ syntax
|
|
132
|
+
*/
|
|
133
|
+
declare function isValidSyntax(query: string): boolean;
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* WASM Module Loader
|
|
137
|
+
*
|
|
138
|
+
* Handles loading and initializing the WASM modules for groq-lint and groq-format.
|
|
139
|
+
* Currently supports Node.js environments.
|
|
140
|
+
*/
|
|
141
|
+
/**
|
|
142
|
+
* Check if WASM modules are initialized
|
|
143
|
+
*/
|
|
144
|
+
declare function isInitialized(): boolean;
|
|
145
|
+
/**
|
|
146
|
+
* Initialize WASM modules
|
|
147
|
+
*
|
|
148
|
+
* Call this once at application startup. Safe to call multiple times.
|
|
149
|
+
*
|
|
150
|
+
* @example
|
|
151
|
+
* ```typescript
|
|
152
|
+
* import { initWasm } from '@sanity-labs/groq-wasm'
|
|
153
|
+
*
|
|
154
|
+
* await initWasm()
|
|
155
|
+
* // Now lint() and format() are ready to use
|
|
156
|
+
* ```
|
|
157
|
+
*/
|
|
158
|
+
declare function initWasm(): Promise<void>;
|
|
159
|
+
|
|
160
|
+
export { DEFAULT_WIDTH, RULE_ID_MAP, WasmError, type WasmFinding, type WasmFormatConfig, type WasmLintConfig, type WasmSeverity, format, formatAsync, initWasm, isInitialized, isValidSyntax, lint, lintAsync, mapRuleId, mapSeverity };
|