@sanity-labs/groq-wasm 0.2.0 → 0.3.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/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/index.js
CHANGED
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.ts","../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: '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 * Uses the `--target web` output from wasm-pack, which works in both Node.js and browsers.\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 const wasmModule = await import('../wasm/groq_wasm.js')\n const wasmUrl = new URL('../wasm/groq_wasm_bg.wasm', import.meta.url)\n\n if (wasmUrl.protocol === 'file:') {\n // Node.js: fetch() doesn't support file:// URLs, read from disk\n const { readFile } = await import('node:fs/promises')\n const { fileURLToPath } = await import('node:url')\n const bytes = await readFile(fileURLToPath(wasmUrl))\n await wasmModule.default({ module_or_path: bytes })\n } else {\n // Browser / other runtimes: use fetch via the default init path\n await wasmModule.default({ module_or_path: wasmUrl })\n }\n\n // Store the functions\n wasmLint = wasmModule.lint\n wasmFormat = wasmModule.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":";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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AA0B,OAAO,IAAI,aAAa;AAAA,IACxE;AAEA,UAAM,IAAI,UAAU,kBAAkB,OAAO,IAAI,YAAY;AAAA,EAC/D;AACF;AAKA,eAAsB,YAAY,OAAe,QAA4C;AAG3F,SAAO,OAAO,OAAO,MAAM;AAC7B;AAQO,SAAS,cAAc,OAAwB;AACpD,MAAI;AACF,WAAO,KAAK;AACZ,WAAO;AAAA,EACT,SAAS,OAAO;AACd,QAAI,iBAAiB,aAAa,MAAM,SAAS,eAAe;AAC9D,aAAO;AAAA,IACT;AAEA,UAAM;AAAA,EACR;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../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: '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 * Uses the `--target web` output from wasm-pack, which works in both Node.js and browsers.\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 const wasmModule = await import('../wasm/groq_wasm.js')\n const wasmUrl = new URL('../wasm/groq_wasm_bg.wasm', import.meta.url)\n\n if (wasmUrl.protocol === 'file:') {\n // Node.js: fetch() doesn't support file:// URLs, read from disk\n const { readFile } = await import('node:fs/promises')\n const { fileURLToPath } = await import('node:url')\n const bytes = await readFile(fileURLToPath(wasmUrl))\n await wasmModule.default({ module_or_path: bytes })\n } else {\n // Browser / other runtimes: use fetch via the default init path\n await wasmModule.default({ module_or_path: wasmUrl })\n }\n\n // Store the functions\n wasmLint = wasmModule.lint\n wasmFormat = wasmModule.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":";AAgBO,SAAS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S,OAAO;AACd,UAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAErE,QAAI,QAAQ,SAAS,OAAO,KAAK,QAAQ,SAAS,OAAO,GAAG;AAC1D,YAAM,IAAI,UAAU,0BAA0B,OAAO,IAAI,aAAa;AAAA,IACxE;AAEA,UAAM,IAAI,UAAU,kBAAkB,OAAO,IAAI,YAAY;AAAA,EAC/D;AACF;AAKA,eAAsB,YAAY,OAAe,QAA4C;AAG3F,SAAO,OAAO,OAAO,MAAM;AAC7B;AAQO,SAAS,cAAc,OAAwB;AACpD,MAAI;AACF,WAAO,KAAK;AACZ,WAAO;AAAA,EACT,SAAS,OAAO;AACd,QAAI,iBAAiB,aAAa,MAAM,SAAS,eAAe;AAC9D,aAAO;AAAA,IACT;AAEA,UAAM;AAAA,EACR;AACF;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity-labs/groq-wasm",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "WASM bindings for GROQ linting and formatting (groq-lint + groq-format)",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"sanity",
|
|
@@ -32,8 +32,8 @@
|
|
|
32
32
|
"devDependencies": {
|
|
33
33
|
"tsup": "^8.3.5",
|
|
34
34
|
"typescript": "^5.7.2",
|
|
35
|
-
"vitest": "^
|
|
36
|
-
"@sanity-labs/lint-core": "0.
|
|
35
|
+
"vitest": "^4.0.0",
|
|
36
|
+
"@sanity-labs/lint-core": "0.2.0"
|
|
37
37
|
},
|
|
38
38
|
"engines": {
|
|
39
39
|
"node": ">=20.0.0"
|