{"id":32972025,"url":"https://github.com/jetstreamapp/soql-parser-js","last_synced_at":"2026-04-25T17:03:25.108Z","repository":{"id":37445087,"uuid":"145348161","full_name":"jetstreamapp/soql-parser-js","owner":"jetstreamapp","description":"Javascript SOQL parser","archived":false,"fork":false,"pushed_at":"2025-12-15T22:42:10.000Z","size":8111,"stargazers_count":86,"open_issues_count":4,"forks_count":23,"subscribers_count":4,"default_branch":"master","last_synced_at":"2026-01-06T16:35:08.136Z","etag":null,"topics":["antlr","salesforce","soql","soql-query","typescript"],"latest_commit_sha":null,"homepage":"https://jetstreamapp.github.io/soql-parser-js/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jetstreamapp.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":"AUTHORS.md","dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2018-08-20T00:39:53.000Z","updated_at":"2025-12-15T22:40:20.000Z","dependencies_parsed_at":"2024-06-16T18:57:46.508Z","dependency_job_id":"b6621772-2755-4b68-a9c3-dd180bbec70e","html_url":"https://github.com/jetstreamapp/soql-parser-js","commit_stats":null,"previous_names":["paustint/soql-parser-js"],"tags_count":97,"template":false,"template_full_name":null,"purl":"pkg:github/jetstreamapp/soql-parser-js","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jetstreamapp%2Fsoql-parser-js","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jetstreamapp%2Fsoql-parser-js/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jetstreamapp%2Fsoql-parser-js/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jetstreamapp%2Fsoql-parser-js/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jetstreamapp","download_url":"https://codeload.github.com/jetstreamapp/soql-parser-js/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jetstreamapp%2Fsoql-parser-js/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28535156,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-18T10:13:46.436Z","status":"ssl_error","status_checked_at":"2026-01-18T10:13:11.045Z","response_time":98,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["antlr","salesforce","soql","soql-query","typescript"],"created_at":"2025-11-13T05:00:32.333Z","updated_at":"2026-01-18T11:03:51.262Z","avatar_url":"https://github.com/jetstreamapp.png","language":"TypeScript","funding_links":[],"categories":["Table of Contents"],"sub_categories":["Developer Utilities"],"readme":"\u003cimg src=\"./assets/soql-parser-js-logo.svg\"\u003e\n\n![build](https://github.com/jetstreamapp/soql-parser-js/actions/workflows/ci.yml/badge.svg)\n[![npm version](https://badge.fury.io/js/@jetstreamapp%2Fsoql-parser-js.svg)](https://badge.fury.io/js/@jetstreamapp%2Fsoql-parser-js)\n\n## Description\n\n**This library allows parsing and composing SOQL queries from Salesforce using JavaScript or Typescript.**\n\n### Installation\n\n👉 **As of version 6.0.0**, this package is now part of the `@jetstreamapp` npm organization.\n\n```bash\nnpm install @jetstreamapp/soql-parser-js\n```\n\n**Available Features:**\n\n1. Parse SOQL queries into a common `Query` data structure.\n2. Deterministically compose a `Query` data structure back into a SOQL query string.\n3. Validate a query to check if the syntax is valid.\n   1. _Even if a query is returned as valid, it might still be invalid based on your Salesforce configuration_\n\nMigrating from version 1 to version 2? [Check out the changelog](CHANGELOG.md#200) for a full list of changes.\n\nMigrating from version 2 to version 3? [Check out the changelog](CHANGELOG.md#300) for a full list of changes.\n\n## Documentation\n\n**[Read the documentation on our docs site](https://paustint.github.io/soql-parser-js/)**.\n\n## Compatibility\n\n**Node**: version 11 or higher, or a polyfill for [Array.flat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat)  \n**Browser**: Tested in all modern browsers, may not work with older browsers.\n\nThe **commander** dependency is only required for the cli, the other two dependencies **chevrotain** and **lodash.get** are bundled with the non-cli code.\n\n## Quick Start\n\n```javascript\nimport { parseQuery, composeQuery, isQueryValid } from '@jetstreamapp/soql-parser-js';\n\nconst query = parseQuery(`SELECT Id FROM Account WHERE Id = 'FOO'`);\nconsole.log('query', query);\n\nconst soql = composeQuery(query);\nconsole.log('soql', soql); // SELECT Id FROM Account WHERE Id = 'FOO'\n\nisQueryValid('SELECT Id, Foo FROM Baz'); // true\nisQueryValid('SELECT Id Foo FROM Baz'); // false\n```\n\n## Available Features\n\n| Function     | Description                                            | Arguments                                  |\n| ------------ | ------------------------------------------------------ | ------------------------------------------ |\n| parseQuery   | Parse a SOQL query string into a Query data structure. | soql: Query\u003cbr\u003e config?: ParseQueryConfig  |\n| isQueryValid | Returns true if the query was able to be parsed.       | soql: Query\u003cbr\u003e config?: ParseQueryConfig  |\n| composeQuery | Turn a Query object back into a SOQL statement.        | soql: Query\u003cbr\u003e config?: SoqlComposeConfig |\n| formatQuery  | Format a SOQL query string.                            | soql: Query\u003cbr\u003e config?: FormatOptions     |\n\n## Utility Functions\n\n**General Utility**\n\nMany of hte utility functions are provided to easily determine the shape of specific data since there are many variants. If you are using Typescript in strict mode, you can use these to narrow your types.\n\n| Function                                | Description                                                                                                                                                                                                             | Arguments                                                                   |\n| --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |\n| hasAlias                                | Returns `true` if the field passed in has the `alias` property.                                                                                                                                                         | input: `string \\| ComposeFieldInput`                                        |\n| getField                                | Convenience method to construct fields in the correct format when using `composeQuery()`. Look in the data models section below for the structure of `ComposeFieldInput`.                                               | input: `string \\| ComposeFieldInput`                                        |\n| getFlattenedFields                      | Flatten a Salesforce record based on the parsed SOQL Query. this is useful if you have relationships in your query and want to show the results in a table, using `.` dot notation for the relationship field headings. | soql: `Query \\| Subquery \\| FieldSubquery`\u003cbr\u003e config?: `SoqlComposeConfig` |\n| isSubquery                              | Returns `true` if the data passed in is a subquery.                                                                                                                                                                     | query: `Query \\| Subquery`                                                  |\n| isFieldSubquery                         | Returns `true` if the data passed in is a FieldSubquery.                                                                                                                                                                | value: `any`                                                                |\n| isWhereClauseWithRightCondition         | Returns `true` if the value passed in is a `WhereClause` with an `operator` and `right` property                                                                                                                        | value: `WhereClause`                                                        |\n| isHavingClauseWithRightCondition        | Returns `true` if the value passed in is a `HavingClause` with an `operator` and `right` property                                                                                                                       | value: `HavingClause`                                                       |\n| isWhereOrHavingClauseWithRightCondition | Returns `true` if the value passed in is a `WhereClause` or `HavingClause` with an `operator` and `right` property                                                                                                      | value: `WhereClause \\| HavingClause`                                        |\n| isValueCondition                        | Returns `true` if the value passed in has `field`, `operator` and `value` properties                                                                                                                                    | value: `Condition`                                                          |\n| isValueWithDateLiteralCondition         | Returns `true` if the value passed in has `field`, `operator` and `value` properties and has a `literalType` property that is `DATE_LITERAL` of `['DATE_LITERAL',...]`                                                  | value: `Condition`                                                          |\n| isValueWithDateNLiteralCondition        | Returns `true` if the value passed in has `field`, `operator`, `value` and `dateLiteralVariable` properties                                                                                                             | value: `Condition`                                                          |\n| isValueFunctionCondition                | Returns `true` if the value passed in has `fn`, `operator` and `value` properties                                                                                                                                       | value: `Condition`                                                          |\n| isNegationCondition                     | Returns `true` if the value passed in has a `openParen` property and does not have `fn`, `field`, `operator`, `value`, and `closeParen` properties                                                                      | value: `Condition`                                                          |\n| isValueQueryCondition                   | Returns `true` if the value passed in has `field`, `operator` and `valueQuery` properties and does not have a `value` property                                                                                          | value: `Condition \\| ValueQueryCondition`                                   |\n| isOrderByField                          | Returns `true` if the value passed in has `field` property                                                                                                                                                              | value: `OrderByClause`                                                      |\n| isOrderByFn                             | Returns `true` if the value passed in has `fn` property                                                                                                                                                                 | value: `OrderByClause`                                                      |\n| isGroupByField                          | Returns `true` if the value passed in has `field` property                                                                                                                                                              | value: `GroupByClause`                                                      |\n| isGroupByFn                             | Returns `true` if the value passed in has `fn` property                                                                                                                                                                 | value: `GroupByClause`                                                      |\n\n**ParseQueryConfig**\n\n| Property               | Type    | Description                                                                                                                                                                                                                                   | required | default |\n| ---------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ------- |\n| allowApexBindVariables | boolean | Determines if apex variables are allowed in parsed query. Example: `WHERE Id IN :accountIds`. Only simple Apex is supported. Function calls are not supported. (e.x. `accountMap.keyset()` is not supported)                                  | FALSE    | FALSE   |\n| allowPartialQuery      | boolean | If provided, you can provide an incomplete soql query. This is useful if you need to parse WHERE clauses, for example. Subqueries are required to be valid.                                                                                   | FALSE    | FALSE   |\n| ignoreParseErrors      | boolean | If set to true, then queries with partially invalid syntax will still be parsed, but any clauses with invalid parts will be omitted. The SELECT clause and FROM clause must always be valid, but all other clauses can contain invalid parts. | FALSE    | FALSE   |\n| logErrors              | boolean | If true, parsing and lexing errors will be logged to the console.                                                                                                                                                                             | FALSE    | FALSE   |\n\n**SoqlComposeConfig**\n\n| Property      | Type          | Description                                                                                                                                                                                                              | required | default |\n| ------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------- | ------- |\n| format        | boolean       | Apply formatting the the composed query. This will result in a multi-line soql statement.                                                                                                                                | FALSE    | TRUE    |\n| formatOptions | FormatOptions | Options to apply to the formatter.                                                                                                                                                                                       | FALSE    |         |\n| autoCompose   | boolean       | If you need to compose just part of a query, you can create your own instance of the Compose class and set this to false, then call any methods that you need to just for what you would like to turn into a SOQL query. | FALSE    | TRUE    |\n| logging       | boolean       | Print out logging statements to the console about the format operation.                                                                                                                                                  | FALSE    | FALSE   |\n\n**FormatOptions**\n\n| Property                         | Type    | Description                                                                                                                                                                                 | required | default |\n| -------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ------- |\n| numIndent                        | number  | The number of tab characters to indent.                                                                                                                                                     | FALSE    | 1       |\n| fieldMaxLineLength               | number  | The number of characters that the fields should take up before making a new line. Set this to 1 to have every field on its own line.                                                        | FALSE    | 60      |\n| fieldSubqueryParensOnOwnLine     | boolean | If true, the opening and closing parentheses will be on their own line for subqueries.                                                                                                      | FALSE    | TRUE    |\n| newLineAfterKeywords             | boolean | Adds a new line and indent after all keywords (such as SELECT, FROM, WHERE, ORDER BY, etc..) Setting this to true will add new lines in other places as well, such as complex WHERE clauses | FALSE    | FALSE   |\n| ~~whereClauseOperatorsIndented~~ | boolean | **Deprecated** If true, indents the where clause operators.                                                                                                                                 | FALSE    | FALSE   |\n| logging                          | boolean | Print out logging statements to the console about the format operation.                                                                                                                     | FALSE    | FALSE   |\n\n## Examples\n\n### Parsing Queries\n\nParsing a SOQL query can be completed by calling `parseQuery(soqlQueryString)`. A `Query` data structure will be returned.\n\n```typescript\nimport { parseQuery } from '@jetstreamapp/soql-parser-js';\n\nconst soql = `\n  SELECT UserId, COUNT(Id)\n  FROM LoginHistory\n  WHERE LoginTime \u003e 2010-09-20T22:16:30.000Z\n  AND LoginTime \u003c 2010-09-21T22:16:30.000Z\n  GROUP BY UserId\n`;\n\nconst soqlQuery = parseQuery(soql);\n\nconsole.log(JSON.stringify(soqlQuery, null, 2));\n```\n\n\u003cdetails\u003e\n  \u003csummary\u003e\u003cb\u003eResults (click to show)\u003c/b\u003e\u003c/summary\u003e\n\n```json\n{\n  \"fields\": [\n    {\n      \"type\": \"Field\",\n      \"field\": \"UserId\"\n    },\n    {\n      \"type\": \"FieldFunctionExpression\",\n      \"functionName\": \"COUNT\",\n      \"parameters\": [\"Id\"],\n      \"isAggregateFn\": true,\n      \"rawValue\": \"COUNT(Id)\"\n    }\n  ],\n  \"sObject\": \"LoginHistory\",\n  \"where\": {\n    \"left\": {\n      \"field\": \"LoginTime\",\n      \"operator\": \"\u003e\",\n      \"value\": \"2010-09-20T22:16:30.000Z\",\n      \"literalType\": \"DATETIME\"\n    },\n    \"operator\": \"AND\",\n    \"right\": {\n      \"left\": {\n        \"field\": \"LoginTime\",\n        \"operator\": \"\u003c\",\n        \"value\": \"2010-09-21T22:16:30.000Z\",\n        \"literalType\": \"DATETIME\"\n      }\n    }\n  },\n  \"groupBy\": {\n    \"field\": \"UserId\"\n  }\n}\n```\n\n\u003c/details\u003e\n\n### Parsing a partial query\n\nAdded support for `allowPartialQuery` in version `4.4.0`\n\n```typescript\nimport { parseQuery } from '@jetstreamapp/soql-parser-js';\n\nconst soql = `\n  WHERE LoginTime \u003e 2010-09-20T22:16:30.000Z\n  AND LoginTime \u003c 2010-09-21T22:16:30.000Z\n  GROUP BY UserId\n`;\n\nconst soqlQuery = parseQuery(soql, { allowPartialQuery: true });\n\nconsole.log(JSON.stringify(soqlQuery, null, 2));\n```\n\n\u003cdetails\u003e\n  \u003csummary\u003e\u003cb\u003eResults (click to show)\u003c/b\u003e\u003c/summary\u003e\n\n```json\n{\n  \"where\": {\n    \"left\": {\n      \"field\": \"LoginTime\",\n      \"operator\": \"\u003e\",\n      \"value\": \"2010-09-20T22:16:30.000Z\",\n      \"literalType\": \"DATETIME\"\n    },\n    \"operator\": \"AND\",\n    \"right\": {\n      \"left\": {\n        \"field\": \"LoginTime\",\n        \"operator\": \"\u003c\",\n        \"value\": \"2010-09-21T22:16:30.000Z\",\n        \"literalType\": \"DATETIME\"\n      }\n    }\n  },\n  \"groupBy\": {\n    \"field\": \"UserId\"\n  }\n}\n```\n\n\u003c/details\u003e\n\n### Validating Queries\n\n```typescript\nimport { isQueryValid } from '@jetstreamapp/soql-parser-js';\n\nconst invalidSoql = `SELECT UserId, COUNT(Id) Account`;\nconst validSoql = `SELECT UserId, COUNT(Id) Account`;\n\nconsole.log(isQueryValid(soql));\nconsole.log(isQueryValid(soql));\n```\n\n### Composing Queries\n\nBuild a `Query` data structure to have it converted back into a SOQL query.\n\nComposing a query will turn a Query object back to a SOQL query string. The exact same data structure returned from `parseQuery()` can be used,\nbut depending on your use-case, you may need to build your own data structure to compose a query.\nThese examples show building your own Query object with the minimum required fields.\n\nSome utility methods have been provided to make it easier to build the field data structures.\n\n**Note:** Some operators may be converted to uppercase (e.x. NOT, AND)\n\n**Note:** There are a number of fields populated on the Query object when `parseQuery()` is called that are not required to compose a query. Look at the examples below and the comments in the data model for more information.\n\n```typescript\nimport { composeQuery, getField, Query } from '@jetstreamapp/soql-parser-js';\n\n// Build a subquery\nconst oppLineItemsSubquery = {\n  fields: [\n    getField('Quantity'),\n    getField('ListPrice'),\n    getField({\n      field: 'UnitPrice',\n      relationships: ['PricebookEntry'],\n    }),\n    getField({\n      field: 'Name',\n      relationships: ['PricebookEntry'],\n    }),\n  ],\n  relationshipName: 'OpportunityLineItems',\n};\n\n// build the main query and add the subquery as a field\nconst soqlQuery: Query = {\n  fields: [\n    getField('Id'),\n    getField('Name'),\n    getField({\n      functionName: 'FORMAT',\n      parameters: 'Amount',\n      alias: 'MyFormattedAmount',\n    }),\n    getField({ subquery: oppLineItemsSubquery }),\n  ],\n  sObject: 'Opportunity',\n  where: {\n    left: {\n      field: 'CreatedDate',\n      operator: '\u003e',\n      value: 'LAST_N_YEARS:1',\n    },\n    operator: 'AND',\n    right: {\n      left: {\n        field: 'StageName',\n        operator: '=',\n        value: 'Closed Won',\n        // literalType is optional, but if set to STRING and our value is not already wrapped in \"'\", they will be added\n        // All other literalType values are ignored when composing a query\n        literalType: 'STRING',\n      },\n    },\n  },\n  limit: 150,\n};\n\nconst composedQuery = composeQuery(soqlQuery, { format: true });\n\nconsole.log(composedQuery);\n```\n\n**Results**\n\n```sql\nSELECT Id, Name, FORMAT(Amount) MyFormattedAmount,\n  (\n    SELECT Quantity, ListPrice, PricebookEntry.UnitPrice,\n      PricebookEntry.Name\n    FROM OpportunityLineItems\n  )\nFROM Opportunity\nWHERE CreatedDate \u003e LAST_N_YEARS:1\nAND StageName = 'Closed Won'\nLIMIT 150\n```\n\n### Composing a partial query\n\nStarting in version `4.4`, compose will not fail if there are missing `SELECT` and `FROM` clauses in your query.\n\nPartial compose support it supported without any additional steps.\n\n```typescript\nimport { Compose, parseQuery } from '@jetstreamapp/soql-parser-js';\n\nconst soql = `WHERE Name LIKE 'A%' AND MailingCity = 'California`;\nconst parsedQuery = parseQuery(soql, { allowPartialQuery: true });\n\n// Results of Parsed Query:\n/**\n{\n  where: {\n    left: { field: 'Name', operator: 'LIKE', value: \"'A%'\", literalType: 'STRING' },\n    operator: 'AND',\n    right: { left: { field: 'MailingCity', operator: '=', value: \"'California'\", literalType: 'STRING' } },\n  },\n}\n*/\n\nconst composedQuery = composeQuery(soqlQuery, { format: true });\n\nconsole.log(composedQuery);\n```\n\n**Results**\n\n```sql\nWHERE Name LIKE 'A%' AND MailingCity = 'California\n```\n\n\u003cdetails\u003e\n  \u003csummary\u003e\u003cb\u003eSee the alternate way to compose partial queries by calling the Compose class directly\u003c/b\u003e\u003c/summary\u003e\n\nIf you need to compose just a part of a query instead of the entire query, you can create an instance of the Compose class directly.\n\nFor example, if you just need the `WHERE` clause from a query as a string, you can do the following:\n\n```typescript\nimport { Compose, parseQuery } from '@jetstreamapp/soql-parser-js';\n\nconst soql = `SELECT Id FROM Account WHERE Name = 'Foo'`;\nconst parsedQuery = parseQuery(soql);\n\n// Results of Parsed Query:\n  // const parsedQuery = {\n  //   fields: [\n  //     {\n  //       type: 'Field',\n  //       field: 'Id',\n  //     },\n  //   ],\n  //   sObject: 'Account',\n  //   where: {\n  //     left: {\n  //       field: 'Name',\n  //       operator: '=',\n  //       value: \"'Foo'\",\n  //       literalType: 'STRING',\n  //     },\n  //   },\n  // };\n\n  // Create a new instance of the compose class and set the autoCompose to false to avoid composing the entire query\n  const composer = new Compose(parsedQuery, { autoCompose: false });\n\n\n  const whereClause = composer.parseWhereOrHavingClause(parsedQuery.where);\n\n  console.log(whereClause);\n}\n```\n\n#### Available methods on the `Compose` class\n\nThese are used internally, but are public and available for use.\n\n```typescript\nparseQuery(query: Query | Subquery): string;\nparseFields(fields: FieldType[]): { text: string; typeOfClause?: string[] }[];\nparseTypeOfField(typeOfField: FieldTypeOf): string[];\nparseWhereOrHavingClause(whereOrHaving: WhereClause | HavingClause, tabOffset = 0, priorConditionIsNegation = false): string;\nparseGroupByClause(groupBy: GroupByClause | GroupByClause[]): string;\nparseOrderBy(orderBy: OrderByClause | OrderByClause[]): string;\nparseWithDataCategory(withDataCategory: WithDataCategoryClause): string;\n```\n\n\u003c/details\u003e\n\n## Format Query\n\nThis function is provided as a convenience and just calls parse and compose.\n[Check out the demo](https://jetstreamapp.github.io/soql-parser-js/) to see the outcome of the various format options.\n\n```typescript\nimport { formatQuery } from '@jetstreamapp/soql-parser-js';\n\nconst query = `SELECT Id, Name, AccountNumber, AccountSource, AnnualRevenue, BillingAddress, BillingCity, BillingCountry, BillingGeocodeAccuracy, ShippingStreet, Sic, SicDesc, Site, SystemModstamp, TickerSymbol, Type, Website, (SELECT Id, Name, AccountId, Amount, CampaignId, CloseDate, CreatedById, Type FROM Opportunities), (SELECT Id, Name, AccountNumber, AccountSource, AnnualRevenue, BillingAddress, Website FROM ChildAccounts) FROM Account WHERE Name LIKE 'a%' OR Name LIKE 'b%' OR Name LIKE 'c%'`;\n\nconst formattedQuery1 = formatQuery(query);\nconst formattedQuery2 = formatQuery(query, {\n  fieldMaxLineLength: 20,\n  fieldSubqueryParensOnOwnLine: false,\n  whereClauseOperatorsIndented: true,\n});\nconst formattedQuery3 = formatQuery(query, { fieldSubqueryParensOnOwnLine: true, whereClauseOperatorsIndented: true });\n```\n\n```sql\n-- formattedQuery1\nSELECT Id, Name, AccountNumber, AccountSource, AnnualRevenue,\n\tBillingAddress, BillingCity, BillingCountry, BillingGeocodeAccuracy,\n\tShippingStreet, Sic, SicDesc, Site, SystemModstamp, TickerSymbol, Type,\n\tWebsite,\n\t(\n\t\tSELECT Id, Name, AccountId, Amount, CampaignId, CloseDate,\n\t\t\tCreatedById, Type\n\t\tFROM Opportunities\n\t),\n\t(\n\t\tSELECT Id, Name, AccountNumber, AccountSource, AnnualRevenue,\n\t\t\tBillingAddress, Website\n\t\tFROM ChildAccounts\n\t)\nFROM Account\nWHERE Name LIKE 'a%'\nOR Name LIKE 'b%'\nOR Name LIKE 'c%'\n\n-- formattedQuery2\nSELECT Id, Name,\n\tAccountNumber, AccountSource,\n\tAnnualRevenue, BillingAddress,\n\tBillingCity, BillingCountry,\n\tBillingGeocodeAccuracy, ShippingStreet,\n\tSic, SicDesc, Site,\n\tSystemModstamp, TickerSymbol, Type,\n\tWebsite,\n\t(SELECT Id, Name,\n\t\tAccountId, Amount, CampaignId,\n\t\tCloseDate, CreatedById, Type\n\tFROM Opportunities),\n\t(SELECT Id, Name,\n\t\tAccountNumber, AccountSource,\n\t\tAnnualRevenue, BillingAddress,\n\t\tWebsite\n\tFROM ChildAccounts)\nFROM Account\nWHERE Name LIKE 'a%'\n\tOR Name LIKE 'b%'\n\tOR Name LIKE 'c%'\n\n\n-- formattedQuery3\nSELECT Id, Name, AccountNumber, AccountSource, AnnualRevenue,\n\tBillingAddress, BillingCity, BillingCountry, BillingGeocodeAccuracy,\n\tShippingStreet, Sic, SicDesc, Site, SystemModstamp, TickerSymbol, Type,\n\tWebsite,\n\t(\n\t\tSELECT Id, Name, AccountId, Amount, CampaignId, CloseDate,\n\t\t\tCreatedById, Type\n\t\tFROM Opportunities\n\t),\n\t(\n\t\tSELECT Id, Name, AccountNumber, AccountSource, AnnualRevenue,\n\t\t\tBillingAddress, Website\n\t\tFROM ChildAccounts\n\t)\nFROM Account\nWHERE Name LIKE 'a%'\n\tOR Name LIKE 'b%'\n\tOR Name LIKE 'c%'\n```\n\n## Using in LWC\n\nThe easiest way to utilize this library in LWC is to deploy the compiled code as a web component in your org.\n\n:warning: The minified version ends up with `$A` characters in the output, which causes the deployment to SFD to fail, so we have created an unminified version of the library just for Salesforce.\n\n### Obtaining the build artifacts\n\nWe don't store the built artifacts on github, so you will need to obtain from NPM or run the build command yourself.\n\n#### Download from NPM\n\nDownload from [npm](https://www.npmjs.com/package/@jetstreamapp/soql-parser-js)\n\n**Either:**\n\n1. Go to the \"Code Tab\" on the [npm](https://www.npmjs.com/package/@jetstreamapp/soql-parser-js) listing\n   1. Navigate to `/dist/lwc.index.mjs`\n2. Install this project in an existing node library by running `npm install @jetstreamapp/soql-parser-js`\n   1. then navigating to the downloaded code in this folder: `node_modules/@jetstreamapp/soql-parser-js/dist/lwc`\n\n#### Build the files yourself\n\n1. Clone/download the repository from GitHub\n2. Ensure you have node installed (version 22 or higher)\n3. Install dependencies with `npm install`\n4. Run `npm build:lwc`\n5. The output will be placed in `/dist/lwc.index.mjs`\n\n### Deploying and Using in Salesforce\n\nCopy `index.mjs` into an LWC component.\n\nFor example:\n\n```\nsoqlParserJsLib\n- soqlParserJsLib.js \u003c--- copy the code here\n- soqlParserJsLib.js-meta.xml\n```\n\nAfter you have deployed the LWC, you can import it just like any other LWC import.\n\n```js\nimport { LightningElement } from 'lwc';\nimport { parseQuery } from 'c/soqlParserJsLib';\n\nexport default class SoqlParserJs extends LightningElement {\n  parsedQuery;\n\n  get parsedQueryString() {\n    return this.parsedQuery ? JSON.stringify(this.parsedQuery, null, 2) : '';\n  }\n\n  handleClick() {\n    this.parsedQuery = parseQuery(\"SELECT Id, Name FROM Account WHERE Industry = 'Technology'\");\n  }\n}\n```\n\n```html\n\u003ctemplate\u003e\n  \u003cbutton class=\"slds-button slds-button_neutral\" onclick=\"{handleClick}\"\u003eClick Me\u003c/button\u003e\n\n  \u003cp\u003eParsed Query: {parsedQueryString}\u003c/p\u003e\n\u003c/template\u003e\n```\n\n## CLI\n\nInstall globally or use `npx` to interact with the cli.\n\n### Available Commands\n\n- `soql-parser-js --help` (or using `npx`: `npx soql-parser-js --help`)\n- `soql-parser-js parse --help`\n- `soql-parser-js compose --help`\n- `soql-parser-js format --help`\n\n### Examples\n\n#### Parse\n\n`npx soql-parser-js parse \"SELECT Id FROM Account\"`\n\n```bash\n{\"fields\":[{\"type\":\"Field\",\"field\":\"Id\"}],\"sObject\":\"Account\"}\n```\n\n#### Compose\n\n`npx soql-parser-js compose \"{\\\"fields\\\":[{\\\"type\\\":\\\"Field\\\",\\\"field\\\":\\\"Id\\\"}],\\\"sObject\\\":\\\"Account\\\"}\"`\n\n```bash\nSELECT Id FROM Account\n```\n\n`npx soql-parser-js compose \"{\\\"fields\\\":[{\\\"type\\\":\\\"Field\\\",\\\"field\\\":\\\"Id\\\"}],\\\"sObject\\\":\\\"Account\\\"}\" --json` or -j\n\n```json\n{ \"query\": \"SELECT Id FROM Account\" }\n```\n\n#### Format\n\n`npx soql-parser-js format \"SELECT Name, COUNT(Id) FROM Account GROUP BY Name HAVING COUNT(Id) \u003e 1\"`\n\n```bash\nSELECT Name, COUNT(Id)\nFROM Account\nGROUP BY Name\nHAVING COUNT(Id) \u003e 1\n```\n\n`npx soql-parser-js format \"SELECT Name, COUNT(Id) FROM Account GROUP BY Name HAVING COUNT(Id) \u003e 1 -j`\n\n```json\n{ \"query\": \"SELECT Name, COUNT(Id)\\nFROM Account\\nGROUP BY Name\\nHAVING COUNT(Id) \u003e 1\" }\n```\n\n#### Is Valid\n\n`npx soql-parser-js valid \"SELECT Id FROM Account\"`\n\n```bash\ntrue\n```\n\n`npx soql-parser-js valid \"SELECT Id invalid FROM Account\"`\n\nℹ️ this returns an exit code of 1\n\n```bash\nfalse\n```\n\n`npx soql-parser-js valid \"SELECT Id FROM Account\" -j`\n\n```json\n{ \"isValid\": true }\n```\n\n`npx soql-parser-js valid \"SELECT Id invalid invalid FROM Account\" -j`\n\nℹ️ this returns an exit code of 0\n\n```json\n{ \"isValid\": false }\n```\n\n### List of options\n\n`soql-parser-js --help`\n\n```bash\nUsage: soql-parser-js [options] [command]\n\nOptions:\n  -h, --help                 output usage information\n\nCommands:\n  parse [options] \u003csql\u003e\n  compose [options] \u003cquery\u003e\n  format [options] \u003csql\u003e\n  valid \u003csql\u003e\n```\n\n`soql-parser-js parse --help`\n\n```bash\nUsage: parse [options] \u003csql\u003e\n\nOptions:\n  -a, --allow-apex     allow apex bind variables\n  -p, --allow-partial  allow partial queries\n  -i, --ignore-errors  ignore parse errors, return as much of query as possible\n  -h, --help           output usage information\n```\n\n`soql-parser-js compose --help`\n\n```bash\nUsage: compose [options] \u003cquery\u003e\n\nOptions:\n  -f, --format                   format output\n  -i --indent \u003cchars\u003e            number of tab characters to indent (default: 1)\n  -m --line-length \u003cchars\u003e       max number of characters per lins (default: 60)\n  -s --subquery-parens-new-line  subquery parens on own line\n  -k --keywords-new-line         new line after keywords\n  -j, --json                     output as JSON\n  -h, --help                     output usage information\n```\n\n`soql-parser-js format --help`\n\n```bash\nUsage: format [options] \u003csql\u003e\n\nOptions:\n  -a, --allow-apex     allow apex bind variables\n  -p, --allow-partial  allow partial queries\n  -i --indent \u003cchars\u003e            number of tab characters to indent (default: 1)\n  -m --line-length \u003cchars\u003e       max number of characters per lins (default: 60)\n  -s --subquery-parens-new-line  subquery parens on own line\n  -k --keywords-new-line         new line after keywords\n  -j, --json                     output as JSON\n  -h, --help                     output usage information\n```\n\n`soql-parser-js valid --help`\n\n```bash\nUsage: valid [options] \u003csql\u003e\n\nOptions:\n  -a, --allow-apex     allow apex bind variables\n  -p, --allow-partial  allow partial queries\n  -j, --json  output as JSON\n  -h, --help  output usage information\n```\n\n## Data Models\n\n### Query\n\n```typescript\nexport type LogicalOperator = 'AND' | 'OR' | 'NOT';\nexport type Operator = '=' | '!=' | '\u003c=' | '\u003e=' | '\u003e' | '\u003c' | 'LIKE' | 'IN' | 'NOT IN' | 'INCLUDES' | 'EXCLUDES';\nexport type FieldTypeOfConditionType = 'WHEN' | 'ELSE';\nexport type GroupSelector = 'ABOVE' | 'AT' | 'BELOW' | 'ABOVE_OR_BELOW';\nexport type ForClause = 'VIEW' | 'UPDATE' | 'REFERENCE';\nexport type UpdateClause = 'TRACKING' | 'VIEWSTAT';\nexport type LiteralType =\n  | 'STRING'\n  | 'INTEGER'\n  | 'DECIMAL'\n  | 'INTEGER_WITH_CURRENCY_PREFIX'\n  | 'DECIMAL_WITH_CURRENCY_PREFIX'\n  | 'BOOLEAN'\n  | 'NULL'\n  | 'DATETIME'\n  | 'DATE'\n  | 'DATE_LITERAL'\n  | 'DATE_N_LITERAL'\n  | 'APEX_BIND_VARIABLE';\nexport type FieldType =\n  | Field\n  | FieldWithAlias\n  | FieldFunctionExpression\n  | FieldRelationship\n  | FieldRelationshipWithAlias\n  | FieldSubquery\n  | FieldTypeOf;\nexport type OrderByCriterion = 'ASC' | 'DESC';\nexport type NullsOrder = 'FIRST' | 'LAST';\nexport type GroupByType = 'CUBE' | 'ROLLUP';\nexport type DateLiteral =\n  | 'YESTERDAY'\n  | 'TODAY'\n  | 'TOMORROW'\n  | 'LAST_WEEK'\n  | 'THIS_WEEK'\n  | 'NEXT_WEEK'\n  | 'LAST_MONTH'\n  | 'THIS_MONTH'\n  | 'NEXT_MONTH'\n  | 'LAST_90_DAYS'\n  | 'NEXT_90_DAYS'\n  | 'THIS_QUARTER'\n  | 'LAST_QUARTER'\n  | 'NEXT_QUARTER'\n  | 'THIS_YEAR'\n  | 'LAST_YEAR'\n  | 'NEXT_YEAR'\n  | 'THIS_FISCAL_QUARTER'\n  | 'LAST_FISCAL_QUARTER'\n  | 'NEXT_FISCAL_QUARTER'\n  | 'THIS_FISCAL_YEAR'\n  | 'LAST_FISCAL_YEAR'\n  | 'NEXT_FISCAL_YEAR';\n\nexport type DateNLiteral =\n  | 'YESTERDAY'\n  | 'NEXT_N_DAYS'\n  | 'LAST_N_DAYS'\n  | 'N_DAYS_AGO'\n  | 'NEXT_N_WEEKS'\n  | 'LAST_N_WEEKS'\n  | 'N_WEEKS_AGO'\n  | 'NEXT_N_MONTHS'\n  | 'LAST_N_MONTHS'\n  | 'N_MONTHS_AGO'\n  | 'NEXT_N_QUARTERS'\n  | 'LAST_N_QUARTERS'\n  | 'N_QUARTERS_AGO'\n  | 'NEXT_N_YEARS'\n  | 'LAST_N_YEARS'\n  | 'N_YEARS_AGO'\n  | 'NEXT_N_FISCAL_QUARTERS'\n  | 'LAST_N_FISCAL_QUARTERS'\n  | 'N_FISCAL_QUARTERS_AGO'\n  | 'NEXT_N_FISCAL_YEARS'\n  | 'LAST_N_FISCAL_YEARS'\n  | 'N_FISCAL_YEARS_AGO';\n\nexport interface Field {\n  type: 'Field';\n  field: string;\n  alias?: string;\n}\n\nexport interface FieldWithAlias extends Field {\n  objectPrefix: string;\n  rawValue: string;\n}\n\nexport interface FieldFunctionExpression {\n  type: 'FieldFunctionExpression';\n  functionName: string;\n  parameters: (string | FieldFunctionExpression)[];\n  alias?: string;\n  isAggregateFn?: boolean; // not required for compose, will be populated if SOQL is parsed\n  rawValue?: string; // not required for compose, will be populated if SOQL is parsed\n}\n\nexport interface FieldRelationship {\n  type: 'FieldRelationship';\n  field: string;\n  relationships: string[];\n  rawValue?: string; // not required for compose, will be populated if SOQL is parsed with the raw value of the entire field\n}\n\nexport interface FieldRelationshipWithAlias extends FieldRelationship {\n  objectPrefix: string;\n  alias: string;\n}\n\nexport interface FieldSubquery {\n  type: 'FieldSubquery';\n  subquery: Subquery;\n}\n\nexport interface FieldTypeOf {\n  type: 'FieldTypeof';\n  field: string;\n  conditions: FieldTypeOfCondition[];\n}\n\nexport interface FieldTypeOfCondition {\n  type: FieldTypeOfConditionType;\n  objectType?: string; // not present when ELSE\n  fieldList: string[];\n}\n\nexport interface QueryBase {\n  fields?: FieldType[];\n  sObjectAlias?: string;\n  usingScope?: string;\n  where?: WhereClause;\n  limit?: number;\n  offset?: number;\n  groupBy?: GroupByClause;\n  orderBy?: OrderByClause | OrderByClause[];\n  withDataCategory?: WithDataCategoryClause;\n  withSecurityEnforced?: boolean;\n  withAccessLevel?: boolean;\n  for?: ForClause;\n  update?: UpdateClause;\n}\n\nexport interface Query extends QueryBase {\n  sObject?: string;\n}\n\nexport interface Subquery extends QueryBase {\n  relationshipName: string;\n  sObjectPrefix?: string[];\n}\n\nexport type WhereClause = WhereClauseWithoutOperator | WhereClauseWithRightCondition;\n\nexport interface WhereClauseWithoutOperator {\n  left: ConditionWithValueQuery;\n}\n\nexport interface WhereClauseWithRightCondition extends WhereClauseWithoutOperator {\n  operator: LogicalOperator;\n  right: WhereClause;\n}\n\nexport type Condition =\n  | ValueCondition\n  | ValueWithDateLiteralCondition\n  | ValueWithDateNLiteralCondition\n  | ValueFunctionCondition\n  | NegationCondition;\n\nexport type ConditionWithValueQuery = Condition | ValueQueryCondition;\n\nexport interface OptionalParentheses {\n  openParen?: number;\n  closeParen?: number;\n}\n\nexport interface ValueCondition extends OptionalParentheses {\n  field: string;\n  operator: Operator;\n  value: string | string[];\n  literalType?: LiteralType | LiteralType[];\n}\n\nexport interface ValueWithDateLiteralCondition extends OptionalParentheses {\n  field: string;\n  operator: Operator;\n  value: DateLiteral | DateLiteral[];\n  literalType?: 'DATE_LITERAL' | 'DATE_LITERAL'[];\n}\n\nexport interface ValueWithDateNLiteralCondition extends OptionalParentheses {\n  field: string;\n  operator: Operator;\n  value: string | string[];\n  literalType?: 'DATE_N_LITERAL' | 'DATE_N_LITERAL'[];\n  dateLiteralVariable: number | number[];\n}\n\nexport interface ValueQueryCondition extends OptionalParentheses {\n  field: string;\n  operator: Operator;\n  valueQuery: Query;\n}\n\nexport interface ValueFunctionCondition extends OptionalParentheses {\n  fn: FunctionExp;\n  operator: Operator;\n  value: string | string[];\n  literalType?: LiteralType | LiteralType[];\n}\n\nexport interface NegationCondition {\n  openParen: number;\n}\n\nexport type OrderByClause = OrderByFieldClause | OrderByFnClause;\n\nexport interface OrderByOptionalFieldsClause {\n  order?: OrderByCriterion;\n  nulls?: NullsOrder;\n}\n\nexport interface OrderByFieldClause extends OrderByOptionalFieldsClause {\n  field: string;\n}\n\nexport interface OrderByFnClause extends OrderByOptionalFieldsClause {\n  fn: FunctionExp;\n}\n\nexport type GroupByClause = GroupByFieldClause | GroupByFnClause;\n\nexport interface GroupByOptionalFieldsClause {\n  having?: HavingClause;\n}\n\nexport interface GroupByFieldClause extends GroupByOptionalFieldsClause {\n  field: string | string[];\n}\n\nexport interface GroupByFnClause extends GroupByOptionalFieldsClause {\n  fn: FunctionExp;\n}\n\nexport type HavingClause = HavingClauseWithoutOperator | HavingClauseWithRightCondition;\n\nexport interface HavingClauseWithoutOperator {\n  left: Condition;\n}\n\nexport interface HavingClauseWithRightCondition extends HavingClauseWithoutOperator {\n  operator: LogicalOperator;\n  right: HavingClause;\n}\n\nexport interface FunctionExp {\n  rawValue?: string; // only used for compose fields if useRawValueForFn=true. Should be formatted like this: Count(Id)\n  functionName?: string; // only used for compose fields if useRawValueForFn=false, will be populated if SOQL is parsed\n  alias?: string;\n  parameters?: (string | FunctionExp)[]; // only used for compose fields if useRawValueForFn=false, will be populated if SOQL is parsed\n  isAggregateFn?: boolean; // not used for compose, will be populated if SOQL is parsed\n}\n\nexport interface WithDataCategoryClause {\n  conditions: WithDataCategoryCondition[];\n}\n\nexport interface WithDataCategoryCondition {\n  groupName: string;\n  selector: GroupSelector;\n  parameters: string[];\n}\n```\n\n## Contributing\n\nAll contributions are welcome on the project. Please read the [contribution guidelines](https://github.com/jetstreamapp/soql-parser-js/blob/master/CONTRIBUTING.md).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjetstreamapp%2Fsoql-parser-js","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjetstreamapp%2Fsoql-parser-js","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjetstreamapp%2Fsoql-parser-js/lists"}