@malloydata/malloyyo 0.2.51 → 0.2.52

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.
@@ -556,6 +556,12 @@ export function Given({ name, ...rest }) {
556
556
  changes re-run immediately and no buttons show. */
557
557
  export function Controls({ style, children }) {
558
558
  const { autorun, apply, reset, dirty } = useDashboard();
559
+ // Nothing to put in the bar — no controls, and no Apply/Reset because the
560
+ // dashboard autoruns — so draw no bar. A dashboard whose only given is one
561
+ // the HOST fills ($MALLOYYO_EMAIL) has an empty spec list by design, and an
562
+ // empty bordered strip under the title reads as a control that failed to
563
+ // load rather than as one that was never the reader's to set.
564
+ if (!children && autorun && givenSpecs().length === 0) return null;
559
565
  return (
560
566
  <div
561
567
  style={{
package/dist/index.js CHANGED
@@ -7,7 +7,7 @@ import { resolve as resolve4 } from "node:path";
7
7
  // src/config.ts
8
8
  import { readFileSync, existsSync } from "node:fs";
9
9
  import { join } from "node:path";
10
- var KNOWN_KEYS = /* @__PURE__ */ new Set(["analytics", "targets", "image_hosts"]);
10
+ var KNOWN_KEYS = /* @__PURE__ */ new Set(["analytics", "targets", "image_hosts", "test_givens"]);
11
11
  function isTarget(v) {
12
12
  return typeof v === "object" && v !== null && typeof v.url === "string";
13
13
  }
@@ -203,7 +203,7 @@ var contentFiles = {
203
203
  "dashboards/charts.md": "# Charts (`# bar_chart`, `# line_chart`, \u2026)\n\nThe renderer's built-in chart tags cover most dashboard tiles. Tag a nested view\nand it draws:\n\n```malloy\nnest:\n # bar_chart\n sales_by_brand\n # line_chart\n sales_by_month\n```\n\nRelated: `yo_help dashboards/grid-layout` (where tiles sit),\n`dashboards/vega-charts` (`<VegaChart>`, for shapes these tags can't express),\n`dashboards/authoring` (the dashboard file itself).\n\n## Channels: name them, don't leave them to be guessed\n\nA chart has three channels \u2014 **x** (the category axis), **y** (the value), and\n**series** (the colour split). Set them on the tag:\n\n```malloy\n# bar_chart { x=weekday y=drunk }\n# bar_chart { x=nickname y=flight_count series=destination }\n# line_chart { x=sale_date y=['sales', 'cost'] }\n```\n\nLeft unset, the renderer infers them: x prefers a time dimension and otherwise\ntakes the first dimension, y takes the first aggregate, and **series takes any\ndimension left over**. That last rule is the one that surprises people \u2014 see\nbelow. Naming `x` and `y` explicitly costs one line and removes the guesswork.\n\nOther properties: `.stack`, `.size` (`spark`/`xs`/`sm`/`md`/`lg`/`xl`/`2xl`, or\n`size.width` / `size.height`), `.x.limit`, `.series.limit`, and `.independent`\non any channel for nested charts.\n\n## THE RULE: charts count DIMENSIONS, not columns\n\nA chart can carry **one x dimension and one series dimension**. The renderer\ncounts the *dimensions* in the result (`group_by` fields \u2014 not aggregates) and:\n\n- **two dimensions, only `x` named** \u2192 the spare one is promoted to a colour\n series, whether or not you wanted a legend\n- **three or more dimensions, none tagged `series`** \u2192 it refuses:\n *\"Too many dimensions. A bar chart can have at most 2 dimensions: 1 for the x\n axis, and 1 for the series. To use 3+ dimensions, explicitly tag multiple\n fields as series.\"*\n\nThat last sentence is the escape hatch: 3+ dimensions is legal if you say which\nones are the series. What is NOT legal is leaving it to be inferred. If you\ngenuinely want a third dimension in the picture, name it; if you don't, the\nproblem is that a field you didn't think of as a dimension is one.\n\nAggregates are exempt. A result can carry as many measures as you like \u2014 only\nthe ones named in `y` (or the first, if `y` is unset) get plotted, and the rest\nare ignored rather than turned into channels.\n\n**`# hidden` does not exempt a dimension from this count.** It hides a field in\ntables, `big_value` comparisons and `# link` targets; it has no effect on chart\nchannel assignment. A `# hidden` group_by is still a dimension and will still\nbecome a series.\n\n## Sorting a named axis (the common case this rule makes hard)\n\nYou want an axis labelled `Sunday \u2026 Saturday`, or `Jan \u2026 Dec`, in *that* order \u2014\nnot alphabetical. The label has to be a string, but the sort key is a number, and\nthe naive fixes both fail:\n\n```malloy\n// WRONG \u2014 two dimensions: weekday_num becomes a colour series.\ngroup_by:\n # hidden\n weekday_num is day_of_week(exit_date)\n weekday is pick 'Sunday' when day_of_week(exit_date) = 1 \u2026\n```\n\n```malloy\n// ALSO WRONG \u2014 a `select:` stage is a projection, so it has no measures:\n// every column becomes a dimension and a 3-column result is rejected.\n} -> {\n select: weekday is pick 'Sunday' when weekday_num = 1 \u2026 , drunk, avg_price\n}\n```\n\n**Make the sort key a MEASURE.** Measures aren't dimensions, so a sort key\nexpressed as one can never be promoted to a channel:\n\n```malloy\n# bar_chart { x=weekday y=drunk }\nview: by_weekday is {\n group_by: weekday is\n pick 'Sunday' when day_of_week(exit_date) = 1\n pick 'Monday' when day_of_week(exit_date) = 2\n \u2026\n else 'Saturday'\n aggregate:\n drunk\n weekday_sort is min(day_of_week(exit_date)) // orders rows; never a channel\n order_by: weekday_sort asc\n}\n```\n\nOne dimension reaches the chart, the rows arrive in the order you asked for, and\na bar chart preserves query row order for a categorical axis. The same shape\nworks for months (`min(month(date))`), fiscal periods, size buckets, and any\nother \"display a name, sort by a number\" axis.\n\n> `min()` because a sort key needs *some* aggregate function and every row in the\n> group shares the value; `max()` is equally fine.\n\n## Deciding which tile is a chart at all\n\n- **Ranked categories** (top brands, regions by volume) \u2014 `# bar_chart`, ordered\n by the measure. Query order is the bar order.\n- **A value over time** \u2014 `# line_chart` with the time dimension as `x`.\n- **A wide detail table** \u2014 no chart tag. Charting eight columns is worse than\n showing them; give the tile `# colspan=6` instead and label the columns.\n- **Flat data** \u2014 if every bar is within a few percent of the others, the chart\n is saying \"no pattern here\" at the cost of a card. Consider whether the tile\n earns its place.\n\n## Trends by period: drop the incomplete one\n\nA by-year or by-month trend whose final period is partial draws a cliff that\nreads as collapse. Filter to complete periods, using a cutoff that comes from\nthe DATA (e.g. a snapshot/max-date column carried on a joined dimension), not\nfrom the result set \u2014 deriving it from the visible rows will wrongly declare a\nperiod partial as soon as a filter narrows the data.\n\n## Validate\n\n`malloyyo lint` compiles each dashboard and its tiles, but it does not render\nthem \u2014 a chart that compiles can still throw \"Too many dimensions\" in the\nbrowser. See it with `malloyyo dashboard dev`, which runs the queries\nserver-side and renders the real result.\n",
204
204
  "dashboards/custom-components.md": '---\ndescription: Custom dashboard UI \u2014 a flat dashboards/<name>.jsx|tsx sibling composing @malloyyo/dashboard widgets/hooks/helpers with your own React\n---\n\n# Custom dashboard components (`dashboards/<name>.jsx`)\n\nThe default UI (auto-rendered controls + panel) covers most dashboards. When it\nisn\'t enough, add ONE file \u2014 a **flat sibling** `dashboards/<name>.jsx` (or\n`.tsx`) next to the dashboard\'s `dashboards/<name>.malloy` (same basename) \u2014 that\ncomposes the runtime\'s widgets/hooks with your own React. You own layout, copy,\nand theming; the `.malloy` file still owns every query and filter. See also\n`yo_help dashboards/authoring` and `dashboards/vega-charts`.\n\n```tsx\nimport React from "react";\nimport { Controls, Given, Search, Select, TimeRange, Panel, filters, useGiven } from "@malloyyo/dashboard";\n\nexport default function Dashboard({ dashboard, givens }) {\n return (\n <div style={{ maxWidth: 860, margin: "0 auto", padding: 24 }}>\n <h1>{dashboard.title}</h1>\n <Controls>\n <Given name="STATE" /> {/* picks the control from the declaration */}\n <Search given="NAME" /> {/* committing input + typeahead + validation */}\n <TimeRange given="PERIOD" presets={[\n { value: "", text: "All time" },\n { value: filters.lastN(1, "day"), text: "Last day" },\n { value: filters.lastN(1, "week"), text: "Last week" },\n { value: filters.lastN(1, "month"), text: "Last month" },\n ]} /> {/* "Custom range\u2026" is always appended */}\n <Select given="MIN_SAMPLE"\n options={[10, 200, 1000].map(n => ({ value: filters.greaterThan(n), text: `> ${n}` }))} />\n </Controls>\n <Panel givens={givens} /> {/* the dashboard itself (its tiles/query) */}\n <Panel query="baby_names -> births_by_decade" givens={givens} /> {/* a specific query */}\n </div>\n );\n}\n```\n\nFrom `@malloyyo/dashboard` (also handed to the component as props):\n- **Widgets** (headless-ish; restyle via className/style or the `--dash-*` CSS\n vars \u2014 see Theming below): `<Controls/>` (all givens, or compose children;\n grows Apply/Reset under `autorun=false`), `<Given name/>`,\n `<Select given [options]/>`, `<Search given/>` (committing input + typeahead +\n inline \u2715 clear), `<MultiSelect given [options]/>` (chip multi-select for a\n `filter<string>` \u2014 commits an exact-match list via `filters.oneOf`),\n `<Range given [min max]/>`, `<TimeRange given [presets]/>` (temporal presets +\n custom range), `<Checkbox given/>` (bound to a boolean given),\n `<VegaChart spec query|malloy|data givens/>` (a Vega-Lite chart over query\n rows \u2014 see `yo_help dashboards/vega-charts`)\n- **Hooks**: `useGiven(name)` \u2192 {value, set, spec};\n `useOptions(name, typed?)` \u2192 {options, loading} (typeahead);\n `useQuery({query|malloy, givens})` \u2192 {rows, loading, error} \u2014 plain rows\n for your own visuals;\n `useUrlState(key, initial)` \u2192 [value, setValue] \u2014 shareable view-state (below)\n- **Helpers**: `filters.oneOf/contains/between/atLeast/\u2026` build\n filter-expression strings with correct escaping; temporal:\n `filters.lastN(7, "day")` \u2192 `\'7 days\'`, `filters.dateRange("2026-01-01",\n "2026-07-01")`, `filters.afterDate/beforeDate`; read back with\n `filters.values/numberRange/threshold/inLast/temporalRange`;\n `filters.isValid(type, src)` checks typed input.\n Never hand-concatenate a filter string.\n **Escaping rule for custom controls:** a filter given\'s value is an\n EXPRESSION, so committing a raw column value is wrong the moment it contains\n a comma/percent/dash (\'Tesla, Inc.\' parses as two alternatives and matches\n nothing). Commit `filters.oneOf(value)` (exact) or\n `filters.contains(term)` (substring), and unwrap for display with\n `filters.values(src)`. The stock `<Select/>` does this automatically;\n `<Search/>` deliberately commits raw text (its input IS a filter\n expression).\n- `<Panel/>` runs against the DASHBOARD\'s own file: a bare `<Panel/>` renders\n the whole dashboard (its tiles); `<Panel query="\u2026"/>` runs a query defined in\n the dashboard file (by name) or a `source -> view`; `<Panel malloy="\u2026"/>` and\n `runData(text, givens)` run arbitrary Malloy as a RESTRICTED query (no import /\n given: / connection.* / raw SQL / ##! flags \u2014 the model\'s governed surface\n only). `lint` checks each hard-coded `query="\u2026"` still resolves.\n\n## Shareable view-state: `useUrlState`\n\n`useState` is invisible to the page that owns the URL, so a component built on\nit has an address bar that never changes \u2014 the result can\'t be shared or\nbookmarked. **`useUrlState(key, initial)` is a `useState` twin whose value lives\nin the URL**, under a `~key` param:\n\n```jsx\nimport { useUrlState } from "@malloyyo/dashboard";\n\nconst [rack, setRack] = useUrlState("rack", ""); // string\nconst [reuse, setReuse] = useUrlState("reuse", false); // boolean\nconst [board, setBoard] = useUrlState("board", "........"); // string\nconst [topN, setTopN] = useUrlState("n", 20); // number\n```\n\n- Same shape as `useState`: `[value, setValue]`, and `setValue` takes a value\n **or** an updater fn (`setBoard(b => \u2026)`).\n- The value comes from the URL on load, else `initial`. Every change is written\n back (debounced, `replaceState` \u2014 no history spam), so the address bar is\n always a shareable link.\n- Typed by `initial`: string / number / boolean / any JSON-serializable value.\n Strings stay readable in the URL (`~rack=retinas`); objects and arrays are\n JSON. A value equal to `initial` is dropped from the URL, so defaults never\n clutter it, and a malformed value falls back to `initial` instead of throwing.\n- Works identically in `malloyyo dashboard dev`, on a bundled static site, and\n on a hosted instance \u2014 including inside the sandboxed iframe, which cannot\n reach the top-level URL on its own. That\'s why this is a hook and not\n something a component can do with `history.replaceState`.\n\n**Use it for view-state, not query parameters.** A `given:` is the governed,\nfilter-typed query contract: it\'s declared in the model, drives the default\ncontrols, and is visible over MCP \u2014 bind those with `useGiven` and they already\nround-trip through the URL as `$NAME`. `useUrlState` is for everything else a\ncustom component needs to make shareable: a letter rack whose real query inputs\n(allowed letters, min/max length) are computed from it in JS, a board layout, a\nmode toggle. The two namespaces (`$NAME` vs `~key`) never collide.\n\n## Theming\n\nEvery widget is styled by the runtime\'s **default Malloyyo theme** (system\nfont, neutral grays, blue accent, auto light/dark following the viewer\'s OS) \u2014\na bare component looks styled with zero effort, so DON\'T hand-hardcode\n`fontFamily`/colors. The theme is CSS custom properties; override any subset by\nsetting them on a wrapper element (more specific than the runtime\'s `:root`):\n\n```tsx\n<div style={{ "--dash-accent": "#e11d48", "--dash-controls-bg": "#faf5ff" }}>\n <Controls /> \u2026\n</div>\n```\n\nVars: `--dash-font`, `--dash-bg`, `--dash-fg`, `--dash-muted`, `--dash-border`,\n`--dash-accent`, `--dash-accent-fg`, `--dash-control-bg`, `--dash-controls-bg`,\n`--dash-chip-bg`, `--dash-chip-fg`, `--dash-panel-bg`, `--dash-radius`,\n`--dash-danger`. `DefaultDashboard` also takes a `theme={{ accent, controlsBg }}`\nprop (camelCase keys \u2192 `--dash-*`). The results `<Panel>` keeps a light surface\nin both light/dark (the Malloy renderer has no dark theme) \u2014 override\n`--dash-panel-bg` if your renderer output is dark-safe.\n\n**Use `--dash-*` and nothing else.** A custom component renders in its own\n**iframe**, so CSS variables defined by the surrounding page \u2014 including the\nbundled site\'s `--line` / `--card` / `--muted` \u2014 are NOT in scope inside it. A\ncomponent styled against those still renders, but every rule referencing them\nresolves to nothing: borders, dividers and panel backgrounds vanish silently\nwhile text and layout survive, so the page looks *almost* right and the cause\nisn\'t obvious. If you\'re porting CSS that has to work both inside the frame and\non a bundled page, resolve each colour once through the chain and use the alias:\n\n```css\n.my-card {\n --edge: var(--dash-border, var(--line, #e4e6eb));\n --surface: var(--dash-panel-bg, var(--card, #fff));\n border: 1px solid var(--edge);\n background: var(--surface);\n}\n```\n\nThis is a class of bug `lint` cannot see and a screenshot can \u2014 look at custom\ncomponents in `malloyyo dashboard dev` before shipping them.\n\nFor charts beyond the Malloy renderer\'s `#` tags, use `<VegaChart>` \u2014\n`yo_help dashboards/vega-charts`.\n',
205
205
  "dashboards/drafts.md": "---\ndescription: Writing a draft dashboard from a chat client \u2014 one component file, queries inline, saved with save_draft_dashboard; and how one is promoted into the model repo\n---\n\n# Draft dashboards (`save_draft_dashboard`)\n\nA draft is a dashboard stored on this instance rather than in the model repo.\nIt gets a URL, renders like any other dashboard, and can be re-saved as often\nas you like. Read this before writing one.\n\n## The shape\n\nONE React component, default-exported, whose queries are Malloy written inline:\n\n```tsx\nimport { useQuery } from \"@malloyyo/dashboard\";\n\nexport default function Dashboard() {\n const top = useQuery({\n malloy: `run: flights -> { group_by: carrier; aggregate: flight_count; limit: 10 }`,\n });\n const rows = top.rows ?? [];\n return (\n <div style={{ padding: 24 }}>\n <h1 style={{ fontSize: 22, fontWeight: 600 }}>Top carriers</h1>\n {top.loading ? <p>Loading\u2026</p> : <ol>{rows.map((r) => (\n <li key={String(r.carrier)}>{String(r.carrier)}: {Number(r.flight_count).toLocaleString()}</li>\n ))}</ol>}\n </div>\n );\n}\n```\n\nSave it with `save_draft_dashboard({ dataset, name, title, source })`. The\nresult carries a `url` to open and a `dashboard` name that `show_dashboard`\nrenders. Pass the returned `slug` back on the next save to update the same\ndraft instead of making another.\n\n## The queries\n\nInline Malloy runs against what the model PUBLISHES \u2014 the same rules as the\n`query` tool. You may define your own sources, measures and joins derived from\nthe model's sources. You may not `import`, open a connection, write raw SQL, or\ndeclare `given:`. Check a query with `query(execute:false)` before you put it\nin a component; the save also compiles every literal query it finds and reports\nwhat failed.\n\nWrite the whole query as one template literal. A query built by string\nconcatenation can't be checked at save time and only fails when a reader opens\nthe dashboard.\n\n## What you can import\n\nOnly these resolve:\n\n| Import | What you get |\n|---|---|\n| `react` | React itself, hooks included |\n| `@malloyyo/dashboard` | `useQuery`, `useGiven`, `useOptions`, `useUrlState`, `runData`, `filters`, `VegaChart`, `Field`, and the controls: `Controls`, `Given`, `Select`, `Search`, `MultiSelect`, `Range`, `Checkbox`, `TimeRange` |\n\nNothing else \u2014 no chart library, no icon set, no CSS framework, no `fetch`.\nUse inline `style` objects, plain HTML, and `VegaChart` (see\n`yo_help dashboards/vega-charts`) for charts.\n\n`useQuery` returns `{ rows, result, loading, error }`. `rows` is an array of\nplain objects. Numbers can arrive as BigInt or decimal objects, so wrap them\nwith `Number()` before `.toLocaleString()` or arithmetic, and format dates in\nMalloy rather than in JavaScript.\n\n## Presentation\n\n- One clear page title, then the content. No wrapper card around everything.\n- Put a few headline numbers in a row, value large (~40px) with a small label\n beneath; don't stack them vertically.\n- Give each query-backed section its own loading and error state, so a slow one\n doesn't blank the page.\n- Prefer a table under ~8 categories, where exact values and ranking matter;\n use a chart when shape or trend is the point.\n- Keep charts responsive in width and roughly 200\u2013280px tall.\n- Say what the data shows. Don't call a change strong, concerning or surprising.\n\n## When to add a `.malloy` file instead\n\nPass `malloy` as well when the dashboard needs:\n\n- **filters/controls** \u2014 declare givens in the model and the controls render\n themselves (`yo_help dashboards/givens-and-controls`);\n- **named queries** shared across several tiles, or a composite grid\n (`yo_help dashboards/authoring`);\n- **no code at all** \u2014 a tagged Malloy query renders through Malloy's own\n renderer, which is often the better dashboard.\n\nThat file is `dashboards/<name>.malloy`: it imports `\"../index.malloy\"` and\ntags a query `# artifact`.\n\n## Promotion\n\nA draft lives on the instance; the model repo is where dashboards belong. To\nmove one in, from a checkout of the repo:\n\n```bash\nmalloyyo draft list # find the slug\nmalloyyo draft promote <slug> # writes dashboards/<name>.malloy + component\n```\n\nPromotion writes the files and records what the draft became; it never deletes\nthe draft, whose URL people may already hold. A draft whose queries are inline\nneeds them LIFTED into its `.malloy` as named queries \u2014 the component then uses\n`useQuery({ query: \"<name>\" })` \u2014 because a repo dashboard's queries live in\nthe model, not the component. The written `.malloy` carries them as comments to\nwork from. Then `malloyyo lint`, and the usual PR.\n\n## Iterating\n\n1. `list_sources`, then `describe_source` for the source you'll query.\n2. Validate each query with `query(execute:false)`.\n3. Save the draft; fix anything the report names.\n4. Show the user the URL (or `show_dashboard`), and ask what to change.\n5. Re-save with the same `slug`.\n",
206
- "dashboards/givens-and-controls.md": "---\ndescription: Dashboard filter controls \u2014 declare filter<T> givens with # label / suggest / control tags; faceted (related) suggestions\n---\n\n# Dashboard givens & controls\n\nA dashboard's filters are `filter<T>` **givens** declared in the model; the\n`#` tags on each declaration drive its control. This is part of authoring a\ndashboard \u2014 see also `yo_help dashboards/authoring`.\n\n**Declare the filters as `filter<T>` givens** \u2014 never raw strings/numbers.\nA `filter<string>` value accepts one value ('NY'), alternatives ('NY, CA'),\nwildcards ('Ann%'), negation ('-NY'); a `filter<number>` accepts ranges\n('[1910 to 1930]') and comparisons ('> 200'); a `filter<timestamp>` /\n`filter<date>` accepts relative windows ('7 days' = the last 7 days, 'today',\n'last month') and literal ranges ('2026-01-01 to 2026-07-01' \u2014 NO `@` in\nfilter literals). Apply with `~`; `f''` = empty = no filter (the natural\n\"All\"/\"all time\" \u2014 just `col ~ $X`, no `$X = '' or \u2026` dance):\n\n```malloy\n##! experimental { givens }\ngiven:\n # label=\"State\" control=select suggest { source=baby_names dimension=state }\n STATE :: filter<string> is f'NY'\n # label=\"Brand\" suggest { query=brand_suggest dimension=product_brand }\n BRAND :: filter<string> is f''\n # label=\"Names\" control=multiselect suggest { query=name_suggest dimension=name }\n NAMES :: filter<string> is f''\n # label=\"Years\" range_min=1910 range_max=2025\n YEAR_RANGE :: filter<number> is f'[1910 to 1930]'\n # label=\"Time period\"\n PERIOD :: filter<timestamp> is f''\n # label=\"Include rare names\"\n INCLUDE_RARE :: boolean is false\n```\n\nTags on the declaration drive the control (tag syntax is `key=\"value\"` \u2014\nequals, not colon):\n- `label` \u2014 control caption (defaults to the given's name)\n- `suggest { \u2026 }` \u2014 where the control's options come from. NO Malloy code in\n strings \u2014 just names:\n - `suggest { query=brand_suggest dimension=product_brand }` \u2014 the FIRST\n COLUMN of a named query (declare the query in the model \u2014 governed and\n reviewable). PREFER THIS FORM. The query must be in scope where the dashboard\n runs (bring it in with the dashboard file's bare `import`).\n - `suggest { source=baby_names dimension=state }` \u2014 the DISTINCT VALUES of\n a dimension on a source (the source must be in the dashboard's scope)\n A `dimension` (in either form) is what enables SERVER-SIDE TYPEAHEAD: the\n runtime refines the base query with what the user has typed\n (`\u2026 + { where: lower(field) ~ f'll%'; limit: 50 }`, case-insensitive,\n escaped). Without a dimension the fetched list is filtered client-side.\n Runs as a restricted query; lint checks the declaration compiles.\n\n **RELATED (faceted) filters** \u2014 query-form only: a suggest query may\n reference the OTHER givens, and the runtime runs it with the dashboard's\n current values (the suggested given itself is excluded, so the list never\n collapses to the current pick). Brand suggestions narrow when Category is\n set:\n\n ```malloy\n query: brand_suggest is inventory_items -> product_brand + {\n where:\n product_category ~ $CATEGORY, // NOT product_brand ~ $BRAND\n product_department ~ $DEPARTMENT\n limit: 500\n }\n ```\n\n Declare one `*_suggest` per filter, each referencing the others; `f''`\n defaults mean unset filters don't constrain. `source=` suggests can't do\n this (no place for a `where:`) \u2014 another reason to prefer `query=`.\n- `control=select` \u2014 a fixed dropdown instead of a typeahead search box\n- `control=multiselect` \u2014 a tokenized multi-select for a `filter<string>`:\n each pick is a removable chip, the committed value is an exact-match list\n (`Emma, Olivia, Sophia`). Ideal for \"pick several\" filters (names, brands).\n Suggestions come from the given's `suggest {\u2026}` (server-side typeahead when\n it names a dimension). Empty (start from `f''`) = no filter (all).\n- `range_min` / `range_max` \u2014 bounds; makes a filter<number> given a\n dual-thumb range slider\n- anything else passes through in `spec.tags` for custom components\n\nControl picked from the declaration automatically: numeric range tags \u2192\ndual-thumb slider; `filter<timestamp|timestamptz|date>` \u2192 the TimeRange\nwidget (relative presets: Today / Last 7 days / Last 30 days / \u2026 plus a\n\"Custom range\u2026\" from/to date picker); `control=multiselect` \u2192 chip\nmulti-select; suggest + control=select \u2192 dropdown; boolean \u2192 checkbox;\nanything else \u2192 committing search box with typeahead (an inline \u2715 clears it;\na \"Press \u21B5 to apply\" hint shows while the typed draft differs from what's\nrunning \u2014 free text can't safely re-run per keystroke).\nThe suggest-driven options are DATA VALUES only \u2014 options that aren't column\nvalues (custom time presets, threshold buckets) need a custom component\n(`yo_help dashboards/custom-components`) with explicit `{value, text}` options\nwhere value is a filter expression built with `filters.*`.\n\n## When the query re-runs: live (default) vs. Apply\n\nBy default a dashboard is **live** \u2014 every control change re-runs the query\nimmediately (the committing search box is the exception: free text commits on\nEnter/blur, since a half-typed filter is invalid). To batch changes behind an\n**Apply** button instead, set `autorun=false` on the `# artifact` tag:\n\n```malloy\n# artifact { name=\"births-by-name\" title=\"Births by name\" autorun=false }\n```\n\n`autorun=false` makes `<Controls>` grow an Apply/Reset pair \u2014 controls edit a\ndraft and nothing re-runs until Apply. Reach for it when the query is expensive\nor several filters are usually changed together; leave it off (live) otherwise.\n",
206
+ "dashboards/givens-and-controls.md": "---\ndescription: Dashboard filter controls \u2014 declare filter<T> givens with # label / suggest / control tags; faceted (related) suggestions\n---\n\n# Dashboard givens & controls\n\nOne given is NOT a control: `$MALLOYYO_EMAIL` is filled from the signed-in\nuser, cannot be set by a caller, and renders no filter \u2014 see\n`yo_help language/who-is-asking` for per-user data.\n\nA dashboard's filters are `filter<T>` **givens** declared in the model; the\n`#` tags on each declaration drive its control. This is part of authoring a\ndashboard \u2014 see also `yo_help dashboards/authoring`.\n\n**Declare the filters as `filter<T>` givens** \u2014 never raw strings/numbers.\nA `filter<string>` value accepts one value ('NY'), alternatives ('NY, CA'),\nwildcards ('Ann%'), negation ('-NY'); a `filter<number>` accepts ranges\n('[1910 to 1930]') and comparisons ('> 200'); a `filter<timestamp>` /\n`filter<date>` accepts relative windows ('7 days' = the last 7 days, 'today',\n'last month') and literal ranges ('2026-01-01 to 2026-07-01' \u2014 NO `@` in\nfilter literals). Apply with `~`; `f''` = empty = no filter (the natural\n\"All\"/\"all time\" \u2014 just `col ~ $X`, no `$X = '' or \u2026` dance):\n\n```malloy\n##! experimental { givens }\ngiven:\n # label=\"State\" control=select suggest { source=baby_names dimension=state }\n STATE :: filter<string> is f'NY'\n # label=\"Brand\" suggest { query=brand_suggest dimension=product_brand }\n BRAND :: filter<string> is f''\n # label=\"Names\" control=multiselect suggest { query=name_suggest dimension=name }\n NAMES :: filter<string> is f''\n # label=\"Years\" range_min=1910 range_max=2025\n YEAR_RANGE :: filter<number> is f'[1910 to 1930]'\n # label=\"Time period\"\n PERIOD :: filter<timestamp> is f''\n # label=\"Include rare names\"\n INCLUDE_RARE :: boolean is false\n```\n\nTags on the declaration drive the control (tag syntax is `key=\"value\"` \u2014\nequals, not colon):\n- `label` \u2014 control caption (defaults to the given's name)\n- `suggest { \u2026 }` \u2014 where the control's options come from. NO Malloy code in\n strings \u2014 just names:\n - `suggest { query=brand_suggest dimension=product_brand }` \u2014 the FIRST\n COLUMN of a named query (declare the query in the model \u2014 governed and\n reviewable). PREFER THIS FORM. The query must be in scope where the dashboard\n runs (bring it in with the dashboard file's bare `import`).\n - `suggest { source=baby_names dimension=state }` \u2014 the DISTINCT VALUES of\n a dimension on a source (the source must be in the dashboard's scope)\n A `dimension` (in either form) is what enables SERVER-SIDE TYPEAHEAD: the\n runtime refines the base query with what the user has typed\n (`\u2026 + { where: lower(field) ~ f'll%'; limit: 50 }`, case-insensitive,\n escaped). Without a dimension the fetched list is filtered client-side.\n Runs as a restricted query; lint checks the declaration compiles.\n\n **RELATED (faceted) filters** \u2014 query-form only: a suggest query may\n reference the OTHER givens, and the runtime runs it with the dashboard's\n current values (the suggested given itself is excluded, so the list never\n collapses to the current pick). Brand suggestions narrow when Category is\n set:\n\n ```malloy\n query: brand_suggest is inventory_items -> product_brand + {\n where:\n product_category ~ $CATEGORY, // NOT product_brand ~ $BRAND\n product_department ~ $DEPARTMENT\n limit: 500\n }\n ```\n\n Declare one `*_suggest` per filter, each referencing the others; `f''`\n defaults mean unset filters don't constrain. `source=` suggests can't do\n this (no place for a `where:`) \u2014 another reason to prefer `query=`.\n- `control=select` \u2014 a fixed dropdown instead of a typeahead search box\n- `control=multiselect` \u2014 a tokenized multi-select for a `filter<string>`:\n each pick is a removable chip, the committed value is an exact-match list\n (`Emma, Olivia, Sophia`). Ideal for \"pick several\" filters (names, brands).\n Suggestions come from the given's `suggest {\u2026}` (server-side typeahead when\n it names a dimension). Empty (start from `f''`) = no filter (all).\n- `range_min` / `range_max` \u2014 bounds; makes a filter<number> given a\n dual-thumb range slider\n- anything else passes through in `spec.tags` for custom components\n\nControl picked from the declaration automatically: numeric range tags \u2192\ndual-thumb slider; `filter<timestamp|timestamptz|date>` \u2192 the TimeRange\nwidget (relative presets: Today / Last 7 days / Last 30 days / \u2026 plus a\n\"Custom range\u2026\" from/to date picker); `control=multiselect` \u2192 chip\nmulti-select; suggest + control=select \u2192 dropdown; boolean \u2192 checkbox;\nanything else \u2192 committing search box with typeahead (an inline \u2715 clears it;\na \"Press \u21B5 to apply\" hint shows while the typed draft differs from what's\nrunning \u2014 free text can't safely re-run per keystroke).\nThe suggest-driven options are DATA VALUES only \u2014 options that aren't column\nvalues (custom time presets, threshold buckets) need a custom component\n(`yo_help dashboards/custom-components`) with explicit `{value, text}` options\nwhere value is a filter expression built with `filters.*`.\n\n## When the query re-runs: live (default) vs. Apply\n\nBy default a dashboard is **live** \u2014 every control change re-runs the query\nimmediately (the committing search box is the exception: free text commits on\nEnter/blur, since a half-typed filter is invalid). To batch changes behind an\n**Apply** button instead, set `autorun=false` on the `# artifact` tag:\n\n```malloy\n# artifact { name=\"births-by-name\" title=\"Births by name\" autorun=false }\n```\n\n`autorun=false` makes `<Controls>` grow an Apply/Reset pair \u2014 controls edit a\ndraft and nothing re-runs until Apply. Reach for it when the query is expensive\nor several filters are usually changed together; leave it off (live) otherwise.\n",
207
207
  "dashboards/grid-layout.md": "---\ndescription: Dashboard grid layout \u2014 # dashboard {columns=N} with # colspan and # break to place KPI tiles and charts\n---\n\n# Dashboard grid layout (`# dashboard {columns=N}`)\n\nBy default a `# dashboard` result flows its KPI tiles and cards and wraps.\nAdd `{columns=N}` to place them on a fixed **N-column grid** instead \u2014 use\n`columns=6`, which divides evenly into 2- and 3-wide cards.\n\n**Key mechanic:** a tag placed ABOVE `aggregate:` or `nest:` applies to EVERY\nitem declared in that block. So you set card widths once per block, not per\nfield.\n\n```malloy\n# artifact { title=\"Customer Insights\" } dashboard {columns=6}\nview: customer_insights is {\n where: created_at ~ $PERIOD\n # colspan=2\n aggregate: total_sales, user_count, order_count, average_order_value\n # colspan=3\n nest:\n # break\n # bar_chart\n users_by_spend_tier\n sales_by_traffic_source\n # shape_map\n sales_by_state\n # colspan=6\n recent_orders // wide detail table \u2192 full width\n}\n```\n\n## The conventions\n\n- **`# colspan=2` above `aggregate:`** \u2014 each KPI / measure tile spans 2 of 6\n columns \u2192 3 tiles per row.\n- **`# colspan=3` above `nest:`** \u2014 each graph or small table spans 3 \u2192 2 per\n row. Per-item render tags (`# line_chart`, `# bar_chart`, `# shape_map`) still\n go on the individual nested items.\n- **`# colspan=6`** \u2014 a single wide / many-column table gets its own full-width\n line. Tag that one item; a per-item `# colspan` overrides the block default.\n- **`# break` on the FIRST nest item** \u2014 starts the graphs on a fresh row, so\n KPI tiles and charts never share one. The renderer splits fields into a new\n grid at each `# break`. Just always add it: it's a no-op when the tiles\n already fill complete rows, and the fix when they don't (e.g. 4 measures\n leave a lone tile a colspan-3 chart would otherwise pack in beside).\n\n`# colspan` only does anything in columns mode \u2014 without `{columns=N}` the\nlayout is free-flow wrap and colspan is ignored. Clamp colspans to `1..N`.\n\nSee also `yo_help dashboards/vega-charts` for custom charts, and the fuller\nauthoring guide surfaced by the local `malloyyo mcp` server.\n",
208
208
  "dashboards/vega-charts.md": '---\ndescription: Custom dashboard charts with Vega-Lite \u2014 the <VegaChart> component, for charts the # renderer tags can\'t do\n---\n\n# Custom charts with Vega-Lite (`<VegaChart>`)\n\nWhen Malloy\'s renderer tags (`# bar_chart`, `# line_chart`, `# shape_map`, \u2026)\ndon\'t cover the chart you want, a dashboard can draw a **Vega-Lite** spec with\nthe `<VegaChart>` component. The chart engine ships in the dashboard runtime, so\nyou author only a JSON spec + a Malloy query \u2014 no library to load.\n\n**It is a COMPONENT, not a `#` tag.** There is no `# vega_lite` or\n`# scatter_chart` tag. `<VegaChart>` lives in a custom component \u2014 a flat sibling\n`dashboards/<name>.jsx` (or `.tsx`) next to the dashboard\'s\n`dashboards/<name>.malloy` \u2014 a different layer from the `#` renderer tags. (The\ndashboard\'s query is declared in the `.malloy` file; the component only\ncustomizes presentation. Preview with `malloyyo dashboard dev`, validate with\n`malloyyo lint`.)\n\n## The recipe\n\n```tsx\nimport { VegaChart } from "@malloyyo/dashboard";\n\n// Encodings point at the query\'s OUTPUT COLUMN NAMES (here: name, births).\nconst spec = {\n mark: { type: "bar", tooltip: true },\n encoding: {\n y: { field: "name", type: "nominal", sort: "-x" },\n x: { field: "births", type: "quantitative" },\n },\n};\n\nexport default function Dashboard({ givens }) {\n return <VegaChart spec={spec} query="births_by_name" givens={givens} />;\n}\n```\n\nThree ways to feed it data:\n- `<VegaChart spec={spec} query="births_by_name" givens={givens}/>` \u2014 a query\n defined in the dashboard\'s `.malloy` file (by name), or a `source -> view`\n- `<VegaChart spec={spec} malloy="source -> view" givens={givens}/>` \u2014 restricted\n Malloy text (same governance as the explore surface: no import / given: /\n connection.* / raw SQL / ##! flags)\n- `<VegaChart spec={spec} data={rows}/>` \u2014 rows you already have from `useQuery`\n\n## Gotchas (the ones that actually bite)\n\n- **Shape the data in Malloy; return FLAT rows.** Do ranking, share/percent\n (`all(x, dim)`), and label lookups (a `pick` for month names) in the QUERY.\n The spec just encodes columns \u2014 it is not the place to reshape data.\n- **Match column names character-for-character.** Run the query once with\n `query(execute:true)` and read the exact output column names; the spec\'s\n `field` values must match them exactly.\n- **The spec\'s `data` is ignored / any `url` is stripped.** The frame has no\n network \u2014 remote data URLs, transform lookups, and remote `image` marks are\n removed. Adapting a Vega-Lite gallery example = delete its\n `"data": {"url": \u2026}` and repoint the encodings; the query rows are inlined for\n you as the dataset.\n- **Nests come back as arrays.** Flatten to plottable rows in the query, or bind\n a nest to its own chart: `<VegaChart data={row.my_nest}/>`.\n- **Huge integers arrive as strings, on purpose.** Integers serialize as JSON\n numbers, but a value beyond \xB12^53 (a snowflake ID, a 64-bit hash) keeps its\n full precision by staying a string \u2014 JSON has no int64. Bound to a\n `quantitative` or `temporal` channel, Vega-Lite would sort such a column\n lexicographically (`"1","10","11","2"`). If a column can get that big and you\n need to plot it, narrow it in the QUERY \u2014 bucket it, rank it, or emit the\n value you actually want on the axis.\n- **Interactivity = setting given values**, never rewriting query text per\n interaction. Client-side chart interactions (tooltip, zoom, brush) work;\n anything that calls a server does not.\n- **Reads well:** for normalized/share data use a diverging color scale with\n `domainMid` (e.g. `1/12` for month-share), and sort a discrete axis by a\n companion numeric field (`month_name` sorted by `month_num`) rather than\n alphabetically.\n\n## Validate\n\n`malloyyo lint` checks the query, the givens, AND the component (it compiles,\nand each `query="\u2026"` it references resolves) \u2014 your only pre-browser check. Then\n`malloyyo dashboard dev` to see it render.\n',
209
209
  "develop/connection-setup.md": '---\ndescription: Setting up a data connection (malloy-config.json)\n---\n\n# Setting up a data connection\n\nA model reaches its data through a **connection** declared in\n`malloy-config.json` at the **root of the model** (next to `index.malloy`). This\nis Malloy\'s standard connection config \u2014 the full reference, with every\nconnector\'s properties, is at\n<https://docs.malloydata.dev/documentation/setup/config>. The essentials:\n\n## The file\n\n```json\n{\n "connections": {\n "mydb": { "is": "duckdb" }\n }\n}\n```\n\n- A connection has a **name** (the key) and a type (`is`). Sources refer to it by\n that name \u2014 `source: x is mydb.table("orders")` or `mydb.sql("SELECT \u2026")` \u2014 so\n the name in the config must match the name in the model.\n- Supported types (`is`): `duckdb` (incl. MotherDuck), `bigquery`, `postgres`,\n `mysql`, `snowflake`, `databricks`, `trino`, `presto`. Each has its own\n properties \u2014 see the full docs.\n\n## Default connections (and when they apply)\n\nSetting `"includeDefaultConnections": true` makes one connection available for\n**each registered database type, named by the type** \u2014 a `duckdb` connection\nnamed `duckdb`, a `postgres` named `postgres`, and so on. Each uses that\nconnector\'s default settings, which for several backends means picking up\ncredentials from the environment (e.g. BigQuery\'s application-default\ncredentials \u2014 see the per-connector setup docs). Connections you name explicitly\nin `connections` always win; the defaults only fill in types you didn\'t list.\n\n```json\n{\n "includeDefaultConnections": true,\n "connections": { "warehouse": { "is": "postgres", "host": "\u2026" } }\n}\n```\n\nmalloyyo has one rule worth knowing:\n\n- **No `malloy-config.json` at all \u2192 defaults are ON.** `duckdb` just works with\n zero setup.\n- **Write a `malloy-config.json` and they turn OFF** unless you add\n `"includeDefaultConnections": true`. A config that only defines, say, a\n `postgres` connection will report *No connection named "duckdb"* if a source\n still references `duckdb`.\n\nThis is deliberate \u2014 your local connections then resolve exactly the way the\npublished server\'s will, rather than silently leaning on a default that would not\nexist in production. (It differs from `malloy-cli`, which forces the defaults on\nunconditionally.)\n\n*No connection named* has one cause that is **not** about your config: if more\nthan one copy of `@malloydata/malloy` is installed, the connectors register with\none copy and malloyyo reads another, and every connection looks missing. malloyyo\ndetects that and says so instead \u2014 if it doesn\'t mention duplicate copies, the\nproblem really is the config. To check by hand: `npm ls @malloydata/malloy`.\n\nGive a connection a **custom name** \u2014 not the bare type default \u2014 whenever you\nhave more than one connection of the same type, or need non-default parameters.\n\n## DuckDB and local files (the common case)\n\nDuckDB can either open a **DuckDB database file** or read **local data files**\n(CSV, Parquet, \u2026) directly.\n\n**A pre-loaded database file** \u2014 point `databasePath` at a `.duckdb` file and\nreference its tables by name (an absolute path is safest):\n\n```json\n{ "connections": { "warehouse": { "is": "duckdb", "databasePath": "/data/warehouse.duckdb" } } }\n```\n\n**Local files, by path** \u2014 read a CSV or Parquet file straight into a source.\nThese paths are **project-relative** \u2014 resolved against the model root, so they\nsurvive publishing:\n\n source: my_csv is duckdb.table(\'data/my_file.csv\')\n source: my_parquet is duckdb.table(\'data/my_file.parquet\')\n\n`.table()` names a single file. When you need something it can\'t express \u2014 a\nglob, a union, any SQL \u2014 wrap it in `.sql()` (its paths are project-relative too):\n\n source: payments is duckdb.sql(\n "SELECT * FROM read_parquet(\'data/payments-*.parquet\')"\n )\n\nThe default `duckdb` connection is **in-memory** \u2014 nothing persists between runs;\nyour data lives in the files (or the `databasePath` database) you read.\n\n**MotherDuck:** a DuckDB connection against an `md:` database; set the\n`MOTHERDUCK_TOKEN` environment variable.\n\n## Secrets \u2014 keep them out of the file\n\nAny property value may be written as `{ "env": "VAR_NAME" }`. It resolves from\n`process.env.VAR_NAME` when the connection opens, so passwords and tokens never\nget committed:\n\n```json\n{\n "connections": {\n "analytics": {\n "is": "postgres",\n "host": "db.internal",\n "databaseName": "analytics",\n "username": "reader",\n "password": { "env": "PG_PASSWORD" }\n }\n }\n}\n```\n\n(The non-secret property names here are illustrative \u2014 each connector\'s exact\nproperties are in the full docs. The `{ "env": \u2026 }` form is the part that\nmatters: it works for any value.)\n\n## malloyyo specifics\n\n- **One file, one place.** Only the `malloy-config.json` at the model root is\n read \u2014 there is no walk-up to parent directories.\n- **Local override:** a `malloy-config-local.json` (do **not** commit it)\n **replaces** `malloy-config.json` entirely when present \u2014 your private variant\n for local credentials or a different database.\n- **The same file ships to production.** Publishing uploads this exact\n `malloy-config.json`, so it must resolve the same way locally and on the\n server \u2014 put anything environment-specific behind `{ "env": \u2026 }` rather than\n hard-coding it. That is what makes the local test window faithful to\n production.\n- Edits are picked up **without a restart** \u2014 the server re-reads the file when\n it changes.\n\n## When a connection will not resolve\n\nFix the connection **first**: a broken connection yields an empty schema and then\na cascade of misleading `field-not-found` errors \u2014 ignore those and fix the\nconnection. A fast check is to compile a probe and see if it alone compiles:\n\n source: _probe is mydb.sql("SELECT 1 AS one")\n',
@@ -215,6 +215,7 @@ var contentFiles = {
215
215
  "explore/restricted-queries.md": "# Restricted Query Explanation\n\nThe `query` tool runs your Malloy against a **published model**. You have that\nmodel's entire published surface to work with \u2014 and you can build on it. The\nmodel is an inentionally curated subset of the data available in the\ndatabase.\n\n## You can\n\n- Use everything the model defines: its **sources, dimensions, measures, views,\n joins, and named queries**. `describe_source` shows exactly what's there.\n- **Run a named query and refine it** \u2014\n `run: top_carriers + { where: dep_year = 2024 }`.\n- **Define your own** dimensions, measures, and **your own sources and joins** \u2014\n as long as they are *derived from the model's sources*. You are not limited to\n the author's fields; compose new ones from them.\n- Reference the model's `$NAME` givens and supply values via the `givens` map on\n the `query` call (use `execute: false` to discover which a query needs).\n- Use a model field that was itself defined with raw SQL \u2014 the author vouched\n for the model's own definitions.\n\n## What is \"Restricted\"\n\nIf you see `restricted-construct-forbidden`, the query used something that\nreaches *outside* the published model: pulling in another file (`import`),\nopening a raw connection (`connection.table(...)` / `connection.sql(...)`),\nwriting raw SQL (`name!type(...)` or the `sql_*` functions), declaring new\n`given:`s, or setting `##!` compiler flags.\n\nThe fix is never to work around it \u2014 express the answer in terms of what the\nmodel publishes (define derived sources, joins, dimensions, and measures from\nthe model's sources). If something fundamental is missing, that's feedback for\nthe model's author.\n",
216
216
  "language/malloy-language-reference.md": '<!-- Copied from malloy-cli (jrtipton/malloy-cli) skills/malloy-language-reference.md on 2026-06-11.\n Deliberate temporary fork \u2014 converge when the engine is extracted to @malloydata. -->\n---\ndescription: Malloy language reference \u2014 concepts, syntax, compilation model. Load this before writing or reviewing Malloy code.\n---\n# Malloy Language Reference\n\nMalloy is a semantic data modeling and query language. It compiles to SQL and runs against existing database engines (DuckDB, BigQuery, Snowflake, PostgreSQL, MySQL, Trino, Presto). It is not a SQL wrapper or abstraction layer \u2014 it has its own type system, scoping rules, expression semantics, and compilation pipeline.\n\nMalloy is designed around how humans think about data, not how data computations are mechanically accomplished. SQL is oriented around the machine \u2014 you specify joins, group-by columns, subqueries, and window functions in terms of what the database needs to do. Malloy is oriented around the analyst \u2014 you describe relationships, name computations, and compose questions in terms of what the data means. Malloy bridges the gap between these two by compiling the human-oriented description into correct, efficient SQL.\n\nA core design principle is that **most queries are themselves designing a new semantic model.** Formulating a question about data \u2014 choosing what to group by, what to aggregate, what to nest \u2014 is inherently an act of defining a new way to look at that data. Malloy is built around this idea: the output of every query is not just a result set but a new source with its own schema, and data comprehension is an ongoing iterative process where later stages want not only the data from a previous stage but how that data came into being. This is why query output carries metadata, why queries can be used as sources, and why views and pipelines compose naturally.\n\n## Documents and Statements\n\nA Malloy file (`.malloy`) is a sequence of statements, optionally separated by semicolons. There are five statement types:\n\n- **`import`** \u2014 import sources and queries from another `.malloy` file\n- **`source:`** \u2014 define a named, reusable data source with its schema and extensions\n- **`query:`** \u2014 define a named query (source + view) for reuse\n- **`run:`** \u2014 execute a query (the "do it now" statement)\n- **`given:`** \u2014 declare model-level parameters supplied at run time (experimental, see Givens)\n\n```malloy\nimport "shared_model.malloy"\n\nsource: flights is duckdb.table(\'flights.parquet\') extend {\n measure: flight_count is count()\n}\n\nquery: carrier_summary is flights -> {\n group_by: carrier\n aggregate: flight_count\n}\n\nrun: carrier_summary\n```\n\nComments use `//` or `--` (both are line comments).\n\n## Sources\n\nA **source** is anything you can hand a SQL database and get a schema back \u2014 a table name, a SQL SELECT, or the output of another Malloy query. The columns in that schema become the source\'s initial fields (all dimensions).\n\n```malloy\nsource: flights is duckdb.table(\'flights.parquet\')\nsource: limited is duckdb.sql("""SELECT * FROM flights LIMIT 100""")\nsource: carrier_facts is carrier_summary -- a query used as a source\n```\n\nWhat makes sources central to Malloy is **extension**. The `extend` block lets you layer on dimensions, measures, views, joins, filters, primary keys, field restrictions, and renames. These extensions travel with the source \u2014 any query against it gets them for free.\n\n```malloy\nsource: flights is duckdb.table(\'flights.parquet\') extend {\n primary_key: id\n\n dimension: distance_km is distance * 1.609344\n\n measure:\n flight_count is count()\n total_distance is sum(distance)\n\n join_one: carriers with carrier\n join_one: origin_airport is airports on origin_airport.code = origin\n\n where: dep_time > @2001\n\n view: by_carrier is {\n group_by: carrier\n aggregate: flight_count, total_distance\n }\n}\n```\n\nSources can extend other sources, creating a refinement chain:\n\n```malloy\nsource: ca_flights is flights extend {\n where: origin.state = \'CA\'\n}\n```\n\nField access control uses `accept:` (allowlist) or `except:` (denylist) to restrict which inherited columns are visible. Fields can be renamed with `rename: new_name is old_name`.\n\n## Joins\n\nJoins are declared in the source, not reconstructed in every query. This is a fundamental design difference from SQL: the graph structure of your data is a property of the model.\n\n```malloy\njoin_one: carriers with carrier -- FK \u2192 PK shorthand\njoin_one: origin_airport is airports on origin_airport.code = origin -- explicit ON\njoin_many: line_items on line_items.order_id = id -- one-to-many\njoin_cross: other_table on other_table.key = key -- cross join\n```\n\n- `join_one` \u2014 the joined source has at most one row per source row (many-to-one or one-to-one)\n- `join_many` \u2014 the joined source has potentially many rows per source row\n- `join_cross` \u2014 a full cross product\n\nThe `with` shorthand requires the joined source to have a declared `primary_key`. All joins are left outer by default. There is no right join \u2014 Malloy\'s graph model doesn\'t need one.\n\n**Choosing `join_one` vs `join_many`:** Ask "for a single row in the base source, can the joined source match more than one row?" If yes \u2192 `join_many`. If no (or at most one) \u2192 `join_one`. The common mistake is reaching for `join_many` when joining a *lookup or summary table* (e.g., joining an inventory snapshot to a purchase history on a wine key). Even though the joined table may have many rows overall, if each base row resolves to *at most one* joined row, use `join_one`. Use `join_many` only when the join genuinely fans out the base rows \u2014 e.g., joining line items to orders, or notes to a wine catalog.\n\nWhen you reference a joined source\'s fields, you use dot notation: `carriers.nickname`, `origin_airport.state`. This is one of Malloy\'s most important abstractions: **the access path to nested data is identical regardless of how the nesting is physically stored.** An array of records embedded in a column, a `join_many` to a separate table, a record-typed column \u2014 all are navigated with the same dot notation. The SQL required to traverse these different physical arrangements varies wildly (unnesting arrays, LEFT JOINs, correlated subqueries, ARRAY_AGG), but Malloy hides all of that. You think about the logical shape of your data \u2014 "flights have carriers, carriers have a nickname" \u2014 and write `carriers.nickname`. The compiler figures out what SQL is needed to get there. This means you can restructure your physical schema (normalize a nested array into a separate table, or denormalize a joined table into a record column) without changing any of the Malloy that references that data.\n\n## Fields\n\nMalloy has four kinds of fields: **dimensions**, **measures**, **views**, and **calculations**.\n\n### Dimensions\n\nScalar expressions \u2014 they compute a value per row. All columns inherited from a table are dimensions. Computed dimensions reference other dimensions or columns:\n\n```malloy\ndimension: full_name is concat(first_name, \' \', last_name)\ndimension: is_long_haul is distance > 1000\n```\n\n### Measures\n\nAggregate expressions \u2014 they compute a value across a set of rows. A field is a measure when its defining expression contains an aggregate function (`count`, `sum`, `avg`, `min`, `max`):\n\n```malloy\nmeasure:\n flight_count is count()\n total_distance is sum(distance)\n avg_distance is avg(distance)\n pct_delayed is count() { where: dep_delay > 30 } / count()\n```\n\n**`count(expr)` counts distinct values.** Unlike SQL\'s `COUNT(DISTINCT expr)`, Malloy uses `count(expr)` for distinct counting. The `count(distinct expr)` form is a deprecated syntax that will produce an error. Use `count()` for total row count, `count(field)` for distinct values of that field:\n\n```malloy\naggregate:\n total_rows is count() -- all rows\n unique_carriers is count(carrier) -- distinct carriers\n```\n\nMeasures can be filtered inline with `{ where: ... }`, which is how you build things like "percent of flights delayed" without subqueries.\n\n### Views\n\nA view is a query saved into the source \u2014 a reusable transformation:\n\n```malloy\nview: by_carrier is {\n group_by: carrier\n aggregate: flight_count, total_distance\n limit: 10\n}\n```\n\nViews can reference other views from the same source as a starting point, and can be extended with `+`.\n\n### Calculations\n\nWindow functions over the grouped result. Calculations can only be defined in a query stage with `calculate:`, never in a source definition, because they depend on the output columns of the query:\n\n```malloy\nrun: flights -> {\n group_by: carrier\n aggregate: flight_count\n calculate: carrier_rank is rank()\n}\n```\n\n## Queries and Views\n\nA query pairs a source with a view (the transformation). Everything after the first `->` is the view.\n\n```malloy\nrun: flights -> {\n group_by: carrier\n aggregate: flight_count\n}\n```\n\n### Reduction vs. Projection\n\nEach stage of a view performs exactly one of:\n\n- **Reduction** \u2014 uses `group_by:` and/or `aggregate:` to reduce grain. Analogous to `SELECT ... GROUP BY` in SQL.\n- **Projection** \u2014 uses `select:` to pick fields without aggregation. Analogous to `SELECT` without `GROUP BY`.\n\nThese cannot be mixed in a single stage. A stage with `group_by:` cannot have `select:`, and vice versa.\n\n### Source-level definitions vs. query-level operations\n\nThe same `name is expression` syntax defines fields in both sources and queries:\n\n```malloy\n-- In a source (reusable):\nsource: flights is ... extend {\n measure: flight_count is count() -- defines a measure in the model\n}\n\n-- In a query (ad hoc):\nrun: flights -> {\n aggregate: flight_count is count() -- defines the same measure inline\n}\n```\n\nWhen used in a source, `measure:` and `dimension:` are **definition statements** \u2014 they add named fields to the source\'s schema. When used in a query, `group_by:`, `aggregate:`, `select:`, `nest:`, and `calculate:` are **query operations** \u2014 they specify what the query does. The field definitions are syntactically identical in both contexts, but the enclosing keyword determines the role:\n\n| Source keyword | Query keyword | What it holds |\n|---|---|---|\n| `dimension:` | `group_by:` or `select:` | scalar expressions |\n| `measure:` | `aggregate:` | aggregate expressions |\n| `view:` | `nest:` | sub-queries |\n| _(n/a)_ | `calculate:` | window functions |\n\nThis is why `measure` and `aggregate` are separate keywords. `measure:` is a *modeling* statement \u2014 "this source has a reusable aggregate computation called X." `aggregate:` is a *query* statement \u2014 "in this query, include these aggregate values in the output." A query\'s `aggregate:` can reference a previously defined measure by name, or define one inline. The distinction parallels the separation between defining a dimension in a source and using it via `group_by:` in a query.\n\n### Multi-stage Pipelines\n\nStages chain with `->`. Each stage\'s output becomes the next stage\'s source:\n\n```malloy\nrun: flights -> {\n group_by: carrier\n aggregate: flight_count is count()\n} -> {\n where: flight_count > 1000\n select: *\n}\n```\n\n### Refinement with `+`\n\nThe refinement operator `+` merges query operations together. It works both within a view and at the top level on a named query:\n\n```malloy\n-- Refining a view within a query:\nrun: flights -> by_carrier + { limit: 5 } + { nest: by_destination }\n\n-- Refining a named query at the top level:\nrun: carrier_summary + { group_by: origin } -- add origin grouping to existing query\n```\n\nWhen a dimension name appears as a bare reference, it expands to `{ group_by: name }`. A measure name expands to `{ aggregate: name }`:\n\n```malloy\nrun: flights -> carrier + flight_count + { limit: 10 }\n-- equivalent to: flights -> { group_by: carrier; aggregate: flight_count; limit: 10 }\n```\n\nFor multi-stage queries, refinement semantics get more complex \u2014 but for single-stage queries, `+` straightforwardly merges operations into the stage.\n\n### Nesting\n\n`nest:` embeds an aggregating subquery inside a reduction. Each row of the outer query gets a subtable from the nested query. Nests can nest arbitrarily deep:\n\n```malloy\nrun: flights -> {\n group_by: carrier\n aggregate: flight_count\n nest: top_routes is {\n group_by: origin, destination\n aggregate: flight_count\n limit: 3\n }\n}\n```\n\n### Other query operations\n\n- **`where:`** \u2014 filter rows (pre-aggregation). Comma-separated filters are ANDed.\n- **`having:`** \u2014 filter groups (post-aggregation), like SQL\'s HAVING.\n- **`limit:`** / **`order_by:`** \u2014 limit and sort output.\n- **`extend`** \u2014 add fields or joins to a source inline within a query expression.\n\n## Aggregate Locality (Symmetric Aggregates)\n\nThis is one of Malloy\'s most important features. In SQL, when you join tables and aggregate, you risk double-counting (the "fan trap"). Malloy solves this with **aggregate locality** \u2014 you specify *where in the join graph* an aggregation should be computed.\n\n```malloy\nrun: flights -> {\n aggregate:\n -- avg seats weighted by number of flights (locality: source, i.e. flights)\n avg_seats_per_flight is source.avg(aircraft.aircraft_models.seats)\n -- avg seats per aircraft model (locality: aircraft_models)\n avg_seats_per_model is aircraft.aircraft_models.seats.avg()\n}\n```\n\nThree syntactic forms:\n\n- `avg(expr)` \u2014 aggregate at the current source (implicit locality)\n- `joined_source.avg(expr)` \u2014 aggregate at the specified join point (explicit locality)\n- `joined_source.field.avg()` \u2014 shorthand for aggregating the field at its parent source\n\nFor `sum` and `avg` (asymmetric aggregates), when the expression crosses a join boundary, Malloy *requires* explicit locality \u2014 it won\'t silently give you a wrong answer. For `min`, `max`, and `count` (symmetric), locality doesn\'t change the result, so implicit is always fine.\n\nMalloy implements this with a technique called **symmetric aggregates** \u2014 it internally de-duplicates rows based on primary keys at the appropriate join level, so aggregations are always mathematically correct regardless of join fan-out.\n\n## Ungrouped Aggregates\n\n`all()` and `exclude()` allow computing aggregates at different grouping levels within a single query:\n\n```malloy\nrun: airports -> {\n group_by: state, faa_region\n aggregate:\n airport_count is count()\n total_airports is all(count()) -- ungrouped: total across all rows\n region_airports is all(count(), faa_region) -- grouped only by faa_region\n pct_of_total is count() / all(count())\n}\n```\n\n`all(expr)` removes all grouping. `all(expr, dim1, dim2)` keeps only the specified grouping dimensions. `exclude(expr, dim)` removes the specified dimension from grouping.\n\n**Important:** `all(expr, dim)` takes the **local alias name** as defined in the query\'s `group_by:`, not a dotted path. If you want to partition by a joined field, alias it first:\n\n```malloy\n-- WRONG: all(count(), director.primaryName) -- dot paths don\'t work here\n-- RIGHT:\nrun: movies -> {\n group_by: director is director.primaryName -- alias it\n aggregate:\n movies is count()\n director_total is all(count(), director) -- reference the alias\n pct is count() / all(count(), director)\n}\n```\n\n## Expressions\n\nMalloy expressions include arithmetic, comparison, logical operators, function calls, type casts, and several Malloy-specific forms.\n\n### Evaluation Spaces\n\nEvery expression has an evaluation space: **literal**, **constant**, **input**, or **output**. Input expressions reference source columns/dimensions. Output expressions reference the results of the current query stage (used in `calculate:`). Some functions constrain their arguments \u2014 e.g., `lag(expr)` requires an output expression, `avg(expr)` requires an input expression.\n\n### Application and Partial Comparison\n\nThe `?` operator applies a condition to a value. Partial comparisons are conditions without a left-hand side:\n\n```malloy\nwhere: state ? \'CA\' | \'NY\' -- state is \'CA\' or \'NY\'\nwhere: distance ? > 500 & < 2000 -- distance between 500 and 2000\n```\n\n`|` is alternation (OR), `&` is conjunction (AND) within partials.\n\n### Pick Expressions\n\nMalloy\'s equivalent of CASE:\n\n```malloy\ndimension: size_bucket is\n pick \'short\' when distance < 500\n pick \'medium\' when distance < 1500\n else \'long\'\n```\n\n### Filtered Aggregate Expressions\n\nAny aggregate can be filtered inline:\n\n```malloy\nmeasure: ca_flights is count() { where: origin.state = \'CA\' }\n```\n\n### Type Casting\n\n```malloy\ntotal_distance::string -- Malloy type cast\nname::"VARCHAR(32)" -- database-native type cast\n```\n\n### Time Literals and Ranges\n\n```malloy\n@2003 -- the year 2003\n@2003-Q2 -- second quarter of 2003\n@2024-01-15 10:30:00 -- timestamp literal\ndep_time ? @2003 to @2005 -- range comparison\nnow -- current timestamp\n```\n\n## Data Types\n\nMalloy\'s type system: `string`, `number`, `boolean`, `date`, `timestamp`, `timestamptz`, `json`, and `sql native` (for unsupported database types). Compound types: `type[]` for arrays, `{ name :: type, ... }` for records, nesting arbitrarily: `{ x :: number, tags :: string[] }[]`.\n\n## Annotations and Tags\n\nThese are related but distinct concepts.\n\n### Annotations\n\nAnnotations are **text strings** attached to objects during compilation. They are metadata \u2014 they never affect query execution or SQL generation. An annotation starts with `#` and continues to end of line:\n\n```malloy\n# bar_chart\nview: by_carrier is { ... }\n```\n\n- `#` annotations attach to the next object defined below them\n- `##` annotations attach to the model (the file)\n- Block annotations use `#|` ... `|#` for multi-line content (closing delimiter must match the column position of the opener)\n\nAnnotations distribute over definition lists:\n\n```malloy\n# currency\nmeasure: -- all three measures get the # currency annotation\n revenue is sum(amount)\n # percent -- this measure also gets # percent\n margin is revenue / cost\n cost is sum(amount)\n```\n\n### Tags (a use of annotations)\n\nTags are the primary *consumer* of annotation strings. They interpret annotation text using a structured property language (MOTLY). The key distinction: **annotations are the transport mechanism (raw strings attached to objects), tags are the interpretation layer (parsed key-value properties).**\n\nNot all annotations are tags. An annotation is just text. Tags are annotations that happen to be written in the tag property language and parsed by an application.\n\n### Annotation prefixes (routing)\n\nThe character(s) immediately after `#` route the annotation to different consumers:\n\n- `# ` (hash-space) \u2014 renderer tags, parsed by the Malloy VS Code extension for visualization (`# bar_chart`, `# line_chart`, `# shape_map`; `# link { url_template="https://\u2026/$$" }` turns a field\'s cell into a clickable deep link \u2014 `$$` is the cell value, `field=other` links on a different (often `# hidden`) field; `# image { url_template=\u2026 }` renders it as an image)\n- `##!` \u2014 compiler directives (e.g., `##! experimental.parameters`, `##! experimental.givens`)\n- `#"` \u2014 reserved for documentation strings\n- `#(appName)` \u2014 application-specific tags (e.g., `#(docs) hidden`)\n\n```malloy\n# bar_chart size=large -- renderer tag: tells VS Code how to render\n##! experimental.parameters -- compiler tag: enables a feature flag\n#(myApp) priority=high -- custom app tag: ignored by renderer/compiler\n```\n\n### Tag property syntax\n\n```\ntName -- boolean flag (exists = true)\ntName=value -- set property value\ntName=[a, b, c] -- array value\ntName: { p1=v1 p2=v2 } -- nested properties (replaces)\ntName { p1=v1 } -- nested properties (merges)\n-tName -- delete a property\ntName.sub.path=value -- deep path assignment\n```\n\nValues can be unquoted identifiers, quoted strings, numbers, or typed values prefixed with `@` (`@true`, `@false`, `@2024-01-15`).\n\n## Givens (Model-Level Parameters)\n\n**Status: experimental, gated by `##! experimental.givens`.** Naming is provisional.\n\nGivens are values supplied at run time that the model can reference in any expression. The motivating use case is row-level access control \u2014 a model written once with `where: x.tenant_id = $TENANT` and the tenant supplied per API call \u2014 but they also fit configuration values, session context, and any "one compiled model, many invocations with varying context" pattern.\n\nGivens are model-wide: a single namespace, one value per name per compilation. They are *complementary to* source/query parameters (`source: foo(x :: string) is ...`), not a replacement. Use a parameter when you want two differently-bound copies of the same source side-by-side in one model; use a given when you want one value visible everywhere in the compilation.\n\n### Declaration\n\nThe `given:` top-level statement introduces givens, with a name, a type, and an optional default:\n\n```malloy\ngiven:\n TENANT :: string\n MAX_ROWS :: number is 1000\n CUTOFF_DATE :: date is @2024-01-01\n```\n\nType can be any Malloy atomic type or compound type, including `filter<T>`:\n\n```malloy\ngiven:\n ROLE :: string\n ALLOWED_ROLES :: string[]\n SESSION :: { user_id :: string, tenant :: string }\n TENANT_FILTER :: filter<string>\n```\n\nDefaults are expressions over constants and other givens. Annotations attach to given declarations the same way they attach to sources or measures.\n\n### Reference: the `$` sigil\n\nInside any expression, a given is referenced with a leading `$`:\n\n```malloy\nsource: orders_for_user is orders extend {\n where: orders.tenant_id = $TENANT\n}\n\nquery: recent_orders is orders_for_user -> {\n where: order_date >= $CUTOFF_DATE\n limit: $MAX_ROWS\n}\n```\n\n`$` appears *only* at expression references. The other three sites where a given\'s name appears \u2014 declaration, import, and supply (caller side) \u2014 use the bare name, because syntactic position already disambiguates. Givens share the top-level declaration namespace with sources/queries/views, so `source: x is ...` plus `given: x :: string` is a name-conflict error.\n\n### Set membership: `expr in $arrayGiven`\n\nThe RHS of `in` is either a parenthesized list of expressions (`in (1, 2, x, y * 7)`, same as SQL) or a given with an array value (`in $ARR`). A bare array-typed expression \u2014 a dimension, a joined array field, an inline `[a, b, c]` literal \u2014 is *not* legal on the RHS; arrays only reach the RHS via the given form.\n\nWhen a given has array type, `expr in $ARR` tests `expr` against the runtime-bound array; `not in $ARR` is the negation. The left-hand side must match the array\'s element type (`string in $string[]`, `number in $number[]`, etc.); mismatches are translate-time errors. Records and nested arrays are out of scope.\n\n```malloy\ngiven:\n ALLOWED_STATES :: string[]\n URGENT_STATUSES :: string[]\n\nsource: orders extend {\n where: state in $ALLOWED_STATES\n dimension: is_urgent is order_status in $URGENT_STATUSES\n}\n```\n\nAt SQL emit, the array\'s contents land in a generated `IN (...)` clause. Empty or `null` arrays collapse to the obvious result (`IN` \u2192 `FALSE`, `NOT IN` \u2192 `TRUE`). NULL elements inside a non-empty array follow standard SQL `IN` semantics.\n\nTo derive a value from an array \u2014 typically a boolean gate \u2014 *without* the array itself reaching row-position SQL, use an inline given (below).\n\n### Inline givens\n\nAn `inline` given is evaluated at **bind time**, before SQL is emitted: its default expression runs against the resolved given values and reduces to a literal, and that literal is what reaches SQL.\n\n```malloy\ngiven:\n CAPABILITIES :: string[]\n inline CAN_READ_ORDERS :: boolean is \'read_orders\' in $CAPABILITIES\n inline CAN_MUTATE :: boolean\n is \'write_orders\' in $CAPABILITIES or \'admin\' in $CAPABILITIES\n\nsource: orders extend {\n where: $CAN_READ_ORDERS -- SQL sees: WHERE ... AND TRUE (or FALSE)\n}\n```\n\nThis is the **row-level access-control gate** pattern: the host supplies a capability list as a regular given, an inline given derives a boolean from it, and only the boolean \u2014 not the list \u2014 crosses into row-position SQL. The query planner sees a constant predicate.\n\nRules:\n\n- An inline given **must** have a default. `inline FOO :: number` with no `is` clause is a translate-time error.\n- The default may use:\n - Boolean and comparison operators: `and`, `or`, `not`, `=`, `!=`, `<`, `<=`, `>`, `>=`\n - The `in $array` test against another given\n - Literals (string, number, boolean, null, array) and references to other givens\n- The default cannot call SQL functions, reference fields, or use any operator outside that list. Disallowed operators are reported at translate time with the offending operator names.\n- Inline givens are filtered out of `Model.givens` and `PreparedQuery.givens` \u2014 they\'re computed, not supplied \u2014 so introspection-driven UIs don\'t render editors for them. A caller can still shadow one by binding it explicitly (useful in tests).\n- `inline` is a context-sensitive modifier, not a reserved keyword: fields, sources, views, dimensions, and joins can still be named `inline`.\n\n### Imports\n\nGivens behave like every other top-level named thing under import:\n\n- **Bare import** (`import "b.malloy"`) brings B\'s full export surface in, including all of B\'s givens, under their original names.\n- **Selective import** (`import { source1 } from "b.malloy"`) brings in only what\'s listed. To surface a given to your callers, list it: `import { source1, MAX_ROWS } from "b.malloy"`.\n- **Rename** uses the existing `LOCAL is REMOTE` form: `import { CAP is MAX_ROWS } from "b.malloy"`.\n\nSurfacing controls *who can supply a value*, not whether internal references work. An imported source can reference a given the importer didn\'t surface; the reference still resolves internally, and at run time the unsurfaced given relies on its declaration-site default.\n\nA common project convention is a shared `tenant_givens.malloy` (declaring `$TENANT`, `$USER_ROLE`, etc.) that every root file bare-imports on line 1, so the project\'s given contract is visible at the top of any model.\n\n### Satisfiability\n\nA query referencing `$X` is satisfiable if either `$X` is in the model\'s namespace (so a caller can supply a value) or `$X` has a default at its declaration site. Otherwise the query is unsatisfiable and errors. Latent definitions (views, dimensions, measures) that reference `$X` are fine if no query actually invokes them \u2014 satisfiability is a property of running queries.\n\n### Supplying values\n\nValues can be supplied at two layers, which compose (per-query overrides per-runtime):\n\n**Per-runtime** \u2014 bound to a `Runtime`, applied as defaults to every query through it. Two paths:\n\n1. **`givensPath` in `malloy-config.json`** points at a JSON file of `name \u2192 value`:\n ```jsonc\n { "givensPath": "./local-givens.json" }\n // or env-var indirection (resolved at config load):\n { "givensPath": { "env": "GAME_STORE_GIVENS" } }\n ```\n The values file is a flat JSON map, keys are caller-facing surface names:\n ```jsonc\n { "TENANT": "acme", "USER_ROLE": "admin", "CUTOFF_DATE": "2024-01-01" }\n ```\n\n2. **Direct on the Runtime constructor** (for per-request multi-tenant servers, tests, scripts):\n ```typescript\n const runtime = new Runtime({\n config,\n givens: { TENANT: claims.tenant_id, USER_ROLE: claims.role },\n urlReader,\n });\n ```\n Constructor values *merge over* the file at `givensPath` per-key.\n\n**Per-query** \u2014 supplied on a single `.run({ givens: ... })` call:\n```typescript\nawait query.run({ givens: { STATE_FILTER: "CA", LIMIT_OVERRIDE: 50 } })\n```\nAvailable on every compile-or-run entry point (`runtime.loadQuery(...).run(options)`, `preparedQuery.getPreparedResult(options)`, `preparedQuery.getSQL(options)`).\n\nThe resolved per-runtime values are exposed on `runtime.givens` (read-only) for diagnostics.\n\n### Finalized givens (security primitive)\n\nA multi-tenant deployment usually wants `TENANT`/`USER_ROLE`/`REGION` to be runtime-bound and **un-overridable per-query** \u2014 otherwise a downstream endpoint that accidentally accepts user-controlled query params and plumbs them into `.run({ givens: ... })` becomes a tenant-leak vulnerability.\n\n`finalizeGivens` in the config locks names at the API surface:\n\n```jsonc\n{\n "givensPath": { "env": "GAME_STORE_GIVENS" },\n "finalizeGivens": ["TENANT", "USER_ROLE", "REGION"]\n}\n```\n\nFinalize doesn\'t change *what* a given resolves to \u2014 only *who* can supply it. A `.run({ givens: { TENANT: ... } })` for a finalized name throws at API entry (named, not silently dropped). Finalized givens are filtered out of `Model.givens` and `PreparedQuery.givens` so introspection-driven UIs don\'t render editors for locked names.\n\n### JS shapes for supplied values\n\nBoth the JSON values file and per-query `givens` maps accept the same per-type shapes:\n\n| Malloy type | JS |\n|---|---|\n| `string` | string |\n| `number` | `number`, `bigint`, or string (precision escape hatch) |\n| `boolean` | boolean |\n| `date` | ISO date string `"2024-01-15"` |\n| `timestamp` (naive) | ISO string without offset \u2014 *not* a JS `Date` |\n| `timestamptz` | JS `Date` or ISO string with offset (string preferred \u2014 makes TZ choice visible) |\n| `T[]` | JS array |\n| `{ name :: T, ... }` | JS object |\n| `filter<T>` | JS string (Malloy filter expression source) |\n\nNaive timestamp givens reject `Date` because `Date` represents a UTC instant, not a wall-clock value, and `new Date("2001-01-01T00:00:00")` silently picks up the system\'s local TZ. Type mismatches throw at the boundary with a path that points at the offending location (e.g., `givens.SESSION.user_id: expected string, got number`). `null` is legal for any given type.\n\n### Introspection\n\n`Model.givens` and `PreparedQuery.givens` expose, to the host, the supplyable givens \u2014 for whole-model parameter editors and per-query "run this" forms respectively. Each entry carries name, type, default expression (or undefined if the caller must supply), location, and access to declaration-site annotations via `tagParse`/`getTaglines`.\n\n## How a Malloy Query Becomes SQL\n\nThe compilation pipeline has two phases:\n\n### Phase 1: Translation (source code \u2192 IR)\n\n```\nMalloy source \u2192 ANTLR lexer/parser \u2192 parse tree \u2192 AST builder \u2192 AST \u2192 IR generator \u2192 IR\n```\n\nThe **Intermediate Representation (IR)** is a plain, serializable data structure (JSON-compatible) that fully describes the semantic model and query. Note that IR is *not* dialect-agnostic \u2014 the same Malloy source compiled against different databases can produce different IR, because schema information, type mappings, and available functions vary by backend. It can be cached, transmitted, and reused. Key IR types:\n\n- **`SourceDef`** \u2014 a source\'s complete definition: schema, fields, joins, filters\n- **`Query`** \u2014 a source paired with a pipeline of operations\n- **`FieldDef`** \u2014 definition of any field (dimension, measure, join, calculation)\n- **`Expr`** \u2014 expression tree (arithmetic, comparisons, aggregates, function calls, field references)\n\nThe translator handles all language-level semantics: scoping, name resolution, type checking, evaluation space validation.\n\n### Phase 2: Compilation (IR \u2192 SQL)\n\n```\nIR \u2192 query compiler \u2192 expression compiler \u2192 dialect-specific SQL generator \u2192 SQL + metadata\n```\n\nThe compiler walks the IR query pipeline, translating each stage into SQL constructs (CTEs, subqueries, GROUP BY, window functions). A **Dialect** layer handles database-specific SQL generation.\n\nThe compiler also produces **metadata** alongside the SQL \u2014 structural information needed to interpret the result set (column types, nesting structure, annotation data). This metadata is what allows Malloy renderers to reconstruct nested/hierarchical results from the flat SQL result set and apply visualization tags.\n\n### Key architectural consequences\n\n- Because the IR is serializable, it can be cached and reused across compilations (though IR is database-specific \u2014 the same source compiled against different backends may produce different IR).\n- Because joins are declared in the source (not the query), the compiler knows the full join graph and can compute symmetric aggregates correctly.\n- Because nested queries are first-class, the compiler generates the appropriate SQL (correlated subqueries or ARRAY_AGG patterns depending on dialect) automatically.\n- Because measures are typed as aggregates in the IR, the compiler can validate that they only appear in aggregate context and enforce locality rules.\n\n## Where to Go Deeper\n\nThis document is a conceptual reference \u2014 enough to reason about the language and its design, but not exhaustive. Here\'s where to find more detail.\n\n### Language Documentation\n\nThe full docs live at [https://docs.malloydata.dev](https://docs.malloydata.dev). Key pages by topic:\n\n| Topic | URL |\n|---|---|\n| Sources, extensions, joins, primary keys | [documentation/language/source](https://docs.malloydata.dev/documentation/language/source) |\n| Queries, views, reduction vs projection | [documentation/language/query](https://docs.malloydata.dev/documentation/language/query), [views](https://docs.malloydata.dev/documentation/language/views) |\n| Fields: dimensions, measures, views, calculations | [documentation/language/fields](https://docs.malloydata.dev/documentation/language/fields) |\n| Aggregate functions and aggregate locality | [documentation/language/aggregates](https://docs.malloydata.dev/documentation/language/aggregates) |\n| Ungrouped aggregates (`all`, `exclude`) | [documentation/language/ungrouped-aggregates](https://docs.malloydata.dev/documentation/language/ungrouped-aggregates) |\n| Nested views / aggregating subqueries | [documentation/language/nesting](https://docs.malloydata.dev/documentation/language/nesting) |\n| Joins | [documentation/language/join](https://docs.malloydata.dev/documentation/language/join) |\n| Expressions, operators, pick, apply | [documentation/language/expressions](https://docs.malloydata.dev/documentation/language/expressions) |\n| Evaluation spaces (literal, constant, input, output) | [documentation/language/eval_space](https://docs.malloydata.dev/documentation/language/eval_space) |\n| Filters and filter placement | [documentation/language/filters](https://docs.malloydata.dev/documentation/language/filters) |\n| Annotations and tags | [documentation/language/tags](https://docs.malloydata.dev/documentation/language/tags) |\n| Calculations and window functions | [documentation/language/calculations_windows](https://docs.malloydata.dev/documentation/language/calculations_windows) |\n| Data types | [documentation/language/datatypes](https://docs.malloydata.dev/documentation/language/datatypes) |\n| Time operations, ranges, timezones | [documentation/language/timestamp-operations](https://docs.malloydata.dev/documentation/language/timestamp-operations), [time-ranges](https://docs.malloydata.dev/documentation/language/time-ranges), [timezones](https://docs.malloydata.dev/documentation/language/timezones) |\n| Imports | [documentation/language/imports](https://docs.malloydata.dev/documentation/language/imports) |\n| Top-level statements and model structure | [documentation/language/statement](https://docs.malloydata.dev/documentation/language/statement) |\n| Functions reference | [documentation/language/functions](https://docs.malloydata.dev/documentation/language/functions) |\n\n### Examples and Patterns\n\nThe docs site includes worked examples of common analytical patterns at [documentation/patterns](https://docs.malloydata.dev/documentation/patterns/): percent-of-total, year-over-year, cohort analysis, sessionization, moving averages, nested subtotals, and more.\n\nEnd-to-end guides are at [documentation/user_guides](https://docs.malloydata.dev/documentation/user_guides/), including [Malloy by Example](https://docs.malloydata.dev/documentation/user_guides/malloy_by_example) (a comprehensive walkthrough) and a three-part series for SQL users ([part 1](https://docs.malloydata.dev/documentation/user_guides/sql_experts1), [part 2](https://docs.malloydata.dev/documentation/user_guides/sql_experts2), [part 3](https://docs.malloydata.dev/documentation/user_guides/sql_experts3)).\n\n### Source Code\n\nThe Malloy implementation lives at [github.com/malloydata/malloy](https://github.com/malloydata/malloy). Key entry points:\n\n| What | Where |\n|---|---|\n| ANTLR grammar (lexer + parser) | `packages/malloy/src/lang/grammar/` |\n| AST node hierarchy | `packages/malloy/src/lang/ast/` |\n| Parse tree \u2192 AST builder | `packages/malloy/src/lang/malloy-to-ast.ts` |\n| IR type definitions | `packages/malloy/src/model/malloy_types.ts` |\n| IR \u2192 SQL compiler | `packages/malloy/src/model/` |\n| Dialect-specific SQL generation | `packages/malloy/src/dialect/` |\n| Tag/annotation parsing (MOTLY) | `packages/malloy-tag/` |\n| Renderer | `packages/malloy-render/` |\n| Architecture overview | `CONTEXT.md` (root and in each package) |\n',
217
217
  "language/pick.md": "---\ndescription: pick expressions \u2014 Malloy's CASE/if-then-else\n---\n\n`pick` is Malloy's equivalent of SQL `CASE WHEN`. Each branch is its own\n`pick` keyword; the `else` clause catches the remainder.\n\nThere are two forms of pick. In the first the `when` expression is any\nboolean expression.\n\n```malloy\n pick 'Female' when upper(first_name) in ('JENNIFER', 'ELIZABETH', 'AMY', 'JESSICA')\n pick 'Male' when upper(first_name) in ('JAMES', 'JOHN', 'ROBERT', 'MICHAEL')\n else 'Unknown'\n```\n\n## Example usage in a query\n\n```malloy\nrun: payments -> {\n group_by: tier is\n pick 'high' when total_amount > 10000\n pick 'medium' when total_amount > 1000\n else 'low'\n aggregate: payment_count is count()\n}\n```\n\n## Common mistakes\n\n- **Every branch needs its own `pick` keyword** \u2014 there is no `when \u2026 then`:\n ```malloy\n -- WRONG:\n pick 'a' when x = 1 'b' when x = 2 else 'c'\n\n -- RIGHT:\n pick 'a' when x = 1\n pick 'b' when x = 2\n else 'c'\n ```\n\n- **`else` is required** when the branches don't cover all cases \u2014 omitting it\n returns `null` for unmatched rows.\n",
218
+ "language/who-is-asking.md": "---\ndescription: Per-user data with $MALLOYYO_EMAIL \u2014 the reserved given this server fills from the signed-in user, how to declare it, and how to run the model locally\n---\n\n# Who is asking \u2014 `$MALLOYYO_EMAIL`\n\nA model can scope what a query returns to the person running it. Declare the\nreserved given, then use it like any other:\n\n```malloy\n##! experimental.givens\ngiven:\n MALLOYYO_EMAIL :: string is ''\n\nsource: orders is duckdb.table('orders.parquet') extend {\n where: owner_email = $MALLOYYO_EMAIL\n}\n```\n\nEvery query against that model \u2014 the `query` tool, a dashboard tile, a saved\nquery, an ltool link \u2014 binds it to the signed-in user's address. Nothing else\nchanges: no per-user models, no filtered copies, no query rewriting.\n\n**The declaration is the opt-in.** A model that does not declare it is\nuntouched, because supplying a given a model never declared is an error in\nMalloy rather than a no-op.\n\n## What a caller cannot do\n\nA caller may not set it. A `givens: { \"MALLOYYO_EMAIL\": \"someone@else.com\" }`\non a `query` call, a dashboard's `?MALLOYYO_EMAIL=` URL, a value baked into a\ncomponent \u2014 all dropped before the query compiles, and the signed-in address\nbound instead. That is the whole point of the feature; do not design around it.\n\nFor the same reason it is not offered as a filter: `query(execute:false)` does\nnot list it among the givens to supply, and a dashboard renders no control for\nit.\n\n## The `MALLOYYO_` prefix is reserved\n\n`MALLOYYO_EMAIL` is the only one that exists. Declaring any other\n`MALLOYYO_*` given is refused at publish \u2014 the prefix means \"a value this\nserver vouches for\", and a `$MALLOYYO_ROLE` the server does not fill would read\nas though it did. Name your own givens anything else.\n\n## Running it locally\n\nLocally there is no one asking, so the declaration default applies and a\ntenant-scoped query comes back empty \u2014 which looks exactly like a broken\ndashboard. Put a stand-in in `malloy-config.json`:\n\n```json\n{\n \"malloyyo\": {\n \"test_givens\": { \"MALLOYYO_EMAIL\": \"you@example.com\" }\n }\n}\n```\n\n`malloyyo dashboard dev`, `malloyyo lint` and the CLI's own MCP server bind it\nthe way the server binds the real one, so what you see locally is what a reader\ngets. Change the address to see another tenant's view.\n\nThe block is **local only** \u2014 the server never reads it. It travels with the\nrepo, so if it were honored a repo could name any address and read that\nperson's rows.\n\n## Not `malloyyo dashboard bundle`\n\nA bundled site has no one asking, and cannot have: there is no server, the\nmodel source is inlined into the page, and DuckDB-WASM fetches the data in the\nreader's own browser. `test_givens` does not travel into it either \u2014 the\nbundler only introspects, and the reserved givens are filtered out of what it\nwrites. So a tenant-scoped dashboard bundles to a page that shows nothing.\n\nDo not answer that by loosening the default. `MALLOYYO_EMAIL :: filter<string>\nis f'\u2026'` with anything permissive publishes every row to every visitor, and the\nraw data is one fetch away regardless. **A model that filters by who is asking\nbelongs on an instance, not in a static bundle.**\n\n## Notes\n\n- Give it a default and make sure the default is the SAFE answer. Watch the\n type: `:: string is ''` matches no rows, which is right, but\n `:: filter<string> is f''` is an EMPTY FILTER, which matches EVERY row. The\n server refuses to run a query when it cannot supply the value (an account\n with no address, say) rather than let a default like that through \u2014 but the\n default is still what a local `dashboard dev` run and any non-server path\n will use, so write one that shows nothing.\n- Filtering belongs in the source (`extend { where: \u2026 }`), not in each query \u2014\n that way it holds for every query anyone writes against it, including ones\n an agent composes later.\n- It is a string, not a verified claim about identity beyond sign-in: it is the\n address the signed-in account carries.\n",
218
219
  "site/auto-update.md": '# Auto-update a data site weekly\n\nAdd a scheduled GitHub Actions job that rebuilds the data and commits it, so the\npublished Pages site stays current on its own. Use this **after** the site works\n(built with `yo_help("site/data-site")`). If the data never changes, skip this.\n\nThe worked example is `malloydata/malloyyo-imdb` \u2014 fetch and read its\n`scripts/build_data.sh` and `.github/workflows/refresh-data.yml`; adapt, don\'t\ncopy blindly.\n\n## Precondition: one command that rebuilds the data\n\nThe whole thing rests on a single script that turns the source URL(s) into the\ncommitted parquet \u2014 the same script you\'d run by hand. Keep it linear so it\nreads as a recipe:\n\n```bash\n# scripts/build_data.sh\nset -euo pipefail\ncd "$(dirname "$0")/.."\nbash data/get.sh # 1. download source URLs -> data/\nrm -f data/build.duckdb\nmalloy-cli -c malloy-build.json build transform.malloy # 2. transform\necho "ATTACH \'data/build.duckdb\' AS b (READ_ONLY); -- 3. export -> docs/*.parquet\n COPY b.thing TO \'docs/thing.parquet\' (FORMAT parquet)" | malloyyo sql\n```\n\n(If you used Path A \u2014 direct \u2014 the whole script is just the one\n`echo "COPY (FROM read_..(\'https://\u2026\')) TO \'docs/\u2026\'" | malloyyo sql` command.\nNo `data/get.sh`, `malloy-build.json`, `malloy-cli`, or transform needed \u2014 and\nno standalone `duckdb` either, since `malloyyo sql` uses the embedded one.)\n\nGitignore the working files: `data/*.gz`, `data/*.duckdb`, `MANIFESTS/`.\n\n## The workflow\n\n`.github/workflows/refresh-data.yml`:\n\n```yaml\nname: refresh-data\non:\n schedule:\n - cron: "0 6 * * 0" # weekly, Sunday 06:00 UTC\n workflow_dispatch: # ...and on demand from the Actions tab\njobs:\n refresh:\n runs-on: ubuntu-latest\n permissions:\n contents: write # so the job can commit + push\n steps:\n - uses: actions/checkout@v4\n - uses: actions/setup-node@v4\n with: { node-version: "20" }\n # malloyyo carries its own DuckDB (`malloyyo sql`), so no duckdb CLI to install.\n # Add `@malloydata/cli` only for a `#@ persist` transform (malloy-cli build).\n - run: npm install -g @malloydata/malloyyo @malloydata/cli\n - uses: actions/setup-python@v5 # only if an enrichment step needs it\n with: { python-version: "3.12" }\n - name: Build data\n run: bash scripts/build_data.sh\n - name: Commit refreshed data\n run: |\n git config user.name github-actions\n git config user.email github-actions@github.com\n git add docs/*.parquet\n git commit -m "refresh data $(date -u +%F)" || exit 0 # unchanged = clean no-op\n git push\n```\n\n## Hard-won details (these came from a real first run)\n\n- **`git commit \u2026 || exit 0`** \u2014 an unchanged week means nothing new upstream.\n That is success, not a failed job.\n- **Secondary/enrichment steps must be best-effort.** If the build has a step\n that can fail independently (an external API lookup, an optional metadata\n enrichment) and it isn\'t essential to the data, mark it\n `continue-on-error: true`. Otherwise one flaky API call throws away an\n otherwise-good data refresh \u2014 the commit step never runs and the fresh parquet\n is lost. (In `malloyyo-imdb` this bit us: a poster-image lookup with a missing\n secret failed the whole job until it was made non-blocking.)\n- **Secrets** go in repo settings (Settings \u2192 Secrets and variables \u2192 Actions,\n or `gh secret set NAME`), referenced as `${{ secrets.NAME }}`. A step reading\n a secret that isn\'t set gets an empty string \u2014 pair that with best-effort.\n- **No re-bundle needed for data changes.** The dashboards fetch parquet at\n runtime, so committing fresh parquet updates the live site. Only install\n `@malloydata/malloyyo` and run `malloyyo dashboard bundle` in CI if the job\n also needs to regenerate the HTML (i.e. dashboard code changed \u2014 rare for a\n data refresh).\n- **Test before trusting the schedule.** Push, then Actions tab \u2192 the workflow \u2192\n **Run workflow** (that\'s `workflow_dispatch`). Or `gh workflow run\n refresh-data.yml`, then `gh run watch <id> --exit-status`.\n\n## Git growth, and the flatten\n\nEach committed refresh adds the full parquet to history (~its file size per\nrun). That is intentional simplicity, not a leak. When history gets too big,\nflatten it to a single commit by hand \u2014 **not** as part of the weekly job:\n\n```bash\ngit checkout --orphan flat && git add -A && git commit -m "flatten history"\ngit branch -M flat main && git push -f origin main\n```\n\nOnly do this on a repo you solely own (it force-pushes; other clones must\n`git reset --hard origin/main`). Run it as often or as rarely as you like.\nDocument this in the repo\'s README so future-you remembers it\'s available.\n\n## Done when\n\n- The workflow file is on the default branch (so `workflow_dispatch` shows up)\n- A manual run goes green end-to-end and commits fresh `docs/*.parquet`\n- The Pages site shows the new data\n',
219
220
  "site/data-site.md": '# Build a public data site from a web data pointer\n\nGoal: given one or more **public data URLs**, produce a **GitHub Pages site** of\ninteractive Malloy dashboards that anyone can open in a browser. The data ends\nup as parquet in `docs/`; the dashboards are static HTML that query it\nclient-side with DuckDB-WASM \u2014 so there is no server, no database to run.\n\nTwo reference repos \u2014 read them, they are the ground truth for structure:\n\n- **`malloydata/malloyyo-babynames`** \u2014 the clean base pattern (one model file,\n a few dashboards, `docs/`). Data is static.\n- **`malloydata/malloyyo-imdb`** \u2014 the same, plus a `transform.malloy` that\n cleans raw source files into parquet, plus a **weekly auto-refresh** (that\n part is `yo_help("site/auto-update")`).\n\nFetch either with `gh api repos/<repo>/git/trees/HEAD?recursive=1` and read the\nfiles you need. Match their layout rather than inventing your own.\n\n## The shape of a finished repo\n\n```\nmalloy-config.json connection(s): duckdb (local), optionally md/gs mirrors\nindex.malloy the EXPORT SURFACE \u2014 only what this file exports is live\n<model>.malloy sources, measures, joins, givens (parameters)\nstorage.malloy sources point at the parquet \u2014 docs-local OR an https URL\n (or gs.malloy / md.malloy) same source names, swappable hosting (step 3)\ndashboards/*.malloy the query behind each dashboard\ndashboards/*.jsx the dashboard layout (grid of charts/tables)\ndocs/ PUBLISHED SITE \u2014 bundled HTML (+ the *.parquet if docs-local)\n *.parquet the data, when hosted docs-local (committed; served by Pages)\n *.html .nojekyll written by `malloyyo dashboard bundle`\n.mcp.json written by `malloyyo init` (author-mode Claude)\n```\n\n## Prerequisites (install once)\n\n```bash\nnpm install -g @malloydata/malloyyo # the `malloyyo` command\n```\n\nThat\'s the whole toolchain for the common case. `malloyyo` has **DuckDB built\nin** \u2014 `malloyyo sql` runs SQL (read a URL, `COPY` to parquet) through it, so you\ndo **not** need a standalone `duckdb` CLI.\n\nAdd `@malloydata/cli` (`malloy-cli`) **only** if you do a heavier transform with\nMalloy `#@ persist` (see Path B in `yo_help("site/data-to-parquet")`):\n\n```bash\nnpm install -g @malloydata/cli # only for #@ persist transforms\n```\n\n## Recipe\n\nWork top to bottom. After each step, prove it before moving on.\n\n### 1. Scaffold\n\n```bash\nmkdir my-site && cd my-site && git init\nmalloyyo init # writes .mcp.json (author-mode Claude) + index.malloy stub\n```\n\nCreate `malloy-config.json` with a local DuckDB connection (this is what reads\nthe parquet):\n\n```json\n{ "connections": { "duckdb": { "is": "duckdb" } } }\n```\n\n### 2. Get the web data into `docs/*.parquet`\n\nThis is the one dataset-specific step. Two paths \u2014 pick the simpler one that\nworks. Full detail and copy-paste commands: **`yo_help("site/data-to-parquet")`**.\n\n- **Direct** (default): `malloyyo sql` reads the URL and writes parquet in one\n shot, through the embedded DuckDB:\n ```bash\n echo "COPY (FROM read_csv_auto(\'https://\u2026/thing.csv\')) TO \'docs/thing.parquet\'" | malloyyo sql\n ```\n Use when the web data is already close to what you want to show.\n- **Transform** (when you need to clean / join / rank / reshape): write a\n `transform.malloy` with `#@ persist` sources and build it with `malloy-cli`,\n then export the tables to `docs/*.parquet`. This is the `malloyyo-imdb`\n pattern.\n\nVerify: `malloyyo sql -e "DESCRIBE SELECT * FROM \'docs/thing.parquet\'"` and a\n`SELECT count(*)`.\n\n### 3. Write the model\n\nA storage file \u2014 one source per parquet file \u2014 that the rest of the model builds\non. **Where the parquet lives is a choice** (the two examples differ here):\n\n- **docs-local** (the `malloyyo-imdb` way) \u2014 parquet committed in `docs/`,\n served same-origin by Pages. Self-contained; git carries the data. Address it\n by project-relative path so the same spelling works locally and published:\n ```malloy\n // storage.malloy\n source: thing_table is duckdb.table(\'docs/thing.parquet\') extend {}\n ```\n- **External URL** (the `malloyyo-babynames` way \u2014 it uses `import "gs.malloy"`)\n \u2014 parquet hosted on GCS / a CDN / any https URL; `docs/` holds only the HTML,\n so git stays small. DuckDB-WASM fetches the URL at runtime:\n ```malloy\n // gs.malloy\n source: thing_table is duckdb.table(\'https://storage.googleapis.com/\u2026/thing.parquet\') extend {}\n ```\n\nKeep the **source names identical** across storage files (as babynames does with\n`gs.malloy` / `md.malloy`) so switching hosting is a one-line import change in\nthe model. Start docs-local (simplest); move to a URL if git growth bites.\n\n`<model>.malloy` \u2014 build real sources on top: primary keys, measures, joins,\nand **givens** (the parameters that become the dashboard\'s filter controls).\n`index.malloy` \u2014 re-export exactly the sources/queries/givens the dashboards\nuse. **Only what `index.malloy` exports is visible** to dashboards, `dashboard\ndev`, and the hosted app.\n\nGive each exported source a `#"` doc string. It\'s what `list_sources` shows the\nhosted app and any MCP client, and it\'s the only place to record the things a\nconsumer can\'t infer \u2014 which source answers which question, and any measure\nwhose meaning is subtle.\n\nFor Malloy modeling and givens specifics, lean on the author MCP rather than\nguessing: the repo\'s `.mcp.json` wires `mcp__malloyyo_author__*`. Call\n`mcp__malloyyo_author__compile` to check files and\n`mcp__malloyyo_author__yo_help` for topics (`develop/working-with-models`).\n\nThree shapes that compile, pass `lint`, and still produce a dashboard that looks\nright and isn\'t:\n\n- **A stage-level `where:` zeroes measures that carry their own filters.**\n `count() { where: status = \'Sold\' }` needs the sold rows to reach it; a\n `where: in_cellar` on the stage removes them first and the measure reads 0\n everywhere. Constrain the output with `having:` instead.\n- **Grouping finer than the fact scatters the counts.** Group by an attribute\n that only applies to some rows and the measures over the others split across\n groups and read near-zero. Pick the grain the question is asked at; if you\n need both, group at the coarser one and `nest:` the finer.\n- **Detail tables default to raw field names and bare numbers.** `exit_date` and\n `829.57`, and a null renders as `\u2205`. Tag them \u2014 `# label="Opened"`,\n `# label="Paid" currency` \u2014 and `coalesce(field, \'\')` where empty is\n meaningful rather than missing.\n\nAggregate locality is NOT one of these: Malloy\'s symmetric aggregates keep\nmeasures honest through a `join_many` fan-out, and it warns (or errors) rather\nthan silently answering when an `avg`/`sum` crosses a join without explicit\nlocality. `notes.rating.avg()` already averages at the notes grain; ask for\n`source.avg(notes.rating)` only when you want the fan-out-weighted number. See\n`yo_help language/aggregate-locality-symmetric-aggregates`.\n\n### 4. Author dashboards and preview live\n\nEach dashboard is **one self-contained `dashboards/<name>.malloy`** \u2014 the query,\nits filtering, and the tags that lay it out. The filename is the dashboard\'s\nname and URL slug.\n\n**A `.jsx` is OPTIONAL and most dashboards don\'t need one.** The default form \u2014\nan inline query tagged `# artifact` + `# dashboard { columns=6 }` \u2014 renders KPI\ntiles and a card grid with no React at all. Reach for a sibling\n`dashboards/<name>.jsx` only when you want bespoke layout or presentation the\ntags can\'t express (a hand-built card, a picker, a Vega chart).\n\nAuthor with the `malloyyo_author` MCP and its `yo_help` topics \u2014 **read these,\ndon\'t guess the API**: `dashboards/authoring` (the dashboard file),\n`dashboards/grid-layout` (colspans), `dashboards/charts` (chart tags and their\nchannel rules), `dashboards/givens-and-controls` (filters),\n`dashboards/custom-components` and `dashboards/vega-charts` (only if you add a\n`.jsx`).\n\nPreview in a browser with live reload:\n\n```bash\nmalloyyo dashboard dev # serves at http://localhost:4173\n```\n\nTwo things about `dashboard dev` worth knowing:\n\n- It runs the queries **server-side**, through the same local DuckDB the CLI\n uses \u2014 the browser only renders results. So it works without DuckDB-WASM or\n its CDN extensions, and it is the only way to see a custom component render\n against real data short of publishing.\n- It holds **one long-lived connection set with a warm schema cache** (a\n deliberate tradeoff \u2014 refetching schemas per compile reads like a hang on a\n warehouse). The file watcher hot-reloads your `.malloy` edits and re-discovers\n `# artifact` tags, but nothing invalidates that cache, so a change to the\n DATA\'s shape \u2014 a new column in a parquet \u2014 needs a restart. The tell is\n `\'<column>\' is not defined` in the browser while the CLI and `lint` are green.\n\nIterate here until the dashboards look right. **Look at every dashboard before\nyou call it done**: `malloyyo lint` compiles the dashboards against the model but\ndoes not render them, so it cannot see a chart that throws at render time, a\ncomponent whose CSS resolved to nothing, or a column of raw field names.\n`malloyyo test` previews what the hosted claude.ai app would see.\n\n### 5. Build the static site\n\n```bash\nmalloyyo dashboard bundle --out docs\n# optional: add analytics + a title\nmalloyyo dashboard bundle --out docs --title "My Site" --analytics G-XXXXXXXXXX\n```\n\n`bundle` writes the HTML, `.nojekyll`, and assets into `docs/`, next to the\nparquet from step 2. The pages fetch `./*.parquet` relative to the site root, so\nthe data must already be in `docs/` \u2014 always run the data step before bundling.\n\n### 6. Publish on GitHub Pages\n\nCommit `docs/` and turn on Pages (Settings \u2192 Pages \u2192 Deploy from a branch \u2192\n`main` / `docs`). Full steps + gotchas: **`yo_help("site/github-pages")`**.\n\n### 7. (Optional) Keep it fresh automatically\n\nIf the data comes from a URL that updates over time and you want the site to\ntrack it, add a weekly GitHub Actions refresh \u2014 see\n**`yo_help("site/auto-update")`** (worked example: `malloydata/malloyyo-imdb`).\n\n## Done when\n\n- `malloyyo sql -e "SELECT count(*) FROM \'docs/<file>.parquet\'"` returns real rows\n- `malloyyo lint` passes\n- **you have LOOKED at every dashboard** in `malloyyo dashboard dev` \u2014 each one\n renders with no console errors, every tile has data, and the labels read like\n English rather than column names. `lint` passing is not this; a dashboard can\n compile and still throw at render time.\n- `docs/` has the bundled `*.html` + `.nojekyll` alongside the parquet\n- the Pages URL loads and the dashboards populate (data fetch succeeds)\n',
220
221
  "site/data-to-parquet.md": '# Getting web data into `docs/*.parquet`\n\nThe site queries parquet files (in `docs/`, or at an https URL \u2014 see the model\nstep). This is how you turn a public data URL into that parquet. Pick the\nsimplest path that produces clean data.\n\n`malloyyo sql` runs SQL through malloyyo\'s **embedded DuckDB** \u2014 no standalone\n`duckdb` binary. It takes SQL from `-e`, `-f <file>`, or stdin, and runs against\na connection from `malloy-config.json` (default `duckdb`).\n\n## Path A \u2014 Direct (default)\n\nOne command reads the URL and writes parquet. Best when the web data is already\nclose to what you want to display.\n\n```bash\n# CSV / TSV\necho "COPY (SELECT * FROM read_csv_auto(\'https://example.com/data.csv\'))\n TO \'docs/data.parquet\' (FORMAT parquet)" | malloyyo sql\n\n# TSV, gzipped, tab-delimited, header row (IMDb-style)\necho "COPY (SELECT * FROM read_csv_auto(\'https://example.com/data.tsv.gz\',\n delim=\'\\t\', header=true, all_varchar=true))\n TO \'docs/data.parquet\' (FORMAT parquet)" | malloyyo sql\n\n# JSON / NDJSON\necho "COPY (SELECT * FROM read_json_auto(\'https://example.com/data.json\'))\n TO \'docs/data.parquet\' (FORMAT parquet)" | malloyyo sql\n\n# Already parquet on the web \u2014 just fetch it\ncurl -fsSL -o docs/data.parquet \'https://example.com/data.parquet\'\n```\n\nFor anything longer than a line or two, put the SQL in a file and run it with\n`-f`, so it\'s re-runnable and diffable:\n\n```bash\nmalloyyo sql -f scripts/build.sql # a file of ;-separated statements\n```\n\nNotes:\n- DuckDB autoloads `httpfs` for `https://` reads.\n- Keep only the columns/rows the dashboards need \u2014 `SELECT` the columns and add a\n `WHERE` to drop noise. Smaller parquet = faster page loads.\n- Cast types here if the source is all-strings: `col::INT`, `col::DOUBLE`, etc.\n\n## Path B \u2014 Transform with Malloy (when you need to reshape)\n\nUse when the data needs cleaning, joining across files, ranking, or nesting \u2014\nthe `malloydata/malloyyo-imdb` case. You write the transform once in Malloy;\n`malloy-cli build` materializes it; you export the tables to parquet. This path\nalso needs `@malloydata/cli` (`npm install -g @malloydata/cli`).\n\n**1. A build connection** \u2014 `malloy-build.json` (a DuckDB db just for building):\n\n```json\n{ "connections": { "build": { "is": "duckdb", "databasePath": "data/build.duckdb" } } }\n```\n\n**2. `transform.malloy`** \u2014 read the raw source(s) through the `build`\nconnection and mark each output source with `#@ persist name="\u2026"`:\n\n```malloy\n##! experimental.persistence experimental.virtual_source\n\nsource: raw is build.sql("""\n SELECT * FROM read_csv_auto(\'data/raw.csv.gz\', delim=\'\\t\', all_varchar=true, header=true)\n""")\n\n#@ persist name="thing"\nsource: thing_base is raw -> {\n where: some_count::number > 100\n select: id, name, value is value::number\n calculate: rank is rank() { order_by: value::number desc }\n}\n```\n\nDownload the raw files first (a `data/get.sh` that `wget`s the URLs into `data/`,\ngitignored). Gitignore `data/`, `data/*.duckdb`, and `MANIFESTS/`.\n\n**3. Build, then export the persisted tables to `docs/`** \u2014 the export still\ngoes through `malloyyo sql` (no standalone duckdb needed):\n\n```bash\nrm -f data/build.duckdb\nmalloy-cli -c malloy-build.json build transform.malloy # -> tables in build.duckdb\necho "ATTACH \'data/build.duckdb\' AS b (READ_ONLY);\n COPY b.thing TO \'docs/thing.parquet\' (FORMAT parquet)" | malloyyo sql\n```\n\nThe persist `name=` is the table name inside `build.duckdb`; the `COPY` names the\nserved file (they can differ \u2014 e.g. `thing` \u2192 `docs/mysite_thing.parquet`).\n\nWrap steps 1\u20133 in a single `scripts/build_data.sh` so it is one command, by hand\nand in CI. That\'s exactly what `yo_help("site/auto-update")` automates weekly.\n\n## Either way, verify\n\n```bash\nmalloyyo sql -e "DESCRIBE SELECT * FROM \'docs/thing.parquet\'"\nmalloyyo sql -e "SELECT count(*) FROM \'docs/thing.parquet\'"\n```\n\nThen point a storage source at it (docs-local shown; an https URL works too \u2014\nsee the model step in SKILL.md):\n\n```malloy\nsource: thing_table is duckdb.table(\'docs/thing.parquet\') extend {}\n```\n',
@@ -1050,6 +1051,34 @@ function modelCatalogEntry(model_ref, model) {
1050
1051
  if (sources.length) entry.sources = sources;
1051
1052
  return entry;
1052
1053
  }
1054
+ function isHostsToFill(name, host) {
1055
+ return name in host.values || host.reservedPrefix !== void 0 && name.startsWith(host.reservedPrefix);
1056
+ }
1057
+ function resolveHostGivens(caller, host, declared) {
1058
+ if (!host) return { ok: true, givens: caller };
1059
+ const missing = [...declared].filter((n) => isHostsToFill(n, host) && !(n in host.values)).sort();
1060
+ if (missing.length > 0) return { ok: false, missing };
1061
+ const out = {};
1062
+ for (const [k, v] of Object.entries(caller ?? {})) {
1063
+ if (isHostsToFill(k, host)) continue;
1064
+ out[k] = v;
1065
+ }
1066
+ for (const [k, v] of Object.entries(host.values)) {
1067
+ if (declared.has(k)) out[k] = v;
1068
+ }
1069
+ return { ok: true, givens: Object.keys(out).length > 0 ? out : void 0 };
1070
+ }
1071
+ var HOST_GIVEN_UNAVAILABLE = "host-given-unavailable";
1072
+ function missingHostGivensMessage(missing) {
1073
+ return `${missing.join(", ")}: filled by the host, not by the query, and no value is available for this request. Refused rather than run on the declaration default, which may not be restrictive.`;
1074
+ }
1075
+ function declaredGivenNames(model) {
1076
+ return new Set(model.givens?.keys() ?? []);
1077
+ }
1078
+ function withoutHostGivens(specs, host) {
1079
+ if (!host) return [...specs];
1080
+ return specs.filter((s) => !isHostsToFill(s.name, host));
1081
+ }
1053
1082
  var MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER);
1054
1083
  var MIN_SAFE = -MAX_SAFE;
1055
1084
  function narrowBigint(value) {
@@ -1113,10 +1142,12 @@ async function run(runtime, entry, opts = {}) {
1113
1142
  let materializer;
1114
1143
  let modelQueries;
1115
1144
  let loadProblems;
1145
+ let declared;
1116
1146
  try {
1117
1147
  materializer = runtime.loadModel(entry);
1118
1148
  const model = await materializer.getModel();
1119
1149
  modelQueries = { named: [...model.queries().named], unnamed: model.queries().unnamed };
1150
+ declared = declaredGivenNames(model);
1120
1151
  loadProblems = mapProblems(model.problems);
1121
1152
  } catch (e) {
1122
1153
  if (e instanceof MalloyError2) {
@@ -1170,7 +1201,17 @@ async function run(runtime, entry, opts = {}) {
1170
1201
  }
1171
1202
  query = materializer.loadFinalQuery();
1172
1203
  }
1173
- return executeMaterialized(query, opts, loadProblems, (p) => p, entry.href);
1204
+ const merged = resolveHostGivens(opts.givens, opts.hostGivens, declared);
1205
+ if (!merged.ok) {
1206
+ return {
1207
+ ok: false,
1208
+ problems: [
1209
+ ...loadProblems,
1210
+ codeProblem(HOST_GIVEN_UNAVAILABLE, missingHostGivensMessage(merged.missing), entry.href)
1211
+ ]
1212
+ };
1213
+ }
1214
+ return executeMaterialized(query, { ...opts, givens: merged.givens }, loadProblems, (p) => p, entry.href);
1174
1215
  }
1175
1216
  async function queryGivens(q) {
1176
1217
  try {
@@ -1184,7 +1225,7 @@ async function queryGivens(q) {
1184
1225
  return void 0;
1185
1226
  }
1186
1227
  }
1187
- async function validateRestricted(runtime, entry, query) {
1228
+ async function validateRestricted(runtime, entry, query, opts = {}) {
1188
1229
  let loadProblems;
1189
1230
  let materializer;
1190
1231
  try {
@@ -1207,8 +1248,8 @@ async function validateRestricted(runtime, entry, query) {
1207
1248
  out.sql = (await q.getSQL()).trim();
1208
1249
  } catch {
1209
1250
  }
1210
- const givens = await queryGivens(q);
1211
- if (givens) out.givens = givens;
1251
+ const givens = withoutHostGivens(await queryGivens(q) ?? [], opts.hostGivens);
1252
+ if (givens.length > 0) out.givens = givens;
1212
1253
  }
1213
1254
  return out;
1214
1255
  } catch (e) {
@@ -1221,9 +1262,11 @@ async function validateRestricted(runtime, entry, query) {
1221
1262
  async function runRestricted(runtime, entry, query, opts = {}) {
1222
1263
  let loadProblems;
1223
1264
  let materializer;
1265
+ let declared;
1224
1266
  try {
1225
1267
  materializer = runtime.loadModel(entry);
1226
1268
  const model = await materializer.getModel();
1269
+ declared = declaredGivenNames(model);
1227
1270
  loadProblems = mapProblems(model.problems);
1228
1271
  } catch (e) {
1229
1272
  if (e instanceof MalloyError3) {
@@ -1233,7 +1276,17 @@ async function runRestricted(runtime, entry, query, opts = {}) {
1233
1276
  }
1234
1277
  try {
1235
1278
  const q = materializer.loadRestrictedQuery(query);
1236
- return await executeMaterialized(q, opts, loadProblems, (p) => p, entry.href);
1279
+ const merged = resolveHostGivens(opts.givens, opts.hostGivens, declared);
1280
+ if (!merged.ok) {
1281
+ return {
1282
+ ok: false,
1283
+ problems: [
1284
+ ...loadProblems,
1285
+ codeProblem(HOST_GIVEN_UNAVAILABLE, missingHostGivensMessage(merged.missing), entry.href)
1286
+ ]
1287
+ };
1288
+ }
1289
+ return await executeMaterialized(q, { ...opts, givens: merged.givens }, loadProblems, (p) => p, entry.href);
1237
1290
  } catch (e) {
1238
1291
  if (e instanceof MalloyError3) {
1239
1292
  return { ok: false, problems: [...loadProblems, ...mapProblems(e.problems)] };
@@ -1311,7 +1364,7 @@ function describeGivenSpec(name, g) {
1311
1364
  }
1312
1365
  return spec;
1313
1366
  }
1314
- async function dashboardGivenSpecs(runtime, entry, runExpr) {
1367
+ async function dashboardGivenSpecs(runtime, entry, runExpr, opts = {}) {
1315
1368
  try {
1316
1369
  const mm = runtime.loadModel(entry);
1317
1370
  const pq = await mm.loadQuery(`run: ${runExpr}`).getPreparedQuery();
@@ -1319,7 +1372,7 @@ async function dashboardGivenSpecs(runtime, entry, runExpr) {
1319
1372
  for (const [name, g] of pq.givens) {
1320
1373
  specs.push(describeGivenSpec(name, g));
1321
1374
  }
1322
- return { ok: true, givens: specs };
1375
+ return { ok: true, givens: withoutHostGivens(specs, opts.hostGivens) };
1323
1376
  } catch (e) {
1324
1377
  return { ok: false, error: e instanceof Error ? e.message : String(e) };
1325
1378
  }
@@ -1651,10 +1704,14 @@ async function executeQuery(m, args, fix, result) {
1651
1704
  const givens = argRecord(args, "givens");
1652
1705
  const rowLimit = Math.max(1, Math.min(1e4, argOptNumber(args, "max_rows") ?? DEFAULT_ROW_LIMIT));
1653
1706
  if (!execute) {
1654
- const v = await validateRestricted(m.runtime, m.entry, malloy);
1707
+ const v = await validateRestricted(m.runtime, m.entry, malloy, { hostGivens: m.hostGivens });
1655
1708
  return { ...v, problems: v.problems.map(fix) };
1656
1709
  }
1657
- const full = await runRestricted(m.runtime, m.entry, malloy, { rowLimit, givens });
1710
+ const full = await runRestricted(m.runtime, m.entry, malloy, {
1711
+ rowLimit,
1712
+ givens,
1713
+ hostGivens: m.hostGivens
1714
+ });
1658
1715
  const budgeted = await applyResultBudget(full, result, { toolName: "query", args });
1659
1716
  return { ...budgeted, problems: budgeted.problems.map(fix) };
1660
1717
  }
@@ -2324,6 +2381,39 @@ async function withConnectionDiagnostics(fn) {
2324
2381
  }
2325
2382
  }
2326
2383
 
2384
+ // src/test-givens.ts
2385
+ var RESERVED_PREFIX = "MALLOYYO_";
2386
+ function testGivensFromConfig(configJson) {
2387
+ const out = { givens: {}, warnings: [] };
2388
+ if (!configJson) return out;
2389
+ let raw;
2390
+ try {
2391
+ raw = JSON.parse(configJson);
2392
+ } catch {
2393
+ return out;
2394
+ }
2395
+ const block = raw?.malloyyo?.test_givens;
2396
+ if (block === void 0) return out;
2397
+ if (typeof block !== "object" || block === null || Array.isArray(block)) {
2398
+ out.warnings.push('malloy-config.json: "test_givens" must be an object of name \u2192 value.');
2399
+ return out;
2400
+ }
2401
+ for (const [name, value] of Object.entries(block)) {
2402
+ if (!name.startsWith(RESERVED_PREFIX)) {
2403
+ out.warnings.push(
2404
+ `test_givens: ignoring "${name}" \u2014 only ${RESERVED_PREFIX}* givens are filled by the server, so only those need a local stand-in. Give an ordinary given a default in its declaration, or set it per dashboard with \`# artifact { givens { \u2026 } }\`.`
2405
+ );
2406
+ continue;
2407
+ }
2408
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") {
2409
+ out.warnings.push(`test_givens: ignoring "${name}" \u2014 value must be a string, number or boolean.`);
2410
+ continue;
2411
+ }
2412
+ out.givens[name] = value;
2413
+ }
2414
+ return out;
2415
+ }
2416
+
2327
2417
  // src/host.ts
2328
2418
  var ENTRY = "index.malloy";
2329
2419
  var IDLE_SHUTDOWN_MS = 6e4;
@@ -2370,6 +2460,14 @@ async function makeRunner(root) {
2370
2460
  const reader = fsReader();
2371
2461
  let configPromise = null;
2372
2462
  const getConfig = () => configPromise ??= loadConfig(rootUrl, reader);
2463
+ const testGivens = (() => {
2464
+ try {
2465
+ return testGivensFromConfig(fs2.readFileSync(path3.join(abs, "malloy-config.json"), "utf8"));
2466
+ } catch {
2467
+ return { givens: {}, warnings: [] };
2468
+ }
2469
+ })();
2470
+ const hostGivens = { values: testGivens.givens, reservedPrefix: "MALLOYYO_" };
2373
2471
  let inFlight = 0;
2374
2472
  let idleTimer = null;
2375
2473
  const clearIdleTimer = () => {
@@ -2401,9 +2499,25 @@ async function makeRunner(root) {
2401
2499
  }
2402
2500
  }
2403
2501
  const lease = (fn) => leaseIn(ENTRY, fn);
2502
+ const withLocalHint = (r) => {
2503
+ if (r.ok) return r;
2504
+ const hit = (r.problems ?? []).some((p) => p.code === HOST_GIVEN_UNAVAILABLE);
2505
+ if (!hit) return r;
2506
+ return {
2507
+ ...r,
2508
+ problems: (r.problems ?? []).map(
2509
+ (p) => p.code === HOST_GIVEN_UNAVAILABLE ? {
2510
+ ...p,
2511
+ message: `${p.message} Locally, set it in malloy-config.json: { "malloyyo": { "test_givens": { "MALLOYYO_EMAIL": "you@example.com" } } }`
2512
+ } : p
2513
+ )
2514
+ };
2515
+ };
2404
2516
  return {
2405
2517
  root: abs,
2406
2518
  entryExists: () => fs2.existsSync(path3.join(abs, ENTRY)),
2519
+ /** Anything unusable in `malloyyo.test_givens`, for `lint` to report. */
2520
+ testGivensWarnings: testGivens.warnings,
2407
2521
  async dispose() {
2408
2522
  clearIdleTimer();
2409
2523
  if (!configPromise) return;
@@ -2414,25 +2528,25 @@ async function makeRunner(root) {
2414
2528
  },
2415
2529
  run(runExpr, givens) {
2416
2530
  return lease(
2417
- (runtime, entry) => run(runtime, entry, { runExpr, givens, stableResult: true, rowLimit: 5e3 })
2418
- );
2531
+ (runtime, entry) => run(runtime, entry, { runExpr, givens, hostGivens, stableResult: true, rowLimit: 5e3 })
2532
+ ).then(withLocalHint);
2419
2533
  },
2420
2534
  runIn(entryFile, runExpr, givens) {
2421
2535
  return leaseIn(
2422
2536
  entryFile,
2423
- (runtime, entry) => run(runtime, entry, { runExpr, givens, stableResult: true, rowLimit: 5e3 })
2424
- );
2537
+ (runtime, entry) => run(runtime, entry, { runExpr, givens, hostGivens, stableResult: true, rowLimit: 5e3 })
2538
+ ).then(withLocalHint);
2425
2539
  },
2426
2540
  runText(malloy, givens) {
2427
2541
  return lease(
2428
- (runtime, entry) => runRestricted(runtime, entry, malloy, { givens, stableResult: true, rowLimit: 5e3 })
2429
- );
2542
+ (runtime, entry) => runRestricted(runtime, entry, malloy, { givens, hostGivens, stableResult: true, rowLimit: 5e3 })
2543
+ ).then(withLocalHint);
2430
2544
  },
2431
2545
  runTextIn(entryFile, malloy, givens) {
2432
2546
  return leaseIn(
2433
2547
  entryFile,
2434
- (runtime, entry) => runRestricted(runtime, entry, malloy, { givens, stableResult: true, rowLimit: 5e3 })
2435
- );
2548
+ (runtime, entry) => runRestricted(runtime, entry, malloy, { givens, hostGivens, stableResult: true, rowLimit: 5e3 })
2549
+ ).then(withLocalHint);
2436
2550
  },
2437
2551
  validateText(malloy) {
2438
2552
  return lease((runtime, entry) => validateRestrictedText(runtime, entry, malloy));
@@ -2441,10 +2555,13 @@ async function makeRunner(root) {
2441
2555
  return leaseIn(entryFile, (runtime, entry) => validateRestrictedText(runtime, entry, malloy));
2442
2556
  },
2443
2557
  givensForQuery(runExpr) {
2444
- return lease((runtime, entry) => dashboardGivenSpecs(runtime, entry, runExpr));
2558
+ return lease((runtime, entry) => dashboardGivenSpecs(runtime, entry, runExpr, { hostGivens }));
2445
2559
  },
2446
2560
  givensForQueryIn(entryFile, runExpr) {
2447
- return leaseIn(entryFile, (runtime, entry) => dashboardGivenSpecs(runtime, entry, runExpr));
2561
+ return leaseIn(
2562
+ entryFile,
2563
+ (runtime, entry) => dashboardGivenSpecs(runtime, entry, runExpr, { hostGivens })
2564
+ );
2448
2565
  },
2449
2566
  artifacts() {
2450
2567
  return lease((runtime, entry) => artifactQueries(runtime, entry));
@@ -2459,7 +2576,7 @@ async function makeRunner(root) {
2459
2576
  return leaseIn(entryFile, async (runtime, entry) => {
2460
2577
  const byName = /* @__PURE__ */ new Map();
2461
2578
  for (const tile of tiles) {
2462
- const specs = await dashboardGivenSpecs(runtime, entry, tile);
2579
+ const specs = await dashboardGivenSpecs(runtime, entry, tile, { hostGivens });
2463
2580
  if (specs.ok) {
2464
2581
  for (const s of specs.givens) if (!byName.has(s.name)) byName.set(s.name, s);
2465
2582
  }
@@ -2472,7 +2589,7 @@ async function makeRunner(root) {
2472
2589
  const byName = /* @__PURE__ */ new Map();
2473
2590
  const out = [];
2474
2591
  for (const tile of tiles) {
2475
- const specs = await dashboardGivenSpecs(runtime, entry, tile);
2592
+ const specs = await dashboardGivenSpecs(runtime, entry, tile, { hostGivens });
2476
2593
  const gvs = specs.ok ? specs.givens : [];
2477
2594
  for (const s of gvs) if (!byName.has(s.name)) byName.set(s.name, s);
2478
2595
  out.push({
@@ -2713,6 +2830,9 @@ async function lintDashboards(root) {
2713
2830
  }
2714
2831
  async function runLint(abs, runner) {
2715
2832
  const dashboards = [];
2833
+ if (runner.testGivensWarnings.length > 0) {
2834
+ dashboards.push({ name: "malloy-config.json", errors: [], warnings: [...runner.testGivensWarnings] });
2835
+ }
2716
2836
  if (runner.entryExists()) {
2717
2837
  const arts = await runner.artifacts();
2718
2838
  if (!arts.ok) dashboards.push({ name: "index.malloy", errors: [arts.error], warnings: [] });
@@ -2902,7 +3022,7 @@ function clearCreds(url6) {
2902
3022
  }
2903
3023
 
2904
3024
  // package.json
2905
- var version = "0.2.51";
3025
+ var version = "0.2.52";
2906
3026
 
2907
3027
  // src/http.ts
2908
3028
  var USER_AGENT = `malloyyo/${version}`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@malloydata/malloyyo",
3
- "version": "0.2.51",
3
+ "version": "0.2.52",
4
4
  "description": "Publish Malloy models to a Malloyyo instance",
5
5
  "license": "MIT",
6
6
  "repository": {