Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Changed spree filters types to write every app's declarations in one run
Damian Legawiecb5208d0ab283
diff --git a/.changeset/filters-types-every-app.md b/.changeset/filters-types-every-app.mdnew file mode 100644index 0000000000..71ff272b6e--- /dev/null+++ b/.changeset/filters-types-every-app.md@@ -0,0 +1,5 @@+---+"@spree/cli": minor+---++`spree filters types` now writes declarations into every app under `apps/` in one run, each for the SDK that app uses. `--api` and `--out` write a single file for an app outside that layout.diff --git a/docs/developer/cli/quickstart.mdx b/docs/developer/cli/quickstart.mdxindex e091c9485a..003e42c40f 100644--- a/docs/developer/cli/quickstart.mdx+++ b/docs/developer/cli/quickstart.mdx@@ -253,16 +253,14 @@ spree generate migration AddPositionToSpreeBrands position:integer # Rails buil### `spree filters types`-Generate TypeScript declarations for your app's list filters, so the SDKs accept and autocomplete the filters and sort fields your app adds. It reads them from the running app and writes one file per run, so run it once for each app that uses an SDK, and again after you change a filter.+Generate TypeScript declarations for your app's list filters, so the SDKs accept and autocomplete the filters and sort fields your app adds. It reads them from the running app and writes `src/types/spree-filters.d.ts` into each app under `apps/` (storefront, dashboard, seller panel), for the SDK that app uses. Run it again after you change a filter.```bash-spree filters types --api store --out apps/storefront/src/types/spree-filters.d.ts # @spree/sdk-spree filters types --api admin --out apps/dashboard/src/types/spree-filters.d.ts # @spree/admin-sdk-spree filters types --api seller --out apps/seller-dashboard/src/types/spree-filters.d.ts # @spree/seller-sdk+spree filters types # every app under apps/+spree filters types --api store --out ../my-storefront/src/types/spree-filters.d.ts # one app elsewhere+spree filters types --from filter-tables.json # from `bin/rails spree:api:filter_tables` output```-`--from <file>` reads the tables from `bin/rails spree:api:filter_tables` output instead of the running app.-See [using your own filters from TypeScript](/developer/core-concepts/search-filtering#using-your-own-filters-from-typescript).### `spree migrate`diff --git a/docs/developer/core-concepts/search-filtering.mdx b/docs/developer/core-concepts/search-filtering.mdxindex 23c3591f0a..3770db7ddf 100644--- a/docs/developer/core-concepts/search-filtering.mdx+++ b/docs/developer/core-concepts/search-filtering.mdx@@ -288,35 +288,31 @@ Every entry is a filter any caller of that API can run. Keep back-office fieldsThe SDKs type each `list()` call with the filters Spree itself declares. A filter your app adds works in the API at once, but TypeScript rejects it until it is declared, because the published types cannot know about it. There are three ways to use it.-**Generate the declarations (recommended).** This reads your app's filters, the ones Spree declares and the ones you added, and writes a declaration file for one SDK. Each frontend uses its own SDK, so generate a file for each app in your project, from the project root:--| App | SDK | `--api` |-|---|---|---|-| `apps/storefront` | `@spree/sdk` | `store` |-| `apps/dashboard` | `@spree/admin-sdk` | `admin` |-| `apps/seller-dashboard` (marketplaces) | `@spree/seller-sdk` | `seller` |+**Generate the declarations (recommended).** This reads your app's filters, the ones Spree declares and the ones you added, and writes a declaration file into each app in your project, for the SDK that app uses. Run it from the project root:<Tabs><Tab title="Spree CLI">```bash- spree filters types --api store --out apps/storefront/src/types/spree-filters.d.ts- spree filters types --api admin --out apps/dashboard/src/types/spree-filters.d.ts- spree filters types --api seller --out apps/seller-dashboard/src/types/spree-filters.d.ts+ spree filters types```</Tab><Tab title="Without CLI">```bash- cd server- bin/rails spree:api:filter_tables > ../filter-tables.json- cd ..- npx @spree/cli filters types --from filter-tables.json --api store --out apps/storefront/src/types/spree-filters.d.ts- npx @spree/cli filters types --from filter-tables.json --api admin --out apps/dashboard/src/types/spree-filters.d.ts- npx @spree/cli filters types --from filter-tables.json --api seller --out apps/seller-dashboard/src/types/spree-filters.d.ts+ (cd server && bin/rails spree:api:filter_tables > ../filter-tables.json)+ npx @spree/cli filters types --from filter-tables.json```</Tab></Tabs>-Run them again after you add or change a filter, and commit the generated files with the app code that uses them. Match `--api` to the app: a storefront file generated with `--api admin` compiles, but declares the Admin API's filters. After that, every `list()` call accepts and autocompletes your filters and sort fields, and a misspelled one is still a compile error.+It writes `src/types/spree-filters.d.ts` into each app that exists:++| App | SDK |+|---|---|+| `apps/storefront` | `@spree/sdk` |+| `apps/dashboard` | `@spree/admin-sdk` |+| `apps/seller-dashboard` (marketplaces) | `@spree/seller-sdk` |++Run it again after you add or change a filter, and commit the generated files with the app code that uses them. For an app outside this layout, write one file for the SDK it uses: `spree filters types --api store --out path/to/spree-filters.d.ts`. After that, every `list()` call accepts and autocompletes your filters and sort fields, and a misspelled one is still a compile error.**Send it unchecked.** Filters inside `q` are sent as given, without type checking or autocomplete:diff --git a/docs/developer/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdxindex 87c5edd1da..68c5a2ef79 100644--- a/docs/developer/upgrades/5.6-to-6.0.mdx+++ b/docs/developer/upgrades/5.6-to-6.0.mdx@@ -1035,10 +1035,10 @@ Each `list()` method now takes the filters and sort fields its endpoint accepts.- **Filters your backend adds are compile errors until you declare them.** The published types list only the filters Spree itself declares. Any filter or scope your backend adds (through `Spree.ransack.add_attribute`, `add_scope` or a model decorator) still works in the API, but TypeScript rejects the key. Generate the declarations from your app, and run the command again whenever a filter changes:```bash- spree filters types --api store --out apps/storefront/src/types/spree-filters.d.ts+ spree filters types```- Generate one for the dashboard (`--api admin --out apps/dashboard/src/types/spree-filters.d.ts`) and the seller panel (`--api seller`) too, if they use your filters. For a one-off filter, send it inside `q` instead (`list({ q: { erp_id_eq: 'ERP-1' } })`), which is not type checked. See [using your own filters from TypeScript](/developer/core-concepts/search-filtering#using-your-own-filters-from-typescript) for both, and for declaring filters by hand.+ It writes a declaration file into each app under `apps/`, for the SDK that app uses (the storefront, the dashboard and the seller panel). For a one-off filter, send it inside `q` instead (`list({ q: { erp_id_eq: 'ERP-1' } })`), which is not type checked. See [using your own filters from TypeScript](/developer/core-concepts/search-filtering#using-your-own-filters-from-typescript) for both, and for declaring filters by hand.- **Amount filters take decimal strings.** `price_gte`, `price_lte` and the other money filters are typed as strings, like every money value in 6.0. Send `'20.00'`, not `20`.diff --git a/packages/cli/src/commands/filters.ts b/packages/cli/src/commands/filters.tsindex fc1983a48c..1f0e0f119e 100644--- a/packages/cli/src/commands/filters.ts+++ b/packages/cli/src/commands/filters.ts@@ -1,5 +1,5 @@-import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'-import { dirname, resolve } from 'node:path'+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'+import { dirname, join, relative, resolve } from 'node:path'import * as p from '@clack/prompts'import { type FilterSpec, renderAppFilterTypes } from '@spree/sdk-core'import type { Command } from 'commander'@@ -10,15 +10,27 @@ const APIS = ['store', 'admin', 'seller'] as consttype Api = (typeof APIS)[number]interface TypesOptions {- api: Api- out: string+ api?: Api+ out?: stringfrom?: string}+/** The apps `create-spree-app` scaffolds under `apps/`, and the SDK each uses. */+export const APP_SDKS: { dir: string; api: Api }[] = [+ { dir: 'storefront', api: 'store' },+ { dir: 'dashboard', api: 'admin' },+ { dir: 'seller-dashboard', api: 'seller' },+]+const APP_TYPES_FILE = join('src', 'types', 'spree-filters.d.ts')+const DEFAULT_OUT = APP_TYPES_FILE+/*** The SDKs type list filters from Spree's own allowlists, so a filter an app* adds is a type error until declared. This writes that declaration from the* app's live filter tables, so it lists exactly what the app's API accepts.+ *+ * Without `--api` or `--out` it writes one file into each app under `apps/`,+ * for the SDK that app uses; with them, one file where asked.*/export function registerFiltersCommand(program: Command): void {const filters = program.command('filters').description("Work with your app's list filters")@@ -26,28 +38,55 @@ export function registerFiltersCommand(program: Command): void {filters.command('types').description("Generate TypeScript declarations for your app's own list filters and sort fields")- .option('--api <api>', `which SDK to declare them for (${APIS.join(', ')})`, 'store')- .option('--out <file>', 'where to write the declarations', 'src/types/spree-filters.d.ts')+ .option(+ '--api <api>',+ `write one file, for this SDK (${APIS.join(', ')}), instead of one per app under apps/`,+ )+ .option('--out <file>', `where to write that one file (default: ${DEFAULT_OUT})`).option('--from <file>','read the filter tables from a file written by `bin/rails spree:api:filter_tables` instead of the running app',).action(async (options: TypesOptions) => {- if (!APIS.includes(options.api)) {+ if (options.api && !APIS.includes(options.api)) {p.log.error(`Unknown API "${options.api}". Use one of: ${APIS.join(', ')}.`)process.exitCode = 1return}- const tables = options.from- ? readFileSync(resolve(options.from), 'utf8')- : await rakeTask('spree:api:filter_tables', detectProject().projectDir)- const spec = parseFilterTables(tables)[options.api]+ const single = options.api !== undefined || options.out !== undefined+ // With --from the app need not run in this CLI's Docker setup; the+ // current folder is then taken as the project root.+ const projectDir = single && options.from ? undefined : projectRoot(Boolean(options.from))+ const targets = single+ ? [{ api: options.api ?? 'store', out: resolve(options.out ?? DEFAULT_OUT) }]+ : APP_SDKS.filter(({ dir }) => existsSync(join(projectDir as string, 'apps', dir))).map(+ ({ dir, api }) => ({+ api,+ out: join(projectDir as string, 'apps', dir, APP_TYPES_FILE),+ }),+ )- const out = resolve(options.out)- mkdirSync(dirname(out), { recursive: true })- writeFileSync(out, renderAppFilterTypes(spec, options.api))- p.log.success(`Wrote ${options.out}. Run this again after you change a filter.`)+ if (targets.length === 0) {+ p.log.error(+ 'No apps found under apps/. Pass --api and --out to write the declarations somewhere else.',+ )+ process.exitCode = 1+ return+ }++ const tables = parseFilterTables(+ options.from+ ? readFileSync(resolve(options.from), 'utf8')+ : await rakeTask('spree:api:filter_tables', projectDir as string),+ )++ for (const { api, out } of targets) {+ mkdirSync(dirname(out), { recursive: true })+ writeFileSync(out, renderAppFilterTypes(tables[api], api))+ p.log.success(`Wrote ${projectDir ? relative(projectDir, out) : out} (${api} API)`)+ }+ p.log.info('Run this again after you change a filter.')})}@@ -64,3 +103,12 @@ export function parseFilterTables(output: string): Record<Api, FilterSpec> {return JSON.parse(json) as Record<Api, FilterSpec>}++function projectRoot(fromFile: boolean): string {+ try {+ return detectProject().projectDir+ } catch (error) {+ if (fromFile) return process.cwd()+ throw error+ }+}diff --git a/packages/cli/tests/filters.test.ts b/packages/cli/tests/filters.test.tsindex 4299f34f5e..98f822faa4 100644--- a/packages/cli/tests/filters.test.ts+++ b/packages/cli/tests/filters.test.ts@@ -1,4 +1,4 @@-import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { Command } from 'commander'@@ -6,11 +6,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'import { parseFilterTables, registerFiltersCommand } from '../src/commands/filters'import { rakeTask } from '../src/docker'+let projectDir = '/proj'vi.mock('../src/context', () => ({- detectProject: () => ({ mode: 'docker', projectDir: '/proj', port: 3000 }),+ detectProject: () => ({ mode: 'docker', projectDir, port: 3000 }),}))vi.mock('../src/docker', () => ({ rakeTask: vi.fn() }))-vi.mock('@clack/prompts', () => ({ log: { success: vi.fn(), error: vi.fn() } }))+vi.mock('@clack/prompts', () => ({ log: { success: vi.fn(), error: vi.fn(), info: vi.fn() } }))const predicates = {text: [@@ -69,6 +70,31 @@ describe('spree filters types', () => {beforeEach(() => {vi.clearAllMocks()dir = mkdtempSync(join(tmpdir(), 'spree-filters-'))+ projectDir = '/proj'+ })++ it('writes one file into each app under apps/, for the SDK it uses', async () => {+ projectDir = dir+ mkdirSync(join(dir, 'apps', 'storefront'), { recursive: true })+ mkdirSync(join(dir, 'apps', 'dashboard'), { recursive: true })+ vi.mocked(rakeTask).mockResolvedValue(taskOutput)++ await run([])++ expect(rakeTask).toHaveBeenCalledTimes(1)+ const types = (app: string) => join(dir, 'apps', app, 'src', 'types', 'spree-filters.d.ts')+ expect(readFileSync(types('storefront'), 'utf8')).toContain("declare module '@spree/sdk'")+ expect(readFileSync(types('dashboard'), 'utf8')).toContain("declare module '@spree/admin-sdk'")+ expect(existsSync(types('seller-dashboard'))).toBe(false)+ })++ it('says so when the project has no apps', async () => {+ projectDir = dir+ await run([])++ expect(rakeTask).not.toHaveBeenCalled()+ expect(process.exitCode).toBe(1)+ process.exitCode = undefined})it("declares the app's filters and sort fields for the chosen SDK", async () => {