@sanity-labs/groq-wasm 1.0.3 → 1.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/README.md +88 -24
- package/dist/{chunk-FE2VTKLP.js → chunk-XXDG7JJH.js} +182 -22
- package/dist/chunk-XXDG7JJH.js.map +1 -0
- package/dist/index.browser.d.ts +171 -5
- package/dist/index.browser.js +7 -3
- package/dist/index.browser.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +7 -3
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/wasm/groq_wasm.d.ts +25 -0
- package/wasm/groq_wasm.js +59 -0
- package/wasm/groq_wasm_bg.wasm +0 -0
- package/wasm/groq_wasm_bg.wasm.d.ts +2 -0
- package/dist/chunk-FE2VTKLP.js.map +0 -1
package/README.md
CHANGED
|
@@ -18,10 +18,9 @@ npm install @sanity-labs/groq-wasm
|
|
|
18
18
|
## Usage
|
|
19
19
|
|
|
20
20
|
```typescript
|
|
21
|
-
import {
|
|
21
|
+
import { lint, format, validate } from '@sanity-labs/groq-wasm'
|
|
22
22
|
|
|
23
|
-
//
|
|
24
|
-
await initWasm()
|
|
23
|
+
// WASM loads when the module is imported. lint, format, and validate are sync.
|
|
25
24
|
|
|
26
25
|
// Lint a query
|
|
27
26
|
const findings = lint('*[_type == "post"]{ author-> }')
|
|
@@ -32,20 +31,19 @@ console.log(findings)
|
|
|
32
31
|
const formatted = format('*[_type=="post"]{title,body}')
|
|
33
32
|
console.log(formatted)
|
|
34
33
|
// '*[_type == "post"]{ title, body }'
|
|
34
|
+
|
|
35
|
+
// Validate syntax without linting or formatting
|
|
36
|
+
const result = validate('*["é" == ]')
|
|
37
|
+
if (!result.ok) {
|
|
38
|
+
const { message, start, end } = result.error
|
|
39
|
+
// start/end are UTF-16 indices: query.slice(start, end) === ']'
|
|
40
|
+
console.log(message, start, end)
|
|
41
|
+
}
|
|
35
42
|
```
|
|
36
43
|
|
|
37
44
|
## API
|
|
38
45
|
|
|
39
|
-
|
|
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.
|
|
46
|
+
Importing the package loads the WASM module. `lint()`, `format()`, and `validate()` are synchronous after that import resolves.
|
|
49
47
|
|
|
50
48
|
### Linting
|
|
51
49
|
|
|
@@ -59,10 +57,6 @@ interface WasmLintConfig {
|
|
|
59
57
|
}
|
|
60
58
|
```
|
|
61
59
|
|
|
62
|
-
#### `lintAsync(query: string, config?: WasmLintConfig): Promise<Finding[]>`
|
|
63
|
-
|
|
64
|
-
Async version of `lint()`.
|
|
65
|
-
|
|
66
60
|
### Formatting
|
|
67
61
|
|
|
68
62
|
#### `format(query: string, config?: WasmFormatConfig): string`
|
|
@@ -75,13 +69,43 @@ interface WasmFormatConfig {
|
|
|
75
69
|
}
|
|
76
70
|
```
|
|
77
71
|
|
|
78
|
-
#### `
|
|
72
|
+
#### `isValidSyntax(query: string): boolean`
|
|
79
73
|
|
|
80
|
-
|
|
74
|
+
Check if a query has valid GROQ syntax by attempting to format it. An empty query is treated as valid. For a structured parse error, use `validate()`.
|
|
81
75
|
|
|
82
|
-
|
|
76
|
+
### Validation
|
|
77
|
+
|
|
78
|
+
#### `validate(query: string): ValidateResult`
|
|
79
|
+
|
|
80
|
+
Parse a GROQ query with groq-parser and return a result value. Syntax errors are not thrown.
|
|
81
|
+
|
|
82
|
+
```typescript
|
|
83
|
+
type ValidateResult = { ok: true } | { ok: false; error: ValidateError }
|
|
84
|
+
|
|
85
|
+
interface ValidateError {
|
|
86
|
+
message: string
|
|
87
|
+
/** Inclusive 0-based index into the JavaScript string (UTF-16 code units). */
|
|
88
|
+
start: number
|
|
89
|
+
/** Exclusive 0-based index into the JavaScript string (UTF-16 code units). */
|
|
90
|
+
end: number
|
|
91
|
+
/** 1-based line of `start`. */
|
|
92
|
+
line: number
|
|
93
|
+
/** 1-based column of `start`, counted in UTF-16 code units. */
|
|
94
|
+
column: number
|
|
95
|
+
/** 1-based line of `end`. */
|
|
96
|
+
endLine: number
|
|
97
|
+
/** 1-based column of `end`, counted in UTF-16 code units. */
|
|
98
|
+
endColumn: number
|
|
99
|
+
}
|
|
100
|
+
```
|
|
83
101
|
|
|
84
|
-
|
|
102
|
+
groq-parser reports UTF-8 byte offsets (`ParseError` positions). `validate` converts `start` and `end` to UTF-16 code unit indices so they match JavaScript string indexing (`query.slice(start, end)`) and editors such as Sanity Vision. Lines and columns are 1-based, and columns count UTF-16 code units, the same convention as `line` / `column` on lint finding locations.
|
|
103
|
+
|
|
104
|
+
`start === end` means the parser reported a caret on a boundary rather than a token span. An empty or whitespace-only query fails with message `"no query"` at offset 0. That differs from `lint('')` (no findings), `format('')` (returns the input), and `isValidSyntax('')` (returns `true`).
|
|
105
|
+
|
|
106
|
+
`$parameter` references are syntactically valid. `validate` does not check that parameters were declared.
|
|
107
|
+
|
|
108
|
+
`lint` and `format` are unchanged: invalid syntax still throws `WasmError` with code `PARSE_ERROR`.
|
|
85
109
|
|
|
86
110
|
### Constants
|
|
87
111
|
|
|
@@ -93,6 +117,44 @@ Default line width for formatting (80).
|
|
|
93
117
|
|
|
94
118
|
Mapping from Rust rule IDs (snake_case) to TS convention (kebab-case).
|
|
95
119
|
|
|
120
|
+
### Parameters
|
|
121
|
+
|
|
122
|
+
#### `extractParams(query: string): QueryParam[]`
|
|
123
|
+
|
|
124
|
+
List the `$parameters` a query references, using groq-parser. Returns one entry per distinct name (without the `$`) in order of first reference, each with every reference's span.
|
|
125
|
+
|
|
126
|
+
```typescript
|
|
127
|
+
import { extractParams } from '@sanity-labs/groq-wasm'
|
|
128
|
+
|
|
129
|
+
const query = '*[_type == $type][0...$limit]{ "same": $type }'
|
|
130
|
+
const params = extractParams(query)
|
|
131
|
+
params.map((param) => param.name)
|
|
132
|
+
// ['type', 'limit']
|
|
133
|
+
params[0].references.map(({ start, end }) => query.slice(start, end))
|
|
134
|
+
// ['$type', '$type']
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
```typescript
|
|
138
|
+
interface QueryParam {
|
|
139
|
+
name: string // Without the `$`
|
|
140
|
+
references: ParamReference[] // Source order, never empty
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
interface ParamReference {
|
|
144
|
+
start: number // Inclusive index of the `$` (UTF-16 code units)
|
|
145
|
+
end: number // Exclusive index (UTF-16 code units)
|
|
146
|
+
line: number // 1-based line of `start`
|
|
147
|
+
column: number // 1-based column of `start` (UTF-16 code units)
|
|
148
|
+
endLine: number
|
|
149
|
+
endColumn: number
|
|
150
|
+
}
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
- Parameters are found in filters, projections, slices, element indexes, function arguments and nested subqueries.
|
|
154
|
+
- `$name` text inside strings and comments is not a reference.
|
|
155
|
+
- Parameters bound by a custom function (`fn ns::f($p) = ...`) are not reported from inside that function's body.
|
|
156
|
+
- An empty or whitespace-only query returns `[]`. Invalid syntax throws `WasmError` with code `PARSE_ERROR`, like `lint()` and `format()`.
|
|
157
|
+
|
|
96
158
|
## Lint Rules
|
|
97
159
|
|
|
98
160
|
The following rules are available (from Rust groq-lint):
|
|
@@ -142,11 +204,11 @@ try {
|
|
|
142
204
|
This package works in modern browsers that support WebAssembly. The WASM modules are loaded automatically based on the environment.
|
|
143
205
|
|
|
144
206
|
```typescript
|
|
145
|
-
// In browser
|
|
146
|
-
import {
|
|
207
|
+
// In browser. The WASM module is fetched and initialized on import.
|
|
208
|
+
import { lint, validate } from '@sanity-labs/groq-wasm'
|
|
147
209
|
|
|
148
|
-
await initWasm()
|
|
149
210
|
const findings = lint(query)
|
|
211
|
+
const parsed = validate(query)
|
|
150
212
|
```
|
|
151
213
|
|
|
152
214
|
## Architecture
|
|
@@ -161,8 +223,10 @@ packages/groq-wasm/
|
|
|
161
223
|
├── wasm/ # Built WASM output (generated)
|
|
162
224
|
├── src/ # TypeScript wrappers
|
|
163
225
|
│ ├── index.ts # Main exports
|
|
226
|
+
│ ├── params.ts # Parameter extraction API
|
|
164
227
|
│ ├── lint.ts # Linting API
|
|
165
228
|
│ ├── format.ts # Formatting API
|
|
229
|
+
│ ├── validate.ts # Syntax validation API
|
|
166
230
|
│ └── wasm-loader.ts # WASM initialization
|
|
167
231
|
└── scripts/
|
|
168
232
|
└── build-wasm.sh # Build script
|
|
@@ -37,6 +37,27 @@ function mapRuleId(rustRuleId) {
|
|
|
37
37
|
}
|
|
38
38
|
|
|
39
39
|
// wasm/groq_wasm.js
|
|
40
|
+
function extractParams(query) {
|
|
41
|
+
let deferred3_0;
|
|
42
|
+
let deferred3_1;
|
|
43
|
+
try {
|
|
44
|
+
const ptr0 = passStringToWasm0(query, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
|
45
|
+
const len0 = WASM_VECTOR_LEN;
|
|
46
|
+
const ret = wasm.extractParams(ptr0, len0);
|
|
47
|
+
var ptr2 = ret[0];
|
|
48
|
+
var len2 = ret[1];
|
|
49
|
+
if (ret[3]) {
|
|
50
|
+
ptr2 = 0;
|
|
51
|
+
len2 = 0;
|
|
52
|
+
throw takeFromExternrefTable0(ret[2]);
|
|
53
|
+
}
|
|
54
|
+
deferred3_0 = ptr2;
|
|
55
|
+
deferred3_1 = len2;
|
|
56
|
+
return getStringFromWasm0(ptr2, len2);
|
|
57
|
+
} finally {
|
|
58
|
+
wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
40
61
|
function format(query, width) {
|
|
41
62
|
let deferred3_0;
|
|
42
63
|
let deferred3_1;
|
|
@@ -79,6 +100,20 @@ function lint(query) {
|
|
|
79
100
|
wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);
|
|
80
101
|
}
|
|
81
102
|
}
|
|
103
|
+
function validate(query) {
|
|
104
|
+
let deferred2_0;
|
|
105
|
+
let deferred2_1;
|
|
106
|
+
try {
|
|
107
|
+
const ptr0 = passStringToWasm0(query, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
|
108
|
+
const len0 = WASM_VECTOR_LEN;
|
|
109
|
+
const ret = wasm.validate(ptr0, len0);
|
|
110
|
+
deferred2_0 = ret[0];
|
|
111
|
+
deferred2_1 = ret[1];
|
|
112
|
+
return getStringFromWasm0(ret[0], ret[1]);
|
|
113
|
+
} finally {
|
|
114
|
+
wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
82
117
|
function __wbg_get_imports() {
|
|
83
118
|
const import0 = {
|
|
84
119
|
__proto__: null,
|
|
@@ -246,9 +281,92 @@ function initWasm(bytes) {
|
|
|
246
281
|
function callLint(query) {
|
|
247
282
|
return lint(query);
|
|
248
283
|
}
|
|
284
|
+
function callExtractParams(query) {
|
|
285
|
+
return extractParams(query);
|
|
286
|
+
}
|
|
249
287
|
function callFormat(query, width) {
|
|
250
288
|
return format(query, width ?? null);
|
|
251
289
|
}
|
|
290
|
+
function callValidate(query) {
|
|
291
|
+
return validate(query);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// src/offsets.ts
|
|
295
|
+
function createUtf8OffsetMapper(text) {
|
|
296
|
+
let index = 0;
|
|
297
|
+
let bytes = 0;
|
|
298
|
+
let line = 1;
|
|
299
|
+
let column = 1;
|
|
300
|
+
return (byteOffset) => {
|
|
301
|
+
if (byteOffset < bytes) {
|
|
302
|
+
index = 0;
|
|
303
|
+
bytes = 0;
|
|
304
|
+
line = 1;
|
|
305
|
+
column = 1;
|
|
306
|
+
}
|
|
307
|
+
while (index < text.length && bytes < byteOffset) {
|
|
308
|
+
const codePoint = text.codePointAt(index) ?? 0;
|
|
309
|
+
const byteWidth = utf8ByteLength(codePoint);
|
|
310
|
+
if (bytes + byteWidth > byteOffset) {
|
|
311
|
+
break;
|
|
312
|
+
}
|
|
313
|
+
const utf16Width = codePoint > 65535 ? 2 : 1;
|
|
314
|
+
bytes += byteWidth;
|
|
315
|
+
index += utf16Width;
|
|
316
|
+
if (codePoint === 10) {
|
|
317
|
+
line += 1;
|
|
318
|
+
column = 1;
|
|
319
|
+
} else {
|
|
320
|
+
column += utf16Width;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
return { index, line, column };
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
function utf8ByteLength(codePoint) {
|
|
327
|
+
if (codePoint <= 127) return 1;
|
|
328
|
+
if (codePoint <= 2047) return 2;
|
|
329
|
+
if (codePoint <= 65535) return 3;
|
|
330
|
+
return 4;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// src/params.ts
|
|
334
|
+
function extractParams2(query) {
|
|
335
|
+
if (!query.trim()) {
|
|
336
|
+
return [];
|
|
337
|
+
}
|
|
338
|
+
let resultJson;
|
|
339
|
+
try {
|
|
340
|
+
resultJson = callExtractParams(query);
|
|
341
|
+
} catch (error) {
|
|
342
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
343
|
+
if (message.includes("parse") || message.includes("Parse")) {
|
|
344
|
+
throw new WasmError(`Failed to parse query: ${message}`, "PARSE_ERROR");
|
|
345
|
+
}
|
|
346
|
+
throw new WasmError(`Extract params failed: ${message}`, "WASM_ERROR");
|
|
347
|
+
}
|
|
348
|
+
const wasmReferences = JSON.parse(resultJson);
|
|
349
|
+
const toPosition = createUtf8OffsetMapper(query);
|
|
350
|
+
const params = /* @__PURE__ */ new Map();
|
|
351
|
+
for (const reference of wasmReferences) {
|
|
352
|
+
const start = toPosition(reference.start);
|
|
353
|
+
const end = toPosition(reference.end);
|
|
354
|
+
let param = params.get(reference.name);
|
|
355
|
+
if (!param) {
|
|
356
|
+
param = { name: reference.name, references: [] };
|
|
357
|
+
params.set(reference.name, param);
|
|
358
|
+
}
|
|
359
|
+
param.references.push({
|
|
360
|
+
start: start.index,
|
|
361
|
+
end: end.index,
|
|
362
|
+
line: start.line,
|
|
363
|
+
column: start.column,
|
|
364
|
+
endLine: end.line,
|
|
365
|
+
endColumn: end.column
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
return [...params.values()];
|
|
369
|
+
}
|
|
252
370
|
|
|
253
371
|
// src/lint.ts
|
|
254
372
|
function lint2(query, config) {
|
|
@@ -287,29 +405,14 @@ function convertFinding(wf, query) {
|
|
|
287
405
|
};
|
|
288
406
|
}
|
|
289
407
|
function byteSpanToSourceSpan(startByte, endByte, query) {
|
|
408
|
+
const toPosition = createUtf8OffsetMapper(query);
|
|
409
|
+
const start = toPosition(startByte);
|
|
410
|
+
const end = toPosition(endByte);
|
|
290
411
|
return {
|
|
291
|
-
start:
|
|
292
|
-
end:
|
|
412
|
+
start: { line: start.line, column: start.column, offset: start.index },
|
|
413
|
+
end: { line: end.line, column: end.column, offset: end.index }
|
|
293
414
|
};
|
|
294
415
|
}
|
|
295
|
-
function byteOffsetToLocation(offset, query) {
|
|
296
|
-
let line = 1;
|
|
297
|
-
let column = 1;
|
|
298
|
-
let currentOffset = 0;
|
|
299
|
-
for (const char of query) {
|
|
300
|
-
if (currentOffset >= offset) {
|
|
301
|
-
break;
|
|
302
|
-
}
|
|
303
|
-
if (char === "\n") {
|
|
304
|
-
line++;
|
|
305
|
-
column = 1;
|
|
306
|
-
} else {
|
|
307
|
-
column++;
|
|
308
|
-
}
|
|
309
|
-
currentOffset++;
|
|
310
|
-
}
|
|
311
|
-
return { line, column, offset };
|
|
312
|
-
}
|
|
313
416
|
|
|
314
417
|
// src/format.ts
|
|
315
418
|
var DEFAULT_WIDTH = 80;
|
|
@@ -340,15 +443,72 @@ function isValidSyntax(query) {
|
|
|
340
443
|
}
|
|
341
444
|
}
|
|
342
445
|
|
|
446
|
+
// src/validate.ts
|
|
447
|
+
function validate2(query) {
|
|
448
|
+
let parsed;
|
|
449
|
+
try {
|
|
450
|
+
parsed = JSON.parse(callValidate(query));
|
|
451
|
+
} catch (error) {
|
|
452
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
453
|
+
throw new WasmError(`Validate failed: ${message}`, "WASM_ERROR");
|
|
454
|
+
}
|
|
455
|
+
const payload = readValidatePayload(parsed);
|
|
456
|
+
switch (payload.ok) {
|
|
457
|
+
case true:
|
|
458
|
+
return { ok: true };
|
|
459
|
+
case false:
|
|
460
|
+
return { ok: false, error: toValidateError(query, payload) };
|
|
461
|
+
default: {
|
|
462
|
+
const unexpected = payload;
|
|
463
|
+
throw new WasmError(`Unexpected validate result: ${JSON.stringify(unexpected)}`, "WASM_ERROR");
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
function readValidatePayload(value) {
|
|
468
|
+
if (!isRecord(value)) {
|
|
469
|
+
throw new WasmError("Validate returned an invalid payload", "WASM_ERROR");
|
|
470
|
+
}
|
|
471
|
+
const ok = value["ok"];
|
|
472
|
+
if (ok === true) {
|
|
473
|
+
return { ok: true };
|
|
474
|
+
}
|
|
475
|
+
const message = value["message"];
|
|
476
|
+
const start = value["start"];
|
|
477
|
+
const end = value["end"];
|
|
478
|
+
if (ok === false && typeof message === "string" && typeof start === "number" && typeof end === "number") {
|
|
479
|
+
return { ok: false, message, start, end };
|
|
480
|
+
}
|
|
481
|
+
throw new WasmError("Validate returned an invalid payload", "WASM_ERROR");
|
|
482
|
+
}
|
|
483
|
+
function toValidateError(query, failure) {
|
|
484
|
+
const toPosition = createUtf8OffsetMapper(query);
|
|
485
|
+
const start = toPosition(Math.max(0, failure.start));
|
|
486
|
+
const end = toPosition(Math.max(failure.start, failure.end));
|
|
487
|
+
return {
|
|
488
|
+
message: failure.message,
|
|
489
|
+
start: start.index,
|
|
490
|
+
end: end.index,
|
|
491
|
+
line: start.line,
|
|
492
|
+
column: start.column,
|
|
493
|
+
endLine: end.line,
|
|
494
|
+
endColumn: end.column
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
function isRecord(value) {
|
|
498
|
+
return typeof value === "object" && value !== null;
|
|
499
|
+
}
|
|
500
|
+
|
|
343
501
|
export {
|
|
344
502
|
mapSeverity,
|
|
345
503
|
WasmError,
|
|
346
504
|
RULE_ID_MAP,
|
|
347
505
|
mapRuleId,
|
|
348
506
|
initWasm,
|
|
507
|
+
extractParams2 as extractParams,
|
|
349
508
|
lint2 as lint,
|
|
350
509
|
DEFAULT_WIDTH,
|
|
351
510
|
format2 as format,
|
|
352
|
-
isValidSyntax
|
|
511
|
+
isValidSyntax,
|
|
512
|
+
validate2 as validate
|
|
353
513
|
};
|
|
354
|
-
//# sourceMappingURL=chunk-
|
|
514
|
+
//# sourceMappingURL=chunk-XXDG7JJH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../wasm/groq_wasm.js","../src/wasm-loader.ts","../src/offsets.ts","../src/params.ts","../src/lint.ts","../src/format.ts","../src/validate.ts"],"sourcesContent":["/**\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 offset into the UTF-8 encoding of the query (0-based) */\n start: number\n /** End offset into the UTF-8 encoding of the query (0-based, exclusive) */\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 * A parameter reference from the Rust parser (JSON format from WASM)\n */\nexport interface WasmParamReference {\n /** Parameter name without the `$` */\n name: string\n /** Start byte offset of the `$` (0-based, UTF-8) */\n start: number\n /** End byte offset, exclusive (0-based, UTF-8) */\n end: number\n}\n\n/**\n * One `$name` reference in a query, from {@link extractParams}.\n *\n * `start` and `end` are indices into the JavaScript query string (UTF-16 code\n * units), not UTF-8 byte offsets. `start` is inclusive and `end` is exclusive,\n * so `query.slice(start, end)` is `\"$name\"`. Lines and columns are 1-based,\n * and columns count UTF-16 code units, matching `SourceLocation` on lint\n * findings.\n */\nexport interface ParamReference {\n /** Inclusive start index of the `$`, 0-based UTF-16 code units. */\n start: number\n /** Exclusive end index, 0-based UTF-16 code units. */\n end: number\n /** 1-based line number of `start`. */\n line: number\n /** 1-based column of `start`, counted in UTF-16 code units. */\n column: number\n /** 1-based line number of `end`. */\n endLine: number\n /** 1-based column of `end`, counted in UTF-16 code units. */\n endColumn: number\n}\n\n/**\n * A query parameter referenced by a GROQ query, from {@link extractParams}.\n */\nexport interface QueryParam {\n /** Parameter name without the `$`, e.g. `\"type\"` for `$type`. */\n name: string\n /** Every reference to this parameter, in source order. Never empty. */\n references: ParamReference[]\n}\n\n/**\n * Error from WASM operations\n */\nexport class WasmError extends Error {\n constructor(\n message: string,\n public readonly code: '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 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 unlimited_query: 'unlimited-query',\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/**\n * A GROQ syntax error from `validate`.\n *\n * `start` and `end` are indices into the JavaScript query string (UTF-16 code\n * units), not UTF-8 byte offsets. `start` is inclusive and `end` is exclusive,\n * so `query.slice(start, end)` is the reported span. groq-parser reports UTF-8\n * byte offsets; `validate` converts them. A zero-width span (`start === end`)\n * is a caret on a token boundary.\n *\n * `line` / `column` locate `start`, and `endLine` / `endColumn` locate `end`.\n * Lines and columns are 1-based. Columns count UTF-16 code units, matching\n * `SourceLocation` on lint findings.\n */\nexport interface ValidateError {\n /** Parser message, without a serialized position suffix. */\n message: string\n /** Inclusive start index, 0-based UTF-16 code units. */\n start: number\n /** Exclusive end index, 0-based UTF-16 code units. */\n end: number\n /** 1-based line number of `start`. */\n line: number\n /** 1-based column of `start`, counted in UTF-16 code units. */\n column: number\n /** 1-based line number of `end`. */\n endLine: number\n /** 1-based column of `end`, counted in UTF-16 code units. */\n endColumn: number\n}\n\n/**\n * Result of {@link validate}.\n *\n * Syntax errors are values, not thrown exceptions. `lint` and `format` still\n * throw {@link WasmError} when a query does not parse.\n */\nexport type ValidateResult = { ok: true } | { ok: false; error: ValidateError }\n","/* @ts-self-types=\"./groq_wasm.d.ts\" */\n\n/**\n * List every query parameter a GROQ query references, as JSON.\n *\n * Returns one entry per reference, ordered by `start`. Byte offsets are\n * UTF-8 offsets into `query`; the JavaScript wrapper converts them to UTF-16\n * code unit indices. Parameters bound by a custom function (`fn ns::f($p)`)\n * are omitted inside that function's body.\n * @param {string} query\n * @returns {string}\n */\nexport function extractParams(query) {\n let deferred3_0;\n let deferred3_1;\n try {\n const ptr0 = passStringToWasm0(query, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.extractParams(ptr0, len0);\n var ptr2 = ret[0];\n var len2 = ret[1];\n if (ret[3]) {\n ptr2 = 0; len2 = 0;\n throw takeFromExternrefTable0(ret[2]);\n }\n deferred3_0 = ptr2;\n deferred3_1 = len2;\n return getStringFromWasm0(ptr2, len2);\n } finally {\n wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);\n }\n}\n\n/**\n * Format a GROQ query.\n *\n * # Arguments\n * * `query` - The GROQ query string to format\n * * `width` - Maximum line width (default: 80)\n *\n * # Returns\n * The formatted query string\n * @param {string} query\n * @param {number | null} [width]\n * @returns {string}\n */\nexport function format(query, width) {\n let deferred3_0;\n let deferred3_1;\n try {\n const ptr0 = passStringToWasm0(query, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.format(ptr0, len0, isLikeNone(width) ? Number.MAX_SAFE_INTEGER : (width) >>> 0);\n var ptr2 = ret[0];\n var len2 = ret[1];\n if (ret[3]) {\n ptr2 = 0; len2 = 0;\n throw takeFromExternrefTable0(ret[2]);\n }\n deferred3_0 = ptr2;\n deferred3_1 = len2;\n return getStringFromWasm0(ptr2, len2);\n } finally {\n wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);\n }\n}\n\nexport function init() {\n wasm.init();\n}\n\n/**\n * Lint a GROQ query and return findings as JSON.\n *\n * # Arguments\n * * `query` - The GROQ query string to lint\n *\n * # Returns\n * A JSON string containing an array of findings\n * @param {string} query\n * @returns {string}\n */\nexport function lint(query) {\n let deferred3_0;\n let deferred3_1;\n try {\n const ptr0 = passStringToWasm0(query, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.lint(ptr0, len0);\n var ptr2 = ret[0];\n var len2 = ret[1];\n if (ret[3]) {\n ptr2 = 0; len2 = 0;\n throw takeFromExternrefTable0(ret[2]);\n }\n deferred3_0 = ptr2;\n deferred3_1 = len2;\n return getStringFromWasm0(ptr2, len2);\n } finally {\n wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);\n }\n}\n\n/**\n * Parse a GROQ query and return a JSON validation result.\n *\n * Byte offsets in the JSON are UTF-8 offsets into `query`. The JavaScript\n * wrapper converts them to UTF-16 code unit indices.\n *\n * Success is `{\"ok\":true}`. A syntax error is\n * `{\"ok\":false,\"message\":\"...\",\"start\":N,\"end\":M}` where `start` is inclusive,\n * `end` is exclusive, and the two are equal when the parser reports a caret\n * rather than a token span.\n * @param {string} query\n * @returns {string}\n */\nexport function validate(query) {\n let deferred2_0;\n let deferred2_1;\n try {\n const ptr0 = passStringToWasm0(query, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.validate(ptr0, len0);\n deferred2_0 = ret[0];\n deferred2_1 = ret[1];\n return getStringFromWasm0(ret[0], ret[1]);\n } finally {\n wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);\n }\n}\nfunction __wbg_get_imports() {\n const import0 = {\n __proto__: null,\n __wbg_error_757e9472f8410341: function(arg0, arg1) {\n let deferred0_0;\n let deferred0_1;\n try {\n deferred0_0 = arg0;\n deferred0_1 = arg1;\n console.error(getStringFromWasm0(arg0, arg1));\n } finally {\n wasm.__wbindgen_free(deferred0_0, deferred0_1, 1);\n }\n },\n __wbg_new_227d7c05414eb861: function() {\n const ret = new Error();\n return ret;\n },\n __wbg_stack_3b0d974bbf31e44f: function(arg0, arg1) {\n const ret = arg1.stack;\n const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len1 = WASM_VECTOR_LEN;\n getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);\n getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);\n },\n __wbindgen_generic_0000000000000001: function(arg0, arg1) {\n // Cast intrinsic for `Ref(String) -> Externref`.\n const ret = getStringFromWasm0(arg0, arg1);\n return ret;\n },\n __wbindgen_init_externref_table: function() {\n const table = wasm.__wbindgen_externrefs;\n const offset = table.grow(4);\n table.set(0, undefined);\n table.set(offset + 0, undefined);\n table.set(offset + 1, null);\n table.set(offset + 2, true);\n table.set(offset + 3, false);\n },\n };\n return {\n __proto__: null,\n \"./groq_wasm_bg.js\": import0,\n };\n}\n\nlet cachedDataViewMemory0 = null;\nfunction getDataViewMemory0() {\n if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {\n cachedDataViewMemory0 = new DataView(wasm.memory.buffer);\n }\n return cachedDataViewMemory0;\n}\n\nfunction getStringFromWasm0(ptr, len) {\n return decodeText(ptr >>> 0, len);\n}\n\nlet cachedUint8ArrayMemory0 = null;\nfunction getUint8ArrayMemory0() {\n if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {\n cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);\n }\n return cachedUint8ArrayMemory0;\n}\n\nfunction isLikeNone(x) {\n return x === undefined || x === null;\n}\n\nfunction passStringToWasm0(arg, malloc, realloc) {\n if (realloc === undefined) {\n const buf = cachedTextEncoder.encode(arg);\n const ptr = malloc(buf.length, 1) >>> 0;\n getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);\n WASM_VECTOR_LEN = buf.length;\n return ptr;\n }\n\n let len = arg.length;\n let ptr = malloc(len, 1) >>> 0;\n\n const mem = getUint8ArrayMemory0();\n\n let offset = 0;\n\n for (; offset < len; offset++) {\n const code = arg.charCodeAt(offset);\n if (code > 0x7F) break;\n mem[ptr + offset] = code;\n }\n if (offset !== len) {\n if (offset !== 0) {\n arg = arg.slice(offset);\n }\n ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;\n const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);\n const ret = cachedTextEncoder.encodeInto(arg, view);\n\n offset += ret.written;\n ptr = realloc(ptr, len, offset, 1) >>> 0;\n }\n\n WASM_VECTOR_LEN = offset;\n return ptr;\n}\n\nfunction takeFromExternrefTable0(idx) {\n const value = wasm.__wbindgen_externrefs.get(idx);\n wasm.__externref_table_dealloc(idx);\n return value;\n}\n\nlet cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });\ncachedTextDecoder.decode();\nconst MAX_SAFARI_DECODE_BYTES = 2146435072;\nlet numBytesDecoded = 0;\nfunction decodeText(ptr, len) {\n numBytesDecoded += len;\n if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {\n cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });\n cachedTextDecoder.decode();\n numBytesDecoded = len;\n }\n return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));\n}\n\nconst cachedTextEncoder = new TextEncoder();\n\nif (!('encodeInto' in cachedTextEncoder)) {\n cachedTextEncoder.encodeInto = function (arg, view) {\n const buf = cachedTextEncoder.encode(arg);\n view.set(buf);\n return {\n read: arg.length,\n written: buf.length\n };\n };\n}\n\nlet WASM_VECTOR_LEN = 0;\n\nlet wasmModule, wasmInstance, wasm;\nfunction __wbg_finalize_init(instance, module) {\n wasmInstance = instance;\n wasm = instance.exports;\n wasmModule = module;\n cachedDataViewMemory0 = null;\n cachedUint8ArrayMemory0 = null;\n wasm.__wbindgen_start();\n return wasm;\n}\n\nasync function __wbg_load(module, imports) {\n if (typeof Response === 'function' && module instanceof Response) {\n if (!module.ok) {\n throw new Error(`failed to fetch Wasm: ${module.status} ${module.statusText} fetching '${module.url}'`);\n }\n\n if (typeof WebAssembly.instantiateStreaming === 'function') {\n try {\n return await WebAssembly.instantiateStreaming(module, imports);\n } catch (e) {\n const validResponse = expectedResponseType(module.type);\n\n if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {\n console.warn(\"`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n\", e);\n\n } else { throw e; }\n }\n }\n\n const bytes = await module.arrayBuffer();\n return await WebAssembly.instantiate(bytes, imports);\n } else {\n const instance = await WebAssembly.instantiate(module, imports);\n\n if (instance instanceof WebAssembly.Instance) {\n return { instance, module };\n } else {\n return instance;\n }\n }\n\n function expectedResponseType(type) {\n switch (type) {\n case 'basic': case 'cors': case 'default': return true;\n }\n return false;\n }\n}\n\nfunction initSync(module) {\n if (wasm !== undefined) return wasm;\n\n\n if (module !== undefined) {\n if (Object.getPrototypeOf(module) === Object.prototype) {\n ({module} = module)\n } else {\n console.warn('using deprecated parameters for `initSync()`; pass a single object instead')\n }\n }\n\n const imports = __wbg_get_imports();\n if (!(module instanceof WebAssembly.Module)) {\n module = new WebAssembly.Module(module);\n }\n const instance = new WebAssembly.Instance(module, imports);\n return __wbg_finalize_init(instance, module);\n}\n\nasync function __wbg_init(module_or_path) {\n if (wasm !== undefined) return wasm;\n\n\n if (module_or_path !== undefined) {\n if (Object.getPrototypeOf(module_or_path) === Object.prototype) {\n ({module_or_path} = module_or_path)\n } else {\n console.warn('using deprecated parameters for the initialization function; pass a single object instead')\n }\n }\n\n if (module_or_path === undefined) {\n module_or_path = new URL('groq_wasm_bg.wasm', import.meta.url);\n }\n const imports = __wbg_get_imports();\n\n if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {\n module_or_path = fetch(module_or_path);\n }\n\n const { instance, module } = await __wbg_load(await module_or_path, imports);\n\n return __wbg_finalize_init(instance, module);\n}\n\nexport { initSync, __wbg_init as default };\n","/**\n * WASM module runtime.\n *\n * Exposes the WASM-backed lint/format/validate calls and a synchronous init helper.\n * The actual byte loading is platform-specific and happens in the\n * environment-specific entry (`index.ts` for Node, `index.browser.ts` for\n * the browser). By the time any caller of this package can call `lint()` /\n * `format()`, the entry has already run `initWasm(bytes)`.\n */\n\nimport * as wasmModule from '../wasm/groq_wasm.js'\n\nimport { WasmError } from './types.js'\n\nexport function initWasm(bytes: ArrayBuffer | Uint8Array): void {\n try {\n wasmModule.initSync({ module: bytes })\n } catch (error) {\n throw new WasmError(\n `Failed to initialize WASM: ${error instanceof Error ? error.message : String(error)}`,\n 'WASM_ERROR'\n )\n }\n}\n\nexport function callLint(query: string): string {\n return wasmModule.lint(query)\n}\n\nexport function callExtractParams(query: string): string {\n return wasmModule.extractParams(query)\n}\n\nexport function callFormat(query: string, width?: number): string {\n return wasmModule.format(query, width ?? null)\n}\n\nexport function callValidate(query: string): string {\n return wasmModule.validate(query)\n}\n","/**\n * Conversion from groq-parser's UTF-8 byte offsets to JavaScript string\n * coordinates.\n *\n * wasm-bindgen passes the query to Rust with `TextEncoder`, so parser spans\n * are byte offsets into the query's UTF-8 encoding. JavaScript strings are\n * UTF-16, so those offsets stop matching string indices once the query\n * contains non-ASCII text.\n */\n\n/** A position in a JavaScript string. */\nexport interface TextPosition {\n /** 0-based UTF-16 code unit index. */\n index: number\n /** 1-based line. Advances on `\\n`. */\n line: number\n /** 1-based column, counted in UTF-16 code units. */\n column: number\n}\n\n/**\n * Create a function that maps UTF-8 byte offsets in `text` to\n * {@link TextPosition}s.\n *\n * The mapper resumes from the previous result, so calling it with ascending\n * offsets walks `text` once. A smaller offset restarts from the beginning.\n * An offset inside a code point resolves to the start of that code point, and\n * an offset past the end resolves to the end of `text`.\n */\nexport function createUtf8OffsetMapper(text: string): (byteOffset: number) => TextPosition {\n let index = 0\n let bytes = 0\n let line = 1\n let column = 1\n\n return (byteOffset) => {\n if (byteOffset < bytes) {\n index = 0\n bytes = 0\n line = 1\n column = 1\n }\n\n while (index < text.length && bytes < byteOffset) {\n const codePoint = text.codePointAt(index) ?? 0\n const byteWidth = utf8ByteLength(codePoint)\n if (bytes + byteWidth > byteOffset) {\n break\n }\n\n const utf16Width = codePoint > 0xffff ? 2 : 1\n bytes += byteWidth\n index += utf16Width\n\n if (codePoint === 0x0a) {\n line += 1\n column = 1\n } else {\n column += utf16Width\n }\n }\n\n return { index, line, column }\n }\n}\n\n/**\n * UTF-8 byte length of one code point, matching `TextEncoder`.\n *\n * Unpaired surrogates fall in the 3-byte range. `TextEncoder` replaces each\n * of them with U+FFFD, which is also 3 bytes.\n */\nfunction utf8ByteLength(codePoint: number): number {\n if (codePoint <= 0x7f) return 1\n if (codePoint <= 0x7ff) return 2\n if (codePoint <= 0xffff) return 3\n return 4\n}\n","/**\n * GROQ query parameter extraction via WASM.\n *\n * Wraps groq-parser's `ParseResult::referenced_params`. The parser reports\n * UTF-8 byte offsets; this module converts them to UTF-16 code unit indices.\n */\n\nimport { createUtf8OffsetMapper } from './offsets.js'\nimport { WasmError, type QueryParam, type WasmParamReference } from './types.js'\nimport { callExtractParams } from './wasm-loader.js'\n\n/**\n * List the query parameters (`$name`) a GROQ query references.\n *\n * Returns one entry per distinct name, in order of first reference. Each entry\n * lists every reference to that name in source order. Names do not include\n * the `$`, so they match the keys of the params object passed to a client.\n *\n * Parameters bound by a custom function (`fn ns::f($p) = ...`) are local to\n * that function's body and are not reported from inside it. `$name` text\n * inside string literals and comments is not a reference.\n *\n * Reference `start` / `end` are 0-based UTF-16 code unit indices into\n * `query` (`end` is exclusive), so `query.slice(start, end)` is `\"$name\"`.\n *\n * An empty or whitespace-only query returns `[]`, like `lint('')`.\n *\n * @param query - The GROQ query string\n * @returns Referenced parameters, in order of first reference\n * @throws {WasmError} With code `PARSE_ERROR` if the query does not parse\n *\n * @example\n * ```typescript\n * import {extractParams} from '@sanity-labs/groq-wasm'\n *\n * extractParams('*[_type == $type][0...$limit]').map((param) => param.name)\n * // ['type', 'limit']\n * ```\n */\nexport function extractParams(query: string): QueryParam[] {\n if (!query.trim()) {\n return []\n }\n\n let resultJson: string\n try {\n resultJson = callExtractParams(query)\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(`Extract params failed: ${message}`, 'WASM_ERROR')\n }\n\n const wasmReferences: WasmParamReference[] = JSON.parse(resultJson)\n const toPosition = createUtf8OffsetMapper(query)\n const params = new Map<string, QueryParam>()\n\n for (const reference of wasmReferences) {\n const start = toPosition(reference.start)\n const end = toPosition(reference.end)\n\n let param = params.get(reference.name)\n if (!param) {\n param = { name: reference.name, references: [] }\n params.set(reference.name, param)\n }\n\n param.references.push({\n start: start.index,\n end: end.index,\n line: start.line,\n column: start.column,\n endLine: end.line,\n endColumn: end.column,\n })\n }\n\n return [...params.values()]\n}\n","/**\n * GROQ Linting via WASM\n *\n * Wraps the Rust groq-lint library compiled to WASM.\n */\n\nimport type { Finding, SourceSpan } from '@sanity-labs/lint-core'\n\nimport { createUtf8OffsetMapper } from './offsets.js'\nimport {\n mapRuleId,\n mapSeverity,\n WasmError,\n type WasmFinding,\n type WasmLintConfig,\n} from './types.js'\nimport { callLint } from './wasm-loader.js'\n\n/**\n * Lint a GROQ query using the WASM-based linter.\n *\n * Finding spans are source locations in JavaScript string coordinates.\n * The Rust linter reports UTF-8 byte offsets; `line`, `column`, and `offset`\n * below are converted from those bytes. `column` counts UTF-16 code units.\n *\n * @param query - The GROQ query string to lint\n * @param config - Optional configuration\n * @returns Array of findings\n * @throws {WasmError} If query parsing fails\n *\n * @example\n * ```typescript\n * import {lint} from '@sanity-labs/groq-wasm'\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 (!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 * 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 UTF-8 byte offsets to a line/column source span.\n *\n * `column` is a 1-based count of UTF-16 code units and `offset` is the\n * matching JavaScript string index. See {@link createUtf8OffsetMapper}.\n */\nfunction byteSpanToSourceSpan(startByte: number, endByte: number, query: string): SourceSpan {\n const toPosition = createUtf8OffsetMapper(query)\n const start = toPosition(startByte)\n const end = toPosition(endByte)\n return {\n start: { line: start.line, column: start.column, offset: start.index },\n end: { line: end.line, column: end.column, offset: end.index },\n }\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 } 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 query parsing fails\n *\n * @example\n * ```typescript\n * import {format} from '@sanity-labs/groq-wasm'\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 const width = config?.width ?? DEFAULT_WIDTH\n\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 * 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 throw error\n }\n}\n","/**\n * GROQ syntax validation via WASM.\n *\n * Wraps groq-parser's structured parse errors. The parser reports UTF-8 byte\n * offsets; this module converts them to UTF-16 code unit indices.\n */\n\nimport { createUtf8OffsetMapper } from './offsets.js'\nimport { WasmError, type ValidateError, type ValidateResult } from './types.js'\nimport { callValidate } from './wasm-loader.js'\n\n/**\n * Parse a GROQ query.\n *\n * Returns `{ok: true}` when the query parses. Syntax errors are returned as\n * `{ok: false, error}` and are not thrown. `lint` and `format` still throw\n * {@link WasmError} on invalid syntax; this function does not change that.\n *\n * `error.start` and `error.end` are 0-based UTF-16 code unit indices into\n * `query` (`end` is exclusive), which is what JavaScript strings and editors\n * such as Vision use. groq-parser's `ParseError` positions are UTF-8 byte\n * offsets (`Position.start` / `Position.end` in groq-parser-rs). An empty or\n * whitespace-only query is a syntax error (`\"no query\"`) at offset 0, unlike\n * `lint('')` and `format('')`, which treat it as nothing to do.\n *\n * `line` / `column` locate `start`, and `endLine` / `endColumn` locate `end`.\n * They are 1-based. Columns count UTF-16 code units, matching `SourceLocation`\n * on lint findings.\n *\n * Parameter references (`$name`) are accepted. This is a syntax check and does\n * not require the parameters to be declared.\n *\n * @example\n * ```typescript\n * import {validate} from '@sanity-labs/groq-wasm'\n *\n * validate('*[_type == \"post\"]')\n * // {ok: true}\n *\n * validate('*[\"é\" == ]')\n * // {\n * // ok: false,\n * // error: {\n * // message: 'unexpected token \"]\", expected expression',\n * // start: 9,\n * // end: 10,\n * // line: 1,\n * // column: 10,\n * // endLine: 1,\n * // endColumn: 11,\n * // },\n * // }\n * ```\n */\nexport function validate(query: string): ValidateResult {\n let parsed: unknown\n try {\n parsed = JSON.parse(callValidate(query))\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n throw new WasmError(`Validate failed: ${message}`, 'WASM_ERROR')\n }\n\n const payload = readValidatePayload(parsed)\n switch (payload.ok) {\n case true:\n return { ok: true }\n case false:\n return { ok: false, error: toValidateError(query, payload) }\n default: {\n const unexpected: never = payload\n throw new WasmError(`Unexpected validate result: ${JSON.stringify(unexpected)}`, 'WASM_ERROR')\n }\n }\n}\n\ninterface WasmValidateFailure {\n ok: false\n message: string\n start: number\n end: number\n}\n\ntype WasmValidatePayload = { ok: true } | WasmValidateFailure\n\nfunction readValidatePayload(value: unknown): WasmValidatePayload {\n if (!isRecord(value)) {\n throw new WasmError('Validate returned an invalid payload', 'WASM_ERROR')\n }\n\n const ok = value['ok']\n if (ok === true) {\n return { ok: true }\n }\n\n const message = value['message']\n const start = value['start']\n const end = value['end']\n if (\n ok === false &&\n typeof message === 'string' &&\n typeof start === 'number' &&\n typeof end === 'number'\n ) {\n return { ok: false, message, start, end }\n }\n\n throw new WasmError('Validate returned an invalid payload', 'WASM_ERROR')\n}\n\nfunction toValidateError(query: string, failure: WasmValidateFailure): ValidateError {\n const toPosition = createUtf8OffsetMapper(query)\n const start = toPosition(Math.max(0, failure.start))\n const end = toPosition(Math.max(failure.start, failure.end))\n return {\n message: failure.message,\n start: start.index,\n end: end.index,\n line: start.line,\n column: start.column,\n endLine: end.line,\n endColumn: end.column,\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n"],"mappings":";AAgBO,SAAS,YAAY,cAA0D;AACpF,UAAQ,cAAc;AAAA,IACpB,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,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AChE,MAAI,CAAC,SAAS,KAAK,GAAG;AACpB,UAAM,IAAI,UAAU,wCAAwC,YAAY;AAAA,EAC1E;AAEA,QAAM,KAAK,MAAM,IAAI;AACrB,MAAI,OAAO,MAAM;AACf,WAAO,EAAE,IAAI,KAAK;AAAA,EACpB;AAEA,QAAM,UAAU,MAAM,SAAS;AAC/B,QAAM,QAAQ,MAAM,OAAO;AAC3B,QAAM,MAAM,MAAM,KAAK;AACvB,MACE,OAAO,SACP,OAAO,YAAY,YACnB,OAAO,UAAU,YACjB,OAAO,QAAQ,UACf;AACA,WAAO,EAAE,IAAI,OAAO,SAAS,OAAO,IAAI;AAAA,EAC1C;AAEA,QAAM,IAAI,UAAU,wCAAwC,YAAY;AAC1E;AAEA,SAAS,gBAAgB,OAAe,SAA6C;AACnF,QAAM,aAAa,uBAAuB,KAAK;AAC/C,QAAM,QAAQ,WAAW,KAAK,IAAI,GAAG,QAAQ,KAAK,CAAC;AACnD,QAAM,MAAM,WAAW,KAAK,IAAI,QAAQ,OAAO,QAAQ,GAAG,CAAC;AAC3D,SAAO;AAAA,IACL,SAAS,QAAQ;AAAA,IACjB,OAAO,MAAM;AAAA,IACb,KAAK,IAAI;AAAA,IACT,MAAM,MAAM;AAAA,IACZ,QAAQ,MAAM;AAAA,IACd,SAAS,IAAI;AAAA,IACb,WAAW,IAAI;AAAA,EACjB;AACF;AAEA,SAAS,SAAS,OAAkD;AAClE,SAAO,OAAO,UAAU,YAAY,UAAU;AAChD;","names":["ptr","extractParams","lint","format","validate"]}
|
package/dist/index.browser.d.ts
CHANGED
|
@@ -25,9 +25,9 @@ interface WasmFinding {
|
|
|
25
25
|
message: string;
|
|
26
26
|
/** Severity level */
|
|
27
27
|
severity: WasmSeverity;
|
|
28
|
-
/** Start
|
|
28
|
+
/** Start offset into the UTF-8 encoding of the query (0-based) */
|
|
29
29
|
start: number;
|
|
30
|
-
/** End
|
|
30
|
+
/** End offset into the UTF-8 encoding of the query (0-based, exclusive) */
|
|
31
31
|
end: number;
|
|
32
32
|
}
|
|
33
33
|
/**
|
|
@@ -44,6 +44,38 @@ interface WasmFormatConfig {
|
|
|
44
44
|
/** Maximum line width (default: 80) */
|
|
45
45
|
width?: number;
|
|
46
46
|
}
|
|
47
|
+
/**
|
|
48
|
+
* One `$name` reference in a query, from {@link extractParams}.
|
|
49
|
+
*
|
|
50
|
+
* `start` and `end` are indices into the JavaScript query string (UTF-16 code
|
|
51
|
+
* units), not UTF-8 byte offsets. `start` is inclusive and `end` is exclusive,
|
|
52
|
+
* so `query.slice(start, end)` is `"$name"`. Lines and columns are 1-based,
|
|
53
|
+
* and columns count UTF-16 code units, matching `SourceLocation` on lint
|
|
54
|
+
* findings.
|
|
55
|
+
*/
|
|
56
|
+
interface ParamReference {
|
|
57
|
+
/** Inclusive start index of the `$`, 0-based UTF-16 code units. */
|
|
58
|
+
start: number;
|
|
59
|
+
/** Exclusive end index, 0-based UTF-16 code units. */
|
|
60
|
+
end: number;
|
|
61
|
+
/** 1-based line number of `start`. */
|
|
62
|
+
line: number;
|
|
63
|
+
/** 1-based column of `start`, counted in UTF-16 code units. */
|
|
64
|
+
column: number;
|
|
65
|
+
/** 1-based line number of `end`. */
|
|
66
|
+
endLine: number;
|
|
67
|
+
/** 1-based column of `end`, counted in UTF-16 code units. */
|
|
68
|
+
endColumn: number;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* A query parameter referenced by a GROQ query, from {@link extractParams}.
|
|
72
|
+
*/
|
|
73
|
+
interface QueryParam {
|
|
74
|
+
/** Parameter name without the `$`, e.g. `"type"` for `$type`. */
|
|
75
|
+
name: string;
|
|
76
|
+
/** Every reference to this parameter, in source order. Never empty. */
|
|
77
|
+
references: ParamReference[];
|
|
78
|
+
}
|
|
47
79
|
/**
|
|
48
80
|
* Error from WASM operations
|
|
49
81
|
*/
|
|
@@ -59,6 +91,84 @@ declare const RULE_ID_MAP: Record<string, string>;
|
|
|
59
91
|
* Convert Rust rule ID to TS convention
|
|
60
92
|
*/
|
|
61
93
|
declare function mapRuleId(rustRuleId: string): string;
|
|
94
|
+
/**
|
|
95
|
+
* A GROQ syntax error from `validate`.
|
|
96
|
+
*
|
|
97
|
+
* `start` and `end` are indices into the JavaScript query string (UTF-16 code
|
|
98
|
+
* units), not UTF-8 byte offsets. `start` is inclusive and `end` is exclusive,
|
|
99
|
+
* so `query.slice(start, end)` is the reported span. groq-parser reports UTF-8
|
|
100
|
+
* byte offsets; `validate` converts them. A zero-width span (`start === end`)
|
|
101
|
+
* is a caret on a token boundary.
|
|
102
|
+
*
|
|
103
|
+
* `line` / `column` locate `start`, and `endLine` / `endColumn` locate `end`.
|
|
104
|
+
* Lines and columns are 1-based. Columns count UTF-16 code units, matching
|
|
105
|
+
* `SourceLocation` on lint findings.
|
|
106
|
+
*/
|
|
107
|
+
interface ValidateError {
|
|
108
|
+
/** Parser message, without a serialized position suffix. */
|
|
109
|
+
message: string;
|
|
110
|
+
/** Inclusive start index, 0-based UTF-16 code units. */
|
|
111
|
+
start: number;
|
|
112
|
+
/** Exclusive end index, 0-based UTF-16 code units. */
|
|
113
|
+
end: number;
|
|
114
|
+
/** 1-based line number of `start`. */
|
|
115
|
+
line: number;
|
|
116
|
+
/** 1-based column of `start`, counted in UTF-16 code units. */
|
|
117
|
+
column: number;
|
|
118
|
+
/** 1-based line number of `end`. */
|
|
119
|
+
endLine: number;
|
|
120
|
+
/** 1-based column of `end`, counted in UTF-16 code units. */
|
|
121
|
+
endColumn: number;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Result of {@link validate}.
|
|
125
|
+
*
|
|
126
|
+
* Syntax errors are values, not thrown exceptions. `lint` and `format` still
|
|
127
|
+
* throw {@link WasmError} when a query does not parse.
|
|
128
|
+
*/
|
|
129
|
+
type ValidateResult = {
|
|
130
|
+
ok: true;
|
|
131
|
+
} | {
|
|
132
|
+
ok: false;
|
|
133
|
+
error: ValidateError;
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* GROQ query parameter extraction via WASM.
|
|
138
|
+
*
|
|
139
|
+
* Wraps groq-parser's `ParseResult::referenced_params`. The parser reports
|
|
140
|
+
* UTF-8 byte offsets; this module converts them to UTF-16 code unit indices.
|
|
141
|
+
*/
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* List the query parameters (`$name`) a GROQ query references.
|
|
145
|
+
*
|
|
146
|
+
* Returns one entry per distinct name, in order of first reference. Each entry
|
|
147
|
+
* lists every reference to that name in source order. Names do not include
|
|
148
|
+
* the `$`, so they match the keys of the params object passed to a client.
|
|
149
|
+
*
|
|
150
|
+
* Parameters bound by a custom function (`fn ns::f($p) = ...`) are local to
|
|
151
|
+
* that function's body and are not reported from inside it. `$name` text
|
|
152
|
+
* inside string literals and comments is not a reference.
|
|
153
|
+
*
|
|
154
|
+
* Reference `start` / `end` are 0-based UTF-16 code unit indices into
|
|
155
|
+
* `query` (`end` is exclusive), so `query.slice(start, end)` is `"$name"`.
|
|
156
|
+
*
|
|
157
|
+
* An empty or whitespace-only query returns `[]`, like `lint('')`.
|
|
158
|
+
*
|
|
159
|
+
* @param query - The GROQ query string
|
|
160
|
+
* @returns Referenced parameters, in order of first reference
|
|
161
|
+
* @throws {WasmError} With code `PARSE_ERROR` if the query does not parse
|
|
162
|
+
*
|
|
163
|
+
* @example
|
|
164
|
+
* ```typescript
|
|
165
|
+
* import {extractParams} from '@sanity-labs/groq-wasm'
|
|
166
|
+
*
|
|
167
|
+
* extractParams('*[_type == $type][0...$limit]').map((param) => param.name)
|
|
168
|
+
* // ['type', 'limit']
|
|
169
|
+
* ```
|
|
170
|
+
*/
|
|
171
|
+
declare function extractParams(query: string): QueryParam[];
|
|
62
172
|
|
|
63
173
|
/**
|
|
64
174
|
* GROQ Linting via WASM
|
|
@@ -67,7 +177,11 @@ declare function mapRuleId(rustRuleId: string): string;
|
|
|
67
177
|
*/
|
|
68
178
|
|
|
69
179
|
/**
|
|
70
|
-
* Lint a GROQ query using the WASM-based linter
|
|
180
|
+
* Lint a GROQ query using the WASM-based linter.
|
|
181
|
+
*
|
|
182
|
+
* Finding spans are source locations in JavaScript string coordinates.
|
|
183
|
+
* The Rust linter reports UTF-8 byte offsets; `line`, `column`, and `offset`
|
|
184
|
+
* below are converted from those bytes. `column` counts UTF-16 code units.
|
|
71
185
|
*
|
|
72
186
|
* @param query - The GROQ query string to lint
|
|
73
187
|
* @param config - Optional configuration
|
|
@@ -120,5 +234,57 @@ declare function format(query: string, config?: WasmFormatConfig): string;
|
|
|
120
234
|
*/
|
|
121
235
|
declare function isValidSyntax(query: string): boolean;
|
|
122
236
|
|
|
123
|
-
|
|
124
|
-
|
|
237
|
+
/**
|
|
238
|
+
* GROQ syntax validation via WASM.
|
|
239
|
+
*
|
|
240
|
+
* Wraps groq-parser's structured parse errors. The parser reports UTF-8 byte
|
|
241
|
+
* offsets; this module converts them to UTF-16 code unit indices.
|
|
242
|
+
*/
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Parse a GROQ query.
|
|
246
|
+
*
|
|
247
|
+
* Returns `{ok: true}` when the query parses. Syntax errors are returned as
|
|
248
|
+
* `{ok: false, error}` and are not thrown. `lint` and `format` still throw
|
|
249
|
+
* {@link WasmError} on invalid syntax; this function does not change that.
|
|
250
|
+
*
|
|
251
|
+
* `error.start` and `error.end` are 0-based UTF-16 code unit indices into
|
|
252
|
+
* `query` (`end` is exclusive), which is what JavaScript strings and editors
|
|
253
|
+
* such as Vision use. groq-parser's `ParseError` positions are UTF-8 byte
|
|
254
|
+
* offsets (`Position.start` / `Position.end` in groq-parser-rs). An empty or
|
|
255
|
+
* whitespace-only query is a syntax error (`"no query"`) at offset 0, unlike
|
|
256
|
+
* `lint('')` and `format('')`, which treat it as nothing to do.
|
|
257
|
+
*
|
|
258
|
+
* `line` / `column` locate `start`, and `endLine` / `endColumn` locate `end`.
|
|
259
|
+
* They are 1-based. Columns count UTF-16 code units, matching `SourceLocation`
|
|
260
|
+
* on lint findings.
|
|
261
|
+
*
|
|
262
|
+
* Parameter references (`$name`) are accepted. This is a syntax check and does
|
|
263
|
+
* not require the parameters to be declared.
|
|
264
|
+
*
|
|
265
|
+
* @example
|
|
266
|
+
* ```typescript
|
|
267
|
+
* import {validate} from '@sanity-labs/groq-wasm'
|
|
268
|
+
*
|
|
269
|
+
* validate('*[_type == "post"]')
|
|
270
|
+
* // {ok: true}
|
|
271
|
+
*
|
|
272
|
+
* validate('*["é" == ]')
|
|
273
|
+
* // {
|
|
274
|
+
* // ok: false,
|
|
275
|
+
* // error: {
|
|
276
|
+
* // message: 'unexpected token "]", expected expression',
|
|
277
|
+
* // start: 9,
|
|
278
|
+
* // end: 10,
|
|
279
|
+
* // line: 1,
|
|
280
|
+
* // column: 10,
|
|
281
|
+
* // endLine: 1,
|
|
282
|
+
* // endColumn: 11,
|
|
283
|
+
* // },
|
|
284
|
+
* // }
|
|
285
|
+
* ```
|
|
286
|
+
*/
|
|
287
|
+
declare function validate(query: string): ValidateResult;
|
|
288
|
+
|
|
289
|
+
export { DEFAULT_WIDTH, RULE_ID_MAP, WasmError, extractParams, format, isValidSyntax, lint, mapRuleId, mapSeverity, validate };
|
|
290
|
+
export type { ParamReference, QueryParam, ValidateError, ValidateResult, WasmFinding, WasmFormatConfig, WasmLintConfig, WasmSeverity };
|
package/dist/index.browser.js
CHANGED
|
@@ -2,13 +2,15 @@ import {
|
|
|
2
2
|
DEFAULT_WIDTH,
|
|
3
3
|
RULE_ID_MAP,
|
|
4
4
|
WasmError,
|
|
5
|
+
extractParams,
|
|
5
6
|
format,
|
|
6
7
|
initWasm,
|
|
7
8
|
isValidSyntax,
|
|
8
9
|
lint,
|
|
9
10
|
mapRuleId,
|
|
10
|
-
mapSeverity
|
|
11
|
-
|
|
11
|
+
mapSeverity,
|
|
12
|
+
validate
|
|
13
|
+
} from "./chunk-XXDG7JJH.js";
|
|
12
14
|
|
|
13
15
|
// src/index.browser.ts
|
|
14
16
|
var wasmUrl = new URL("../wasm/groq_wasm_bg.wasm", import.meta.url);
|
|
@@ -23,10 +25,12 @@ export {
|
|
|
23
25
|
DEFAULT_WIDTH,
|
|
24
26
|
RULE_ID_MAP,
|
|
25
27
|
WasmError,
|
|
28
|
+
extractParams,
|
|
26
29
|
format,
|
|
27
30
|
isValidSyntax,
|
|
28
31
|
lint,
|
|
29
32
|
mapRuleId,
|
|
30
|
-
mapSeverity
|
|
33
|
+
mapSeverity,
|
|
34
|
+
validate
|
|
31
35
|
};
|
|
32
36
|
//# sourceMappingURL=index.browser.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.browser.ts"],"sourcesContent":["/**\n * @sanity-labs/groq-wasm — Browser entry.\n *\n * Fetches the WASM bytes at import time and initializes the module via\n * top-level await + `initSync`. After this module finishes loading,\n * `lint()` and `
|
|
1
|
+
{"version":3,"sources":["../src/index.browser.ts"],"sourcesContent":["/**\n * @sanity-labs/groq-wasm — Browser entry.\n *\n * Fetches the WASM bytes at import time and initializes the module via\n * top-level await + `initSync`. After this module finishes loading,\n * `lint()`, `format()`, and `validate()` are usable synchronously. Bundlers that\n * understand `new URL('...', import.meta.url)` (Vite, Rollup, Webpack 5,\n * esbuild) emit the WASM file as an asset and rewrite the URL.\n */\n\nimport { initWasm } from './wasm-loader.js'\n\nconst wasmUrl = new URL('../wasm/groq_wasm_bg.wasm', import.meta.url)\nconst response = await fetch(wasmUrl)\nif (!response.ok) {\n throw new Error(\n `Failed to fetch GROQ WASM module from ${wasmUrl.href}: ${response.status} ${response.statusText}`\n )\n}\ninitWasm(await response.arrayBuffer())\n\nexport * from './public.js'\n"],"mappings":";;;;;;;;;;;;;;;AAYA,IAAM,UAAU,IAAI,IAAI,6BAA6B,YAAY,GAAG;AACpE,IAAM,WAAW,MAAM,MAAM,OAAO;AACpC,IAAI,CAAC,SAAS,IAAI;AAChB,QAAM,IAAI;AAAA,IACR,yCAAyC,QAAQ,IAAI,KAAK,SAAS,MAAM,IAAI,SAAS,UAAU;AAAA,EAClG;AACF;AACA,SAAS,MAAM,SAAS,YAAY,CAAC;","names":[]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { DEFAULT_WIDTH, RULE_ID_MAP, WasmError, WasmFinding, WasmFormatConfig, WasmLintConfig, WasmSeverity, format, isValidSyntax, lint, mapRuleId, mapSeverity } from './index.browser.js';
|
|
1
|
+
export { DEFAULT_WIDTH, ParamReference, QueryParam, RULE_ID_MAP, ValidateError, ValidateResult, WasmError, WasmFinding, WasmFormatConfig, WasmLintConfig, WasmSeverity, extractParams, format, isValidSyntax, lint, mapRuleId, mapSeverity, validate } from './index.browser.js';
|
|
2
2
|
import '@sanity-labs/lint-core';
|
package/dist/index.js
CHANGED
|
@@ -2,13 +2,15 @@ import {
|
|
|
2
2
|
DEFAULT_WIDTH,
|
|
3
3
|
RULE_ID_MAP,
|
|
4
4
|
WasmError,
|
|
5
|
+
extractParams,
|
|
5
6
|
format,
|
|
6
7
|
initWasm,
|
|
7
8
|
isValidSyntax,
|
|
8
9
|
lint,
|
|
9
10
|
mapRuleId,
|
|
10
|
-
mapSeverity
|
|
11
|
-
|
|
11
|
+
mapSeverity,
|
|
12
|
+
validate
|
|
13
|
+
} from "./chunk-XXDG7JJH.js";
|
|
12
14
|
|
|
13
15
|
// src/index.ts
|
|
14
16
|
import { readFileSync } from "fs";
|
|
@@ -19,10 +21,12 @@ export {
|
|
|
19
21
|
DEFAULT_WIDTH,
|
|
20
22
|
RULE_ID_MAP,
|
|
21
23
|
WasmError,
|
|
24
|
+
extractParams,
|
|
22
25
|
format,
|
|
23
26
|
isValidSyntax,
|
|
24
27
|
lint,
|
|
25
28
|
mapRuleId,
|
|
26
|
-
mapSeverity
|
|
29
|
+
mapSeverity,
|
|
30
|
+
validate
|
|
27
31
|
};
|
|
28
32
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * @sanity-labs/groq-wasm — Node entry.\n *\n * Loads the WASM module synchronously at import time using `fs.readFileSync`\n * + `initSync`. After importing this package, `lint()` and `
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * @sanity-labs/groq-wasm — Node entry.\n *\n * Loads the WASM module synchronously at import time using `fs.readFileSync`\n * + `initSync`. After importing this package, `lint()`, `format()`, and\n * `validate()` are usable immediately — no async bootstrap.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { fileURLToPath } from 'node:url'\n\nimport { initWasm } from './wasm-loader.js'\n\nconst wasmPath = fileURLToPath(new URL('../wasm/groq_wasm_bg.wasm', import.meta.url))\ninitWasm(readFileSync(wasmPath))\n\nexport * from './public.js'\n"],"mappings":";;;;;;;;;;;;;;;AAQA,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAI9B,IAAM,WAAW,cAAc,IAAI,IAAI,6BAA6B,YAAY,GAAG,CAAC;AACpF,SAAS,aAAa,QAAQ,CAAC;","names":[]}
|
package/package.json
CHANGED
package/wasm/groq_wasm.d.ts
CHANGED
|
@@ -1,6 +1,16 @@
|
|
|
1
1
|
/* tslint:disable */
|
|
2
2
|
/* eslint-disable */
|
|
3
3
|
|
|
4
|
+
/**
|
|
5
|
+
* List every query parameter a GROQ query references, as JSON.
|
|
6
|
+
*
|
|
7
|
+
* Returns one entry per reference, ordered by `start`. Byte offsets are
|
|
8
|
+
* UTF-8 offsets into `query`; the JavaScript wrapper converts them to UTF-16
|
|
9
|
+
* code unit indices. Parameters bound by a custom function (`fn ns::f($p)`)
|
|
10
|
+
* are omitted inside that function's body.
|
|
11
|
+
*/
|
|
12
|
+
export function extractParams(query: string): string;
|
|
13
|
+
|
|
4
14
|
/**
|
|
5
15
|
* Format a GROQ query.
|
|
6
16
|
*
|
|
@@ -26,13 +36,28 @@ export function init(): void;
|
|
|
26
36
|
*/
|
|
27
37
|
export function lint(query: string): string;
|
|
28
38
|
|
|
39
|
+
/**
|
|
40
|
+
* Parse a GROQ query and return a JSON validation result.
|
|
41
|
+
*
|
|
42
|
+
* Byte offsets in the JSON are UTF-8 offsets into `query`. The JavaScript
|
|
43
|
+
* wrapper converts them to UTF-16 code unit indices.
|
|
44
|
+
*
|
|
45
|
+
* Success is `{"ok":true}`. A syntax error is
|
|
46
|
+
* `{"ok":false,"message":"...","start":N,"end":M}` where `start` is inclusive,
|
|
47
|
+
* `end` is exclusive, and the two are equal when the parser reports a caret
|
|
48
|
+
* rather than a token span.
|
|
49
|
+
*/
|
|
50
|
+
export function validate(query: string): string;
|
|
51
|
+
|
|
29
52
|
export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;
|
|
30
53
|
|
|
31
54
|
export interface InitOutput {
|
|
32
55
|
readonly memory: WebAssembly.Memory;
|
|
56
|
+
readonly extractParams: (a: number, b: number) => [number, number, number, number];
|
|
33
57
|
readonly format: (a: number, b: number, c: number) => [number, number, number, number];
|
|
34
58
|
readonly init: () => void;
|
|
35
59
|
readonly lint: (a: number, b: number) => [number, number, number, number];
|
|
60
|
+
readonly validate: (a: number, b: number) => [number, number];
|
|
36
61
|
readonly __wbindgen_free: (a: number, b: number, c: number) => void;
|
|
37
62
|
readonly __wbindgen_malloc: (a: number, b: number) => number;
|
|
38
63
|
readonly __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
|
package/wasm/groq_wasm.js
CHANGED
|
@@ -1,5 +1,36 @@
|
|
|
1
1
|
/* @ts-self-types="./groq_wasm.d.ts" */
|
|
2
2
|
|
|
3
|
+
/**
|
|
4
|
+
* List every query parameter a GROQ query references, as JSON.
|
|
5
|
+
*
|
|
6
|
+
* Returns one entry per reference, ordered by `start`. Byte offsets are
|
|
7
|
+
* UTF-8 offsets into `query`; the JavaScript wrapper converts them to UTF-16
|
|
8
|
+
* code unit indices. Parameters bound by a custom function (`fn ns::f($p)`)
|
|
9
|
+
* are omitted inside that function's body.
|
|
10
|
+
* @param {string} query
|
|
11
|
+
* @returns {string}
|
|
12
|
+
*/
|
|
13
|
+
export function extractParams(query) {
|
|
14
|
+
let deferred3_0;
|
|
15
|
+
let deferred3_1;
|
|
16
|
+
try {
|
|
17
|
+
const ptr0 = passStringToWasm0(query, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
|
18
|
+
const len0 = WASM_VECTOR_LEN;
|
|
19
|
+
const ret = wasm.extractParams(ptr0, len0);
|
|
20
|
+
var ptr2 = ret[0];
|
|
21
|
+
var len2 = ret[1];
|
|
22
|
+
if (ret[3]) {
|
|
23
|
+
ptr2 = 0; len2 = 0;
|
|
24
|
+
throw takeFromExternrefTable0(ret[2]);
|
|
25
|
+
}
|
|
26
|
+
deferred3_0 = ptr2;
|
|
27
|
+
deferred3_1 = len2;
|
|
28
|
+
return getStringFromWasm0(ptr2, len2);
|
|
29
|
+
} finally {
|
|
30
|
+
wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
3
34
|
/**
|
|
4
35
|
* Format a GROQ query.
|
|
5
36
|
*
|
|
@@ -69,6 +100,34 @@ export function lint(query) {
|
|
|
69
100
|
wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);
|
|
70
101
|
}
|
|
71
102
|
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Parse a GROQ query and return a JSON validation result.
|
|
106
|
+
*
|
|
107
|
+
* Byte offsets in the JSON are UTF-8 offsets into `query`. The JavaScript
|
|
108
|
+
* wrapper converts them to UTF-16 code unit indices.
|
|
109
|
+
*
|
|
110
|
+
* Success is `{"ok":true}`. A syntax error is
|
|
111
|
+
* `{"ok":false,"message":"...","start":N,"end":M}` where `start` is inclusive,
|
|
112
|
+
* `end` is exclusive, and the two are equal when the parser reports a caret
|
|
113
|
+
* rather than a token span.
|
|
114
|
+
* @param {string} query
|
|
115
|
+
* @returns {string}
|
|
116
|
+
*/
|
|
117
|
+
export function validate(query) {
|
|
118
|
+
let deferred2_0;
|
|
119
|
+
let deferred2_1;
|
|
120
|
+
try {
|
|
121
|
+
const ptr0 = passStringToWasm0(query, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
|
122
|
+
const len0 = WASM_VECTOR_LEN;
|
|
123
|
+
const ret = wasm.validate(ptr0, len0);
|
|
124
|
+
deferred2_0 = ret[0];
|
|
125
|
+
deferred2_1 = ret[1];
|
|
126
|
+
return getStringFromWasm0(ret[0], ret[1]);
|
|
127
|
+
} finally {
|
|
128
|
+
wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
72
131
|
function __wbg_get_imports() {
|
|
73
132
|
const import0 = {
|
|
74
133
|
__proto__: null,
|
package/wasm/groq_wasm_bg.wasm
CHANGED
|
Binary file
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
/* tslint:disable */
|
|
2
2
|
/* eslint-disable */
|
|
3
3
|
export const memory: WebAssembly.Memory;
|
|
4
|
+
export const extractParams: (a: number, b: number) => [number, number, number, number];
|
|
4
5
|
export const format: (a: number, b: number, c: number) => [number, number, number, number];
|
|
5
6
|
export const init: () => void;
|
|
6
7
|
export const lint: (a: number, b: number) => [number, number, number, number];
|
|
8
|
+
export const validate: (a: number, b: number) => [number, number];
|
|
7
9
|
export const __wbindgen_free: (a: number, b: number, c: number) => void;
|
|
8
10
|
export const __wbindgen_malloc: (a: number, b: number) => number;
|
|
9
11
|
export const __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.ts","../wasm/groq_wasm.js","../src/wasm-loader.ts","../src/lint.ts","../src/format.ts"],"sourcesContent":["/**\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: '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 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 unlimited_query: 'unlimited-query',\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","/* @ts-self-types=\"./groq_wasm.d.ts\" */\n\n/**\n * Format a GROQ query.\n *\n * # Arguments\n * * `query` - The GROQ query string to format\n * * `width` - Maximum line width (default: 80)\n *\n * # Returns\n * The formatted query string\n * @param {string} query\n * @param {number | null} [width]\n * @returns {string}\n */\nexport function format(query, width) {\n let deferred3_0;\n let deferred3_1;\n try {\n const ptr0 = passStringToWasm0(query, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.format(ptr0, len0, isLikeNone(width) ? Number.MAX_SAFE_INTEGER : (width) >>> 0);\n var ptr2 = ret[0];\n var len2 = ret[1];\n if (ret[3]) {\n ptr2 = 0; len2 = 0;\n throw takeFromExternrefTable0(ret[2]);\n }\n deferred3_0 = ptr2;\n deferred3_1 = len2;\n return getStringFromWasm0(ptr2, len2);\n } finally {\n wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);\n }\n}\n\nexport function init() {\n wasm.init();\n}\n\n/**\n * Lint a GROQ query and return findings as JSON.\n *\n * # Arguments\n * * `query` - The GROQ query string to lint\n *\n * # Returns\n * A JSON string containing an array of findings\n * @param {string} query\n * @returns {string}\n */\nexport function lint(query) {\n let deferred3_0;\n let deferred3_1;\n try {\n const ptr0 = passStringToWasm0(query, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len0 = WASM_VECTOR_LEN;\n const ret = wasm.lint(ptr0, len0);\n var ptr2 = ret[0];\n var len2 = ret[1];\n if (ret[3]) {\n ptr2 = 0; len2 = 0;\n throw takeFromExternrefTable0(ret[2]);\n }\n deferred3_0 = ptr2;\n deferred3_1 = len2;\n return getStringFromWasm0(ptr2, len2);\n } finally {\n wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);\n }\n}\nfunction __wbg_get_imports() {\n const import0 = {\n __proto__: null,\n __wbg_error_757e9472f8410341: function(arg0, arg1) {\n let deferred0_0;\n let deferred0_1;\n try {\n deferred0_0 = arg0;\n deferred0_1 = arg1;\n console.error(getStringFromWasm0(arg0, arg1));\n } finally {\n wasm.__wbindgen_free(deferred0_0, deferred0_1, 1);\n }\n },\n __wbg_new_227d7c05414eb861: function() {\n const ret = new Error();\n return ret;\n },\n __wbg_stack_3b0d974bbf31e44f: function(arg0, arg1) {\n const ret = arg1.stack;\n const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len1 = WASM_VECTOR_LEN;\n getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);\n getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);\n },\n __wbindgen_generic_0000000000000001: function(arg0, arg1) {\n // Cast intrinsic for `Ref(String) -> Externref`.\n const ret = getStringFromWasm0(arg0, arg1);\n return ret;\n },\n __wbindgen_init_externref_table: function() {\n const table = wasm.__wbindgen_externrefs;\n const offset = table.grow(4);\n table.set(0, undefined);\n table.set(offset + 0, undefined);\n table.set(offset + 1, null);\n table.set(offset + 2, true);\n table.set(offset + 3, false);\n },\n };\n return {\n __proto__: null,\n \"./groq_wasm_bg.js\": import0,\n };\n}\n\nlet cachedDataViewMemory0 = null;\nfunction getDataViewMemory0() {\n if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {\n cachedDataViewMemory0 = new DataView(wasm.memory.buffer);\n }\n return cachedDataViewMemory0;\n}\n\nfunction getStringFromWasm0(ptr, len) {\n return decodeText(ptr >>> 0, len);\n}\n\nlet cachedUint8ArrayMemory0 = null;\nfunction getUint8ArrayMemory0() {\n if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {\n cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);\n }\n return cachedUint8ArrayMemory0;\n}\n\nfunction isLikeNone(x) {\n return x === undefined || x === null;\n}\n\nfunction passStringToWasm0(arg, malloc, realloc) {\n if (realloc === undefined) {\n const buf = cachedTextEncoder.encode(arg);\n const ptr = malloc(buf.length, 1) >>> 0;\n getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);\n WASM_VECTOR_LEN = buf.length;\n return ptr;\n }\n\n let len = arg.length;\n let ptr = malloc(len, 1) >>> 0;\n\n const mem = getUint8ArrayMemory0();\n\n let offset = 0;\n\n for (; offset < len; offset++) {\n const code = arg.charCodeAt(offset);\n if (code > 0x7F) break;\n mem[ptr + offset] = code;\n }\n if (offset !== len) {\n if (offset !== 0) {\n arg = arg.slice(offset);\n }\n ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;\n const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);\n const ret = cachedTextEncoder.encodeInto(arg, view);\n\n offset += ret.written;\n ptr = realloc(ptr, len, offset, 1) >>> 0;\n }\n\n WASM_VECTOR_LEN = offset;\n return ptr;\n}\n\nfunction takeFromExternrefTable0(idx) {\n const value = wasm.__wbindgen_externrefs.get(idx);\n wasm.__externref_table_dealloc(idx);\n return value;\n}\n\nlet cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });\ncachedTextDecoder.decode();\nconst MAX_SAFARI_DECODE_BYTES = 2146435072;\nlet numBytesDecoded = 0;\nfunction decodeText(ptr, len) {\n numBytesDecoded += len;\n if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {\n cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });\n cachedTextDecoder.decode();\n numBytesDecoded = len;\n }\n return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));\n}\n\nconst cachedTextEncoder = new TextEncoder();\n\nif (!('encodeInto' in cachedTextEncoder)) {\n cachedTextEncoder.encodeInto = function (arg, view) {\n const buf = cachedTextEncoder.encode(arg);\n view.set(buf);\n return {\n read: arg.length,\n written: buf.length\n };\n };\n}\n\nlet WASM_VECTOR_LEN = 0;\n\nlet wasmModule, wasmInstance, wasm;\nfunction __wbg_finalize_init(instance, module) {\n wasmInstance = instance;\n wasm = instance.exports;\n wasmModule = module;\n cachedDataViewMemory0 = null;\n cachedUint8ArrayMemory0 = null;\n wasm.__wbindgen_start();\n return wasm;\n}\n\nasync function __wbg_load(module, imports) {\n if (typeof Response === 'function' && module instanceof Response) {\n if (!module.ok) {\n throw new Error(`failed to fetch Wasm: ${module.status} ${module.statusText} fetching '${module.url}'`);\n }\n\n if (typeof WebAssembly.instantiateStreaming === 'function') {\n try {\n return await WebAssembly.instantiateStreaming(module, imports);\n } catch (e) {\n const validResponse = expectedResponseType(module.type);\n\n if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {\n console.warn(\"`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n\", e);\n\n } else { throw e; }\n }\n }\n\n const bytes = await module.arrayBuffer();\n return await WebAssembly.instantiate(bytes, imports);\n } else {\n const instance = await WebAssembly.instantiate(module, imports);\n\n if (instance instanceof WebAssembly.Instance) {\n return { instance, module };\n } else {\n return instance;\n }\n }\n\n function expectedResponseType(type) {\n switch (type) {\n case 'basic': case 'cors': case 'default': return true;\n }\n return false;\n }\n}\n\nfunction initSync(module) {\n if (wasm !== undefined) return wasm;\n\n\n if (module !== undefined) {\n if (Object.getPrototypeOf(module) === Object.prototype) {\n ({module} = module)\n } else {\n console.warn('using deprecated parameters for `initSync()`; pass a single object instead')\n }\n }\n\n const imports = __wbg_get_imports();\n if (!(module instanceof WebAssembly.Module)) {\n module = new WebAssembly.Module(module);\n }\n const instance = new WebAssembly.Instance(module, imports);\n return __wbg_finalize_init(instance, module);\n}\n\nasync function __wbg_init(module_or_path) {\n if (wasm !== undefined) return wasm;\n\n\n if (module_or_path !== undefined) {\n if (Object.getPrototypeOf(module_or_path) === Object.prototype) {\n ({module_or_path} = module_or_path)\n } else {\n console.warn('using deprecated parameters for the initialization function; pass a single object instead')\n }\n }\n\n if (module_or_path === undefined) {\n module_or_path = new URL('groq_wasm_bg.wasm', import.meta.url);\n }\n const imports = __wbg_get_imports();\n\n if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {\n module_or_path = fetch(module_or_path);\n }\n\n const { instance, module } = await __wbg_load(await module_or_path, imports);\n\n return __wbg_finalize_init(instance, module);\n}\n\nexport { initSync, __wbg_init as default };\n","/**\n * WASM module runtime.\n *\n * Exposes the WASM-backed lint/format calls and a synchronous init helper.\n * The actual byte loading is platform-specific and happens in the\n * environment-specific entry (`index.ts` for Node, `index.browser.ts` for\n * the browser). By the time any caller of this package can call `lint()` /\n * `format()`, the entry has already run `initWasm(bytes)`.\n */\n\nimport * as wasmModule from '../wasm/groq_wasm.js'\n\nimport { WasmError } from './types.js'\n\nexport function initWasm(bytes: ArrayBuffer | Uint8Array): void {\n try {\n wasmModule.initSync({ module: bytes })\n } catch (error) {\n throw new WasmError(\n `Failed to initialize WASM: ${error instanceof Error ? error.message : String(error)}`,\n 'WASM_ERROR'\n )\n }\n}\n\nexport function callLint(query: string): string {\n return wasmModule.lint(query)\n}\n\nexport function callFormat(query: string, width?: number): string {\n return wasmModule.format(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 } 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 query parsing fails\n *\n * @example\n * ```typescript\n * import {lint} from '@sanity-labs/groq-wasm'\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 (!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 * 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 } 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 query parsing fails\n *\n * @example\n * ```typescript\n * import {format} from '@sanity-labs/groq-wasm'\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 const width = config?.width ?? DEFAULT_WIDTH\n\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 * 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 throw error\n }\n}\n"],"mappings":";AAgBO,SAAS,YAAY,cAA0D;AACpF,UAAQ,cAAc;AAAA,IACpB,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,EACX;AACF;AAqCO,IAAM,YAAN,cAAwB,MAAM;AAAA,EACnC,YACE,SACgB,MAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AAAA,EAJkB;AAKpB;AAKO,IAAM,cAAsC;AAAA,EACjD,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,0BAA0B;AAAA,EAC1B,aAAa;AAAA,EACb,eAAe;AAAA,EACf,iBAAiB;AAAA,EACjB,aAAa;AAAA,EACb,wBAAwB;AAAA,EACxB,8BAA8B;AAAA,EAC9B,kBAAkB;AAAA,EAClB,uBAAuB;AAAA,EACvB,YAAY;AAAA,EACZ,iBAAiB;AACnB;AAKO,SAAS,UAAU,YAA4B;AACpD,SAAO,YAAY,UAAU,KAAK,WAAW,Q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