@modelform/react-native 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -14,6 +14,8 @@ same format. One JSON model describes both what an app records and how it charts
14
14
  instance's HTTP API. You can also implement your own.
15
15
  - **Configs:** a manifest format for whole apps (tabs, forms and dashboards), with JSON Schemas, validation that
16
16
  reports issues instead of throwing, and a loader with caching and last-good fallback.
17
+ - **AI assistants:** `templatePrompt()` writes a prompt for making a template with any assistant (Claude, ChatGPT…),
18
+ and `readTemplateAnswer()` reads the template back out of its reply. Nothing calls a model.
17
19
 
18
20
  modelform is not affiliated with or endorsed by Grafana Labs. It reads the dashboard JSON model that Grafana
19
21
  exports, and ignores keys it doesn't understand.
@@ -11567,6 +11567,235 @@ function applyTemplate(manifestText, paths, template, options = {}) {
11567
11567
  return { manifest: applyJsonEdits(manifestText, edits), files: out, ids, tabs: added };
11568
11568
  }
11569
11569
 
11570
+ // src/core/authoring.ts
11571
+ var AUTHORING_GUIDE = `# modelform templates
11572
+
11573
+ A template is JSON that adds forms (for recording entries) and dashboards (for charting them) to an app, plus tabs to show them.
11574
+
11575
+ \`\`\`
11576
+ {
11577
+ "$modelform": "template",
11578
+ "version": 1,
11579
+ "title": "Short name",
11580
+ "description": "One sentence on what it's for.",
11581
+ "documents": [ { "kind": "form" | "dashboard", "id": "letters-digits-dashes", "dashboard": { ...document } } ],
11582
+ "tabs": [ ...tabs ]
11583
+ }
11584
+ \`\`\`
11585
+
11586
+ ## Documents
11587
+
11588
+ A document is a subset of Grafana's dashboard JSON: \`{ "kind": "form" | "dashboard", "title": "\u2026", "panels": [ \u2026 ] }\`, and dashboards add \`"time": { "from": "now-30d", "to": "now" }\`. Its \`kind\` matches its entry in \`documents\`.
11589
+
11590
+ Every panel has an \`id\` (a number, unique in its document), a \`type\`, a \`title\`, and a \`gridPos\` \`{ "x", "y", "w", "h" }\` on a 24-column grid: \`w: 24\` is full width, \`w: 12\` half. Stack panels top to bottom with no gaps or overlaps (each \`y\` is the previous \`y + h\` unless they sit side by side). On phones panels show full width in that order.
11591
+
11592
+ A \`"row"\` panel (\`h: 1\`, no options) is a section heading for the panels under it, in forms and dashboards.
11593
+
11594
+ ## Forms
11595
+
11596
+ Forms hold input panels. Each records to a \`metric\` (lowercase words joined with dashes, e.g. \`"body-weight"\`), and charts read entries by that metric. Two inputs never share a metric. Use \`h: 3\` for inputs.
11597
+
11598
+ | type | what | options besides metric |
11599
+ |---|---|---|
11600
+ | input-number | a number typed or stepped with + and \u2212 | unit, step, min, max |
11601
+ | input-slider | a value dragged along a range | min, max, step, unit, labels (text spread along the track) |
11602
+ | input-select | one of a set of choices | choices: [{ "label", "value" }], multi (allow several) |
11603
+ | input-toggle | yes or no (records 1 or 0) | |
11604
+ | input-rating | a score, e.g. 1 to 5 | min, max |
11605
+ | input-text | free text | placeholder, suggest (offer earlier values) |
11606
+ | input-counter | taps that add up, e.g. glasses of water | increment, unit |
11607
+ | input-duration | a length of time, recorded in seconds | placeholder |
11608
+
11609
+ Any input (not counter) can also take \`required: true\`, \`default\` (a value, or \`"last"\` for the last one saved), and \`record: "always"\` to record its value on every save even when it wasn't changed.
11610
+
11611
+ \`input-group\` repeats fields once per item, for things like the sets of a workout or the dishes of a meal. Give it \`h: 12\` and options \`{ "itemTitle": "Set", "titleFrom": "<a field's metric>", "start": 1 | "last", "min", "max", "fields": [ { "type": "input-\u2026", "title", "span": 1\u201324, "options": { "metric", \u2026 } } ] }\`. Fields can be any input but input-counter.
11612
+
11613
+ ## Dashboards
11614
+
11615
+ Chart panels read the app's entries with \`"datasource": { "type": "modelform-local" }\` and \`"targets": [ { "refId": "A", "metric": "\u2026" } ]\` (refIds A, B, C\u2026 for more series). A target can also have:
11616
+
11617
+ - \`aggregate\`: "sum", "avg", "min", "max", "count" or "last", with \`bucket\`: "1h", "1d", "1w" or "1M". Without them each entry is a point.
11618
+ - \`groupBy\`: "text" for one series per text or choice value; \`{ "field": "<metric>" }\` for one series per value of another input saved at the same time (in an input-group, of the same item, e.g. weight per exercise).
11619
+ - \`alias\`: the series name. \`fillZero: false\` leaves empty buckets out.
11620
+
11621
+ | type | use for | h |
11622
+ |---|---|---|
11623
+ | timeseries | values over time | 7\u20138 |
11624
+ | barchart | totals per day, week or category | 7\u20138 |
11625
+ | stat | one big number; \`"options": { "reduceOptions": { "calcs": ["lastNotNull" or "mean" or "sum"] } }\` | 4 |
11626
+ | gauge, bargauge | a value against a range (set min and max) | 5\u20136 |
11627
+ | piechart | how a total splits, e.g. by choice with groupBy "text" and aggregate "count" | 8 |
11628
+ | table | rows of values | 8 |
11629
+ | text | markdown notes: \`"options": { "content": "\u2026" }\`, no targets | 3\u20134 |
11630
+
11631
+ Units and ranges go in \`"fieldConfig": { "defaults": { "unit": "\u2026", "min", "max", "decimals" } }\`. Units are Grafana's, e.g. "percent", "masskg", "lengthkm", "s", or "suffix: <text>" for anything else (\`"suffix: glasses"\`). Don't use trend, xychart or geomap panels.
11632
+
11633
+ Charts can't do arithmetic across metrics (weight \xD7 reps, a ratio of two inputs). Chart what's recorded instead, or add an input for the combined value, and say which you did in the sentence before the JSON.
11634
+
11635
+ ## Tabs
11636
+
11637
+ \`{ "id": "\u2026", "title": "\u2026", "icon": "\u2026", "screen": \u2026 }\`, where the screen is one of:
11638
+
11639
+ - \`{ "type": "forms", "forms": ["<form id>", \u2026] }\`
11640
+ - \`{ "type": "dashboard", "dashboard": "<dashboard id>" }\`
11641
+ - \`{ "type": "menu", "items": [ { "form": "<id>" } or { "dashboard": "<id>", "description": "\u2026" } ] }\`
11642
+
11643
+ Usually one tab for the forms and one per dashboard.
11644
+ `;
11645
+ var EXAMPLE = {
11646
+ $modelform: "template",
11647
+ version: 1,
11648
+ title: "Water and sleep",
11649
+ description: "Count glasses of water and log sleep, and see both by day.",
11650
+ documents: [
11651
+ {
11652
+ kind: "form",
11653
+ id: "today",
11654
+ dashboard: {
11655
+ kind: "form",
11656
+ title: "Today",
11657
+ panels: [
11658
+ { id: 1, type: "input-counter", title: "Water", gridPos: { x: 0, y: 0, w: 24, h: 3 }, options: { metric: "water", unit: "glasses" } },
11659
+ { id: 2, type: "input-duration", title: "Sleep", gridPos: { x: 0, y: 3, w: 12, h: 3 }, options: { metric: "sleep" } },
11660
+ { id: 3, type: "input-rating", title: "Sleep quality", gridPos: { x: 12, y: 3, w: 12, h: 3 }, options: { metric: "sleep-quality", min: 1, max: 5 } }
11661
+ ]
11662
+ }
11663
+ },
11664
+ {
11665
+ kind: "dashboard",
11666
+ id: "by-day",
11667
+ dashboard: {
11668
+ kind: "dashboard",
11669
+ title: "By day",
11670
+ time: { from: "now-30d", to: "now" },
11671
+ panels: [
11672
+ {
11673
+ id: 1,
11674
+ type: "stat",
11675
+ title: "Average sleep",
11676
+ gridPos: { x: 0, y: 0, w: 12, h: 4 },
11677
+ datasource: { type: "modelform-local" },
11678
+ targets: [{ refId: "A", metric: "sleep" }],
11679
+ fieldConfig: { defaults: { unit: "s" } },
11680
+ options: { reduceOptions: { calcs: ["mean"] } }
11681
+ },
11682
+ {
11683
+ id: 2,
11684
+ type: "stat",
11685
+ title: "Water today",
11686
+ gridPos: { x: 12, y: 0, w: 12, h: 4 },
11687
+ datasource: { type: "modelform-local" },
11688
+ targets: [{ refId: "A", metric: "water", aggregate: "sum", bucket: "1d" }],
11689
+ fieldConfig: { defaults: { unit: "suffix: glasses", decimals: 0 } },
11690
+ options: { reduceOptions: { calcs: ["lastNotNull"] } }
11691
+ },
11692
+ {
11693
+ id: 3,
11694
+ type: "barchart",
11695
+ title: "Water per day",
11696
+ gridPos: { x: 0, y: 4, w: 24, h: 7 },
11697
+ datasource: { type: "modelform-local" },
11698
+ targets: [{ refId: "A", metric: "water", alias: "Glasses", aggregate: "sum", bucket: "1d" }],
11699
+ fieldConfig: { defaults: { min: 0, decimals: 0 } }
11700
+ },
11701
+ {
11702
+ id: 4,
11703
+ type: "timeseries",
11704
+ title: "Sleep quality",
11705
+ gridPos: { x: 0, y: 11, w: 24, h: 7 },
11706
+ datasource: { type: "modelform-local" },
11707
+ targets: [{ refId: "A", metric: "sleep-quality", alias: "Quality", aggregate: "avg", bucket: "1d", fillZero: false }],
11708
+ fieldConfig: { defaults: { min: 1, max: 5 } }
11709
+ }
11710
+ ]
11711
+ }
11712
+ }
11713
+ ],
11714
+ tabs: [
11715
+ { id: "today", title: "Today", icon: "edit", screen: { type: "forms", forms: ["today"] } },
11716
+ { id: "by-day", title: "By day", icon: "chart", screen: { type: "dashboard", dashboard: "by-day" } }
11717
+ ],
11718
+ metrics: ["water", "sleep", "sleep-quality"]
11719
+ };
11720
+ var EXAMPLE_TEMPLATE = EXAMPLE;
11721
+ function templatePrompt(request, { recorded = [], icons = [] } = {}) {
11722
+ const context = [
11723
+ recorded.length ? `The app already records these metrics: ${recorded.map((m) => `\`${m}\``).join(", ")}. Charts can read them. A new form should only record one of them if it's for the same thing; otherwise pick new names.` : "The app doesn\u2019t record anything yet.",
11724
+ icons.length ? `Tab icons can be: ${icons.map((i) => `\`${i}\``).join(", ")}.` : ""
11725
+ ].filter(Boolean);
11726
+ return [
11727
+ "I\u2019m building an app with modelform studio. Make me a modelform template for this:",
11728
+ "",
11729
+ request.trim().replace(/^/gm, "> "),
11730
+ "",
11731
+ ...context,
11732
+ "",
11733
+ "Reply with the template as one ```json code block. A sentence before it is fine; nothing after it.",
11734
+ "",
11735
+ AUTHORING_GUIDE,
11736
+ "## Example",
11737
+ "",
11738
+ "```json",
11739
+ JSON.stringify(EXAMPLE),
11740
+ "```"
11741
+ ].join("\n");
11742
+ }
11743
+ function jsonFromAnswer(text) {
11744
+ const blocks = [...text.matchAll(/```(?:json|JSON)?[ \t]*\r?\n([\s\S]*?)```/g)].map((m) => m[1]);
11745
+ const start = text.indexOf("{");
11746
+ const end = text.lastIndexOf("}");
11747
+ if (start >= 0 && end > start) blocks.push(text.slice(start, end + 1));
11748
+ for (const block of blocks.reverse()) {
11749
+ try {
11750
+ return JSON.parse(block);
11751
+ } catch (e22) {
11752
+ }
11753
+ }
11754
+ throw new Error("There\u2019s no JSON in that answer");
11755
+ }
11756
+ function readTemplateAnswer(text) {
11757
+ let json;
11758
+ try {
11759
+ json = jsonFromAnswer(text);
11760
+ } catch (e) {
11761
+ return { error: e.message };
11762
+ }
11763
+ const parsed = parseTemplate(JSON.stringify(json));
11764
+ if ("error" in parsed) return parsed;
11765
+ const { template } = parsed;
11766
+ const raw = json;
11767
+ const warnings = raw.documents.flatMap(
11768
+ (d) => prepareDashboard(d.dashboard, d.id).issues.filter((i) => i.severity === "warning").map((i) => `${i.path}: ${i.message}`)
11769
+ );
11770
+ const kept = new Set(template.tabs.map((t) => t.id));
11771
+ for (const [i, tab] of (Array.isArray(raw.tabs) ? raw.tabs : []).entries()) {
11772
+ const id = _optionalChain([tab, 'optionalAccess', _332 => _332.id]);
11773
+ if (typeof id !== "string" || !kept.has(id)) warnings.push(`tabs[${i}] was left out: it needs an id, a title and a screen showing only this template\u2019s documents`);
11774
+ }
11775
+ const kinds = new Map(template.documents.map((d) => [d.id, d.kind]));
11776
+ for (const tab of template.tabs)
11777
+ for (const ref of screenDocuments(tab.screen)) {
11778
+ const kind = kinds.get(ref.id);
11779
+ if (kind && kind !== ref.kind) warnings.push(`tab "${tab.id}" shows "${ref.id}" as a ${ref.kind}, but it\u2019s a ${kind}`);
11780
+ }
11781
+ return { template, warnings };
11782
+ }
11783
+ function fixTemplatePrompt(problems) {
11784
+ return [
11785
+ "modelform couldn\u2019t use that template as it was:",
11786
+ "",
11787
+ ...problems.map((p) => `- ${p}`),
11788
+ "",
11789
+ "Fix these and reply with the whole corrected template as one ```json code block."
11790
+ ].join("\n");
11791
+ }
11792
+
11793
+
11794
+
11795
+
11796
+
11797
+
11798
+
11570
11799
 
11571
11800
 
11572
11801
 
@@ -11791,4 +12020,4 @@ function applyTemplate(manifestText, paths, template, options = {}) {
11791
12020
 
11792
12021
 
11793
12022
 
11794
- exports.frameLength = frameLength; exports.timeField = timeField; exports.numberFields = numberFields; exports.fieldDisplayName = fieldDisplayName; exports.toSeries = toSeries; exports.toXYSeries = toXYSeries; exports.uniqueNames = uniqueNames; exports.toMillis = toMillis; exports.parseTime = parseTime; exports.parseRange = parseRange; exports.addTime = addTime; exports.startOf = startOf; exports.parseDuration = parseDuration; exports.calculateInterval = calculateInterval; exports.formatDuration = formatDuration; exports.TIME_PRESETS = TIME_PRESETS; exports.RELATIVE_RANGES = RELATIVE_RANGES; exports.parseLocalDateTime = parseLocalDateTime; exports.formatLocalDateTime = formatLocalDateTime; exports.timeExprError = timeExprError; exports.describeRange = describeRange; exports.zoomRange = zoomRange; exports.ALL = ALL; exports.initialVariableValues = initialVariableValues; exports.variableOptions = variableOptions; exports.variableInfo = variableInfo; exports.visibleVariables = visibleVariables; exports.isSqlDatasource = isSqlDatasource; exports.framesToOptions = framesToOptions; exports.refineOptions = refineOptions; exports.selectValue = selectValue; exports.variableReferences = variableReferences; exports.interpolate = interpolate; exports.queryParam = queryParam; exports.interpolateDeep = interpolateDeep; exports.resolveTimezone = resolveTimezone; exports.valueText = valueText; exports.GRID_COLUMNS = GRID_COLUMNS; exports.gridUnitsToPx = gridUnitsToPx; exports.gridOffsetPx = gridOffsetPx; exports.compactGrid = compactGrid; exports.isRow = isRow; exports.layoutDashboard = layoutDashboard; exports.repeatOptions = repeatOptions; exports.panelKey = panelKey; exports.panelSpan = panelSpan; exports.applyTransformations = applyTransformations; exports.DASHBOARD_DS = DASHBOARD_DS; exports.dashboardSourceIds = dashboardSourceIds; exports.panelHasQueries = panelHasQueries; exports.queryPanel = queryPanel; exports.normalizeRef = normalizeRef; exports.refreshedVariables = refreshedVariables; exports.variableDependents = variableDependents; exports.variableOrder = variableOrder; exports.resolveVariables = resolveVariables; exports.REDUCER_LABELS = REDUCER_LABELS; exports.isReducer = isReducer; exports.reduce = reduce; exports.INPUT_OPTION_KEYS = INPUT_OPTION_KEYS; exports.INPUT_TYPES = INPUT_TYPES; exports.isInputType = isInputType; exports.isInputPanel = isInputPanel; exports.INPUT_GROUP = INPUT_GROUP; exports.isFormPanelType = isFormPanelType; exports.isInputGroup = isInputGroup; exports.GROUP_FIELD_TYPES = GROUP_FIELD_TYPES; exports.groupFields = groupFields; exports.inputPanels = inputPanels; exports.documentKind = documentKind; exports.inputGroups = inputGroups; exports.plainInputPanels = plainInputPanels; exports.parseClockDigits = parseClockDigits; exports.formatClock = formatClock; exports.toEntries = toEntries; exports.newSaveId = newSaveId; exports.isEmptyItem = isEmptyItem; exports.groupToEntries = groupToEntries; exports.entriesToItems = entriesToItems; exports.groupProblems = groupProblems; exports.sameSave = sameSave; exports.inputProblem = inputProblem; exports.entryToInputValue = entryToInputValue; exports.textSuggestions = textSuggestions; exports.entriesSavedWith = entriesSavedWith; exports.formatValue = formatValue; exports.thresholdStep = thresholdStep; exports.NAMED_COLORS = NAMED_COLORS; exports.resolveColor = resolveColor; exports.SERIES_PALETTE = SERIES_PALETTE; exports.seriesColor = seriesColor; exports.mappedResult = mappedResult; exports.formatDisplay = formatDisplay; exports.valueColor = valueColor; exports.resolveFieldConfig = resolveFieldConfig; exports.fieldMatches = fieldMatches; exports.GrafanaError = GrafanaError; exports.GrafanaClient = GrafanaClient; exports.GrafanaDataSource = GrafanaDataSource; exports.fromWire = fromWire; exports.LOCAL_DATASOURCE_TYPE = LOCAL_DATASOURCE_TYPE; exports.isLocalDatasource = isLocalDatasource; exports.LocalDataSource = LocalDataSource; exports.groupField = groupField; exports.buildFrames = buildFrames; exports.MemoryEntryStore = MemoryEntryStore; exports.DEFAULT_GAZETTEER = DEFAULT_GAZETTEER; exports.parseGazetteer = parseGazetteer; exports.loadGazetteer = loadGazetteer; exports.resolveLinks = resolveLinks; exports.parseDashboardLink = parseDashboardLink; exports.applyDashboardLink = applyDashboardLink; exports.appSchema = appSchema; exports.dashboardSchema = dashboardSchema; exports.pointerToPath = pointerToPath; exports.manifestSchemaIssues = manifestSchemaIssues; exports.dashboardSchemaIssues = dashboardSchemaIssues; exports.cleanDashboard = cleanDashboard; exports.MAPPING_TYPES = MAPPING_TYPES; exports.SPECIAL_MATCHES = SPECIAL_MATCHES; exports.mappingRows = mappingRows; exports.rowsToMappings = rowsToMappings; exports.mappingRow = mappingRow; exports.mappingProblem = mappingProblem; exports.OPTION_CATEGORIES = OPTION_CATEGORIES; exports.UNIT_CHOICES = UNIT_CHOICES; exports.panelOptions = panelOptions; exports.getPath = getPath; exports.optionValue = optionValue; exports.setOption = setOption; exports.setOptionValue = setOptionValue; exports.cleanPanelOptions = cleanPanelOptions; exports.OVERRIDE_MATCHERS = OVERRIDE_MATCHERS; exports.overrideProperties = overrideProperties; exports.panelOverrides = panelOverrides; exports.setOverrides = setOverrides; exports.MANIFEST_VERSION = MANIFEST_VERSION; exports.validateManifest = validateManifest; exports.prepareDashboard = prepareDashboard; exports.validateDashboard = validateDashboard2; exports.validateBundle = validateBundle; exports.resolveUrl = resolveUrl; exports.httpFetchJson = httpFetchJson; exports.defaultFetchJson = defaultFetchJson; exports.BUNDLE_TYPE = BUNDLE_TYPE; exports.BUNDLE_ACCEPT = BUNDLE_ACCEPT; exports.isBundleResponse = isBundleResponse; exports.bundleRoot = bundleRoot; exports.assembleFromResponse = assembleFromResponse; exports.assembleBundle = assembleBundle; exports.fetchBundle = fetchBundle; exports.revalidateBundle = revalidateBundle; exports.ConfigLoader = ConfigLoader; exports.tabIdFor = tabIdFor; exports.screenOfType = screenOfType; exports.screenDocuments = screenDocuments; exports.documentUses = documentUses; exports.stringifyCompact = stringifyCompact; exports.applyJsonEdits = applyJsonEdits; exports.diffJson = diffJson; exports.documentIdFor = documentIdFor; exports.removeDocumentFromManifest = removeDocumentFromManifest; exports.renameDocumentInManifest = renameDocumentInManifest; exports.metricChanges = metricChanges; exports.REFRESH_CHOICES = REFRESH_CHOICES; exports.EDITABLE_VARIABLE_TYPES = EDITABLE_VARIABLE_TYPES; exports.isEditableVariableType = isEditableVariableType; exports.variableNameError = variableNameError; exports.newVariable = newVariable; exports.variableWithType = variableWithType; exports.variableWithQuery = variableWithQuery; exports.variableWithCurrent = variableWithCurrent; exports.variableWithFlags = variableWithFlags; exports.variableUses = variableUses; exports.renameVariableInPanels = renameVariableInPanels; exports.lineColumn = lineColumn; exports.parseJsonText = parseJsonText; exports.splitPath = splitPath; exports.locate = locate; exports.checkFiles = checkFiles; exports.bundleFromFiles = bundleFromFiles; exports.formatJsonText = formatJsonText; exports.setJsonValue = setJsonValue; exports.PANEL_TYPES = PANEL_TYPES; exports.newPanel = newPanel; exports.newDocument = newDocument; exports.SaveConflictError = SaveConflictError; exports.HttpConfigFiles = HttpConfigFiles; exports.fetchJsonWithToken = fetchJsonWithToken; exports.readConfigFiles = readConfigFiles; exports.readingOrder = readingOrder; exports.repack = repack; exports.CANVAS_GAP = CANVAS_GAP; exports.CANVAS_ROW_HEADER = CANVAS_ROW_HEADER; exports.panelSize = panelSize; exports.layoutCanvas = layoutCanvas; exports.dropTarget = dropTarget; exports.movePanel = movePanel; exports.resizePanel = resizePanel; exports.setHiddenOnPhones = setHiddenOnPhones; exports.nextPanelId = nextPanelId; exports.insertPanel = insertPanel; exports.duplicatePanel = duplicatePanel; exports.removePanel = removePanel; exports.expandRow = expandRow; exports.collapseRow = collapseRow; exports.settleLayout = settleLayout; exports.placePanel = placePanel; exports.snapToGrid = snapToGrid; exports.panelEdits = panelEdits; exports.sampleEntries = sampleEntries; exports.SNIPPET_VERSION = SNIPPET_VERSION; exports.panelMetrics = panelMetrics; exports.renameMetrics = renameMetrics; exports.copyPanels = copyPanels; exports.parseSnippet = parseSnippet; exports.previewPaste = previewPaste; exports.pasteSnippet = pasteSnippet; exports.TEMPLATE_VERSION = TEMPLATE_VERSION; exports.makeTemplate = makeTemplate; exports.parseTemplate = parseTemplate; exports.templateNeeds = templateNeeds; exports.applyTemplate = applyTemplate;
12023
+ exports.frameLength = frameLength; exports.timeField = timeField; exports.numberFields = numberFields; exports.fieldDisplayName = fieldDisplayName; exports.toSeries = toSeries; exports.toXYSeries = toXYSeries; exports.uniqueNames = uniqueNames; exports.toMillis = toMillis; exports.parseTime = parseTime; exports.parseRange = parseRange; exports.addTime = addTime; exports.startOf = startOf; exports.parseDuration = parseDuration; exports.calculateInterval = calculateInterval; exports.formatDuration = formatDuration; exports.TIME_PRESETS = TIME_PRESETS; exports.RELATIVE_RANGES = RELATIVE_RANGES; exports.parseLocalDateTime = parseLocalDateTime; exports.formatLocalDateTime = formatLocalDateTime; exports.timeExprError = timeExprError; exports.describeRange = describeRange; exports.zoomRange = zoomRange; exports.ALL = ALL; exports.initialVariableValues = initialVariableValues; exports.variableOptions = variableOptions; exports.variableInfo = variableInfo; exports.visibleVariables = visibleVariables; exports.isSqlDatasource = isSqlDatasource; exports.framesToOptions = framesToOptions; exports.refineOptions = refineOptions; exports.selectValue = selectValue; exports.variableReferences = variableReferences; exports.interpolate = interpolate; exports.queryParam = queryParam; exports.interpolateDeep = interpolateDeep; exports.resolveTimezone = resolveTimezone; exports.valueText = valueText; exports.GRID_COLUMNS = GRID_COLUMNS; exports.gridUnitsToPx = gridUnitsToPx; exports.gridOffsetPx = gridOffsetPx; exports.compactGrid = compactGrid; exports.isRow = isRow; exports.layoutDashboard = layoutDashboard; exports.repeatOptions = repeatOptions; exports.panelKey = panelKey; exports.panelSpan = panelSpan; exports.applyTransformations = applyTransformations; exports.DASHBOARD_DS = DASHBOARD_DS; exports.dashboardSourceIds = dashboardSourceIds; exports.panelHasQueries = panelHasQueries; exports.queryPanel = queryPanel; exports.normalizeRef = normalizeRef; exports.refreshedVariables = refreshedVariables; exports.variableDependents = variableDependents; exports.variableOrder = variableOrder; exports.resolveVariables = resolveVariables; exports.REDUCER_LABELS = REDUCER_LABELS; exports.isReducer = isReducer; exports.reduce = reduce; exports.INPUT_OPTION_KEYS = INPUT_OPTION_KEYS; exports.INPUT_TYPES = INPUT_TYPES; exports.isInputType = isInputType; exports.isInputPanel = isInputPanel; exports.INPUT_GROUP = INPUT_GROUP; exports.isFormPanelType = isFormPanelType; exports.isInputGroup = isInputGroup; exports.GROUP_FIELD_TYPES = GROUP_FIELD_TYPES; exports.groupFields = groupFields; exports.inputPanels = inputPanels; exports.documentKind = documentKind; exports.inputGroups = inputGroups; exports.plainInputPanels = plainInputPanels; exports.parseClockDigits = parseClockDigits; exports.formatClock = formatClock; exports.toEntries = toEntries; exports.newSaveId = newSaveId; exports.isEmptyItem = isEmptyItem; exports.groupToEntries = groupToEntries; exports.entriesToItems = entriesToItems; exports.groupProblems = groupProblems; exports.sameSave = sameSave; exports.inputProblem = inputProblem; exports.entryToInputValue = entryToInputValue; exports.textSuggestions = textSuggestions; exports.entriesSavedWith = entriesSavedWith; exports.formatValue = formatValue; exports.thresholdStep = thresholdStep; exports.NAMED_COLORS = NAMED_COLORS; exports.resolveColor = resolveColor; exports.SERIES_PALETTE = SERIES_PALETTE; exports.seriesColor = seriesColor; exports.mappedResult = mappedResult; exports.formatDisplay = formatDisplay; exports.valueColor = valueColor; exports.resolveFieldConfig = resolveFieldConfig; exports.fieldMatches = fieldMatches; exports.GrafanaError = GrafanaError; exports.GrafanaClient = GrafanaClient; exports.GrafanaDataSource = GrafanaDataSource; exports.fromWire = fromWire; exports.LOCAL_DATASOURCE_TYPE = LOCAL_DATASOURCE_TYPE; exports.isLocalDatasource = isLocalDatasource; exports.LocalDataSource = LocalDataSource; exports.groupField = groupField; exports.buildFrames = buildFrames; exports.MemoryEntryStore = MemoryEntryStore; exports.DEFAULT_GAZETTEER = DEFAULT_GAZETTEER; exports.parseGazetteer = parseGazetteer; exports.loadGazetteer = loadGazetteer; exports.resolveLinks = resolveLinks; exports.parseDashboardLink = parseDashboardLink; exports.applyDashboardLink = applyDashboardLink; exports.appSchema = appSchema; exports.dashboardSchema = dashboardSchema; exports.pointerToPath = pointerToPath; exports.manifestSchemaIssues = manifestSchemaIssues; exports.dashboardSchemaIssues = dashboardSchemaIssues; exports.cleanDashboard = cleanDashboard; exports.MAPPING_TYPES = MAPPING_TYPES; exports.SPECIAL_MATCHES = SPECIAL_MATCHES; exports.mappingRows = mappingRows; exports.rowsToMappings = rowsToMappings; exports.mappingRow = mappingRow; exports.mappingProblem = mappingProblem; exports.OPTION_CATEGORIES = OPTION_CATEGORIES; exports.UNIT_CHOICES = UNIT_CHOICES; exports.panelOptions = panelOptions; exports.getPath = getPath; exports.optionValue = optionValue; exports.setOption = setOption; exports.setOptionValue = setOptionValue; exports.cleanPanelOptions = cleanPanelOptions; exports.OVERRIDE_MATCHERS = OVERRIDE_MATCHERS; exports.overrideProperties = overrideProperties; exports.panelOverrides = panelOverrides; exports.setOverrides = setOverrides; exports.MANIFEST_VERSION = MANIFEST_VERSION; exports.validateManifest = validateManifest; exports.prepareDashboard = prepareDashboard; exports.validateDashboard = validateDashboard2; exports.validateBundle = validateBundle; exports.resolveUrl = resolveUrl; exports.httpFetchJson = httpFetchJson; exports.defaultFetchJson = defaultFetchJson; exports.BUNDLE_TYPE = BUNDLE_TYPE; exports.BUNDLE_ACCEPT = BUNDLE_ACCEPT; exports.isBundleResponse = isBundleResponse; exports.bundleRoot = bundleRoot; exports.assembleFromResponse = assembleFromResponse; exports.assembleBundle = assembleBundle; exports.fetchBundle = fetchBundle; exports.revalidateBundle = revalidateBundle; exports.ConfigLoader = ConfigLoader; exports.tabIdFor = tabIdFor; exports.screenOfType = screenOfType; exports.screenDocuments = screenDocuments; exports.documentUses = documentUses; exports.stringifyCompact = stringifyCompact; exports.applyJsonEdits = applyJsonEdits; exports.diffJson = diffJson; exports.documentIdFor = documentIdFor; exports.removeDocumentFromManifest = removeDocumentFromManifest; exports.renameDocumentInManifest = renameDocumentInManifest; exports.metricChanges = metricChanges; exports.REFRESH_CHOICES = REFRESH_CHOICES; exports.EDITABLE_VARIABLE_TYPES = EDITABLE_VARIABLE_TYPES; exports.isEditableVariableType = isEditableVariableType; exports.variableNameError = variableNameError; exports.newVariable = newVariable; exports.variableWithType = variableWithType; exports.variableWithQuery = variableWithQuery; exports.variableWithCurrent = variableWithCurrent; exports.variableWithFlags = variableWithFlags; exports.variableUses = variableUses; exports.renameVariableInPanels = renameVariableInPanels; exports.lineColumn = lineColumn; exports.parseJsonText = parseJsonText; exports.splitPath = splitPath; exports.locate = locate; exports.checkFiles = checkFiles; exports.bundleFromFiles = bundleFromFiles; exports.formatJsonText = formatJsonText; exports.setJsonValue = setJsonValue; exports.PANEL_TYPES = PANEL_TYPES; exports.newPanel = newPanel; exports.newDocument = newDocument; exports.SaveConflictError = SaveConflictError; exports.HttpConfigFiles = HttpConfigFiles; exports.fetchJsonWithToken = fetchJsonWithToken; exports.readConfigFiles = readConfigFiles; exports.readingOrder = readingOrder; exports.repack = repack; exports.CANVAS_GAP = CANVAS_GAP; exports.CANVAS_ROW_HEADER = CANVAS_ROW_HEADER; exports.panelSize = panelSize; exports.layoutCanvas = layoutCanvas; exports.dropTarget = dropTarget; exports.movePanel = movePanel; exports.resizePanel = resizePanel; exports.setHiddenOnPhones = setHiddenOnPhones; exports.nextPanelId = nextPanelId; exports.insertPanel = insertPanel; exports.duplicatePanel = duplicatePanel; exports.removePanel = removePanel; exports.expandRow = expandRow; exports.collapseRow = collapseRow; exports.settleLayout = settleLayout; exports.placePanel = placePanel; exports.snapToGrid = snapToGrid; exports.panelEdits = panelEdits; exports.sampleEntries = sampleEntries; exports.SNIPPET_VERSION = SNIPPET_VERSION; exports.panelMetrics = panelMetrics; exports.renameMetrics = renameMetrics; exports.copyPanels = copyPanels; exports.parseSnippet = parseSnippet; exports.previewPaste = previewPaste; exports.pasteSnippet = pasteSnippet; exports.TEMPLATE_VERSION = TEMPLATE_VERSION; exports.makeTemplate = makeTemplate; exports.parseTemplate = parseTemplate; exports.templateNeeds = templateNeeds; exports.applyTemplate = applyTemplate; exports.AUTHORING_GUIDE = AUTHORING_GUIDE; exports.EXAMPLE_TEMPLATE = EXAMPLE_TEMPLATE; exports.templatePrompt = templatePrompt; exports.jsonFromAnswer = jsonFromAnswer; exports.readTemplateAnswer = readTemplateAnswer; exports.fixTemplatePrompt = fixTemplatePrompt;
@@ -11567,6 +11567,229 @@ function applyTemplate(manifestText, paths, template, options = {}) {
11567
11567
  return { manifest: applyJsonEdits(manifestText, edits), files: out, ids, tabs: added };
11568
11568
  }
11569
11569
 
11570
+ // src/core/authoring.ts
11571
+ var AUTHORING_GUIDE = `# modelform templates
11572
+
11573
+ A template is JSON that adds forms (for recording entries) and dashboards (for charting them) to an app, plus tabs to show them.
11574
+
11575
+ \`\`\`
11576
+ {
11577
+ "$modelform": "template",
11578
+ "version": 1,
11579
+ "title": "Short name",
11580
+ "description": "One sentence on what it's for.",
11581
+ "documents": [ { "kind": "form" | "dashboard", "id": "letters-digits-dashes", "dashboard": { ...document } } ],
11582
+ "tabs": [ ...tabs ]
11583
+ }
11584
+ \`\`\`
11585
+
11586
+ ## Documents
11587
+
11588
+ A document is a subset of Grafana's dashboard JSON: \`{ "kind": "form" | "dashboard", "title": "\u2026", "panels": [ \u2026 ] }\`, and dashboards add \`"time": { "from": "now-30d", "to": "now" }\`. Its \`kind\` matches its entry in \`documents\`.
11589
+
11590
+ Every panel has an \`id\` (a number, unique in its document), a \`type\`, a \`title\`, and a \`gridPos\` \`{ "x", "y", "w", "h" }\` on a 24-column grid: \`w: 24\` is full width, \`w: 12\` half. Stack panels top to bottom with no gaps or overlaps (each \`y\` is the previous \`y + h\` unless they sit side by side). On phones panels show full width in that order.
11591
+
11592
+ A \`"row"\` panel (\`h: 1\`, no options) is a section heading for the panels under it, in forms and dashboards.
11593
+
11594
+ ## Forms
11595
+
11596
+ Forms hold input panels. Each records to a \`metric\` (lowercase words joined with dashes, e.g. \`"body-weight"\`), and charts read entries by that metric. Two inputs never share a metric. Use \`h: 3\` for inputs.
11597
+
11598
+ | type | what | options besides metric |
11599
+ |---|---|---|
11600
+ | input-number | a number typed or stepped with + and \u2212 | unit, step, min, max |
11601
+ | input-slider | a value dragged along a range | min, max, step, unit, labels (text spread along the track) |
11602
+ | input-select | one of a set of choices | choices: [{ "label", "value" }], multi (allow several) |
11603
+ | input-toggle | yes or no (records 1 or 0) | |
11604
+ | input-rating | a score, e.g. 1 to 5 | min, max |
11605
+ | input-text | free text | placeholder, suggest (offer earlier values) |
11606
+ | input-counter | taps that add up, e.g. glasses of water | increment, unit |
11607
+ | input-duration | a length of time, recorded in seconds | placeholder |
11608
+
11609
+ Any input (not counter) can also take \`required: true\`, \`default\` (a value, or \`"last"\` for the last one saved), and \`record: "always"\` to record its value on every save even when it wasn't changed.
11610
+
11611
+ \`input-group\` repeats fields once per item, for things like the sets of a workout or the dishes of a meal. Give it \`h: 12\` and options \`{ "itemTitle": "Set", "titleFrom": "<a field's metric>", "start": 1 | "last", "min", "max", "fields": [ { "type": "input-\u2026", "title", "span": 1\u201324, "options": { "metric", \u2026 } } ] }\`. Fields can be any input but input-counter.
11612
+
11613
+ ## Dashboards
11614
+
11615
+ Chart panels read the app's entries with \`"datasource": { "type": "modelform-local" }\` and \`"targets": [ { "refId": "A", "metric": "\u2026" } ]\` (refIds A, B, C\u2026 for more series). A target can also have:
11616
+
11617
+ - \`aggregate\`: "sum", "avg", "min", "max", "count" or "last", with \`bucket\`: "1h", "1d", "1w" or "1M". Without them each entry is a point.
11618
+ - \`groupBy\`: "text" for one series per text or choice value; \`{ "field": "<metric>" }\` for one series per value of another input saved at the same time (in an input-group, of the same item, e.g. weight per exercise).
11619
+ - \`alias\`: the series name. \`fillZero: false\` leaves empty buckets out.
11620
+
11621
+ | type | use for | h |
11622
+ |---|---|---|
11623
+ | timeseries | values over time | 7\u20138 |
11624
+ | barchart | totals per day, week or category | 7\u20138 |
11625
+ | stat | one big number; \`"options": { "reduceOptions": { "calcs": ["lastNotNull" or "mean" or "sum"] } }\` | 4 |
11626
+ | gauge, bargauge | a value against a range (set min and max) | 5\u20136 |
11627
+ | piechart | how a total splits, e.g. by choice with groupBy "text" and aggregate "count" | 8 |
11628
+ | table | rows of values | 8 |
11629
+ | text | markdown notes: \`"options": { "content": "\u2026" }\`, no targets | 3\u20134 |
11630
+
11631
+ Units and ranges go in \`"fieldConfig": { "defaults": { "unit": "\u2026", "min", "max", "decimals" } }\`. Units are Grafana's, e.g. "percent", "masskg", "lengthkm", "s", or "suffix: <text>" for anything else (\`"suffix: glasses"\`). Don't use trend, xychart or geomap panels.
11632
+
11633
+ Charts can't do arithmetic across metrics (weight \xD7 reps, a ratio of two inputs). Chart what's recorded instead, or add an input for the combined value, and say which you did in the sentence before the JSON.
11634
+
11635
+ ## Tabs
11636
+
11637
+ \`{ "id": "\u2026", "title": "\u2026", "icon": "\u2026", "screen": \u2026 }\`, where the screen is one of:
11638
+
11639
+ - \`{ "type": "forms", "forms": ["<form id>", \u2026] }\`
11640
+ - \`{ "type": "dashboard", "dashboard": "<dashboard id>" }\`
11641
+ - \`{ "type": "menu", "items": [ { "form": "<id>" } or { "dashboard": "<id>", "description": "\u2026" } ] }\`
11642
+
11643
+ Usually one tab for the forms and one per dashboard.
11644
+ `;
11645
+ var EXAMPLE = {
11646
+ $modelform: "template",
11647
+ version: 1,
11648
+ title: "Water and sleep",
11649
+ description: "Count glasses of water and log sleep, and see both by day.",
11650
+ documents: [
11651
+ {
11652
+ kind: "form",
11653
+ id: "today",
11654
+ dashboard: {
11655
+ kind: "form",
11656
+ title: "Today",
11657
+ panels: [
11658
+ { id: 1, type: "input-counter", title: "Water", gridPos: { x: 0, y: 0, w: 24, h: 3 }, options: { metric: "water", unit: "glasses" } },
11659
+ { id: 2, type: "input-duration", title: "Sleep", gridPos: { x: 0, y: 3, w: 12, h: 3 }, options: { metric: "sleep" } },
11660
+ { id: 3, type: "input-rating", title: "Sleep quality", gridPos: { x: 12, y: 3, w: 12, h: 3 }, options: { metric: "sleep-quality", min: 1, max: 5 } }
11661
+ ]
11662
+ }
11663
+ },
11664
+ {
11665
+ kind: "dashboard",
11666
+ id: "by-day",
11667
+ dashboard: {
11668
+ kind: "dashboard",
11669
+ title: "By day",
11670
+ time: { from: "now-30d", to: "now" },
11671
+ panels: [
11672
+ {
11673
+ id: 1,
11674
+ type: "stat",
11675
+ title: "Average sleep",
11676
+ gridPos: { x: 0, y: 0, w: 12, h: 4 },
11677
+ datasource: { type: "modelform-local" },
11678
+ targets: [{ refId: "A", metric: "sleep" }],
11679
+ fieldConfig: { defaults: { unit: "s" } },
11680
+ options: { reduceOptions: { calcs: ["mean"] } }
11681
+ },
11682
+ {
11683
+ id: 2,
11684
+ type: "stat",
11685
+ title: "Water today",
11686
+ gridPos: { x: 12, y: 0, w: 12, h: 4 },
11687
+ datasource: { type: "modelform-local" },
11688
+ targets: [{ refId: "A", metric: "water", aggregate: "sum", bucket: "1d" }],
11689
+ fieldConfig: { defaults: { unit: "suffix: glasses", decimals: 0 } },
11690
+ options: { reduceOptions: { calcs: ["lastNotNull"] } }
11691
+ },
11692
+ {
11693
+ id: 3,
11694
+ type: "barchart",
11695
+ title: "Water per day",
11696
+ gridPos: { x: 0, y: 4, w: 24, h: 7 },
11697
+ datasource: { type: "modelform-local" },
11698
+ targets: [{ refId: "A", metric: "water", alias: "Glasses", aggregate: "sum", bucket: "1d" }],
11699
+ fieldConfig: { defaults: { min: 0, decimals: 0 } }
11700
+ },
11701
+ {
11702
+ id: 4,
11703
+ type: "timeseries",
11704
+ title: "Sleep quality",
11705
+ gridPos: { x: 0, y: 11, w: 24, h: 7 },
11706
+ datasource: { type: "modelform-local" },
11707
+ targets: [{ refId: "A", metric: "sleep-quality", alias: "Quality", aggregate: "avg", bucket: "1d", fillZero: false }],
11708
+ fieldConfig: { defaults: { min: 1, max: 5 } }
11709
+ }
11710
+ ]
11711
+ }
11712
+ }
11713
+ ],
11714
+ tabs: [
11715
+ { id: "today", title: "Today", icon: "edit", screen: { type: "forms", forms: ["today"] } },
11716
+ { id: "by-day", title: "By day", icon: "chart", screen: { type: "dashboard", dashboard: "by-day" } }
11717
+ ],
11718
+ metrics: ["water", "sleep", "sleep-quality"]
11719
+ };
11720
+ var EXAMPLE_TEMPLATE = EXAMPLE;
11721
+ function templatePrompt(request, { recorded = [], icons = [] } = {}) {
11722
+ const context = [
11723
+ recorded.length ? `The app already records these metrics: ${recorded.map((m) => `\`${m}\``).join(", ")}. Charts can read them. A new form should only record one of them if it's for the same thing; otherwise pick new names.` : "The app doesn\u2019t record anything yet.",
11724
+ icons.length ? `Tab icons can be: ${icons.map((i) => `\`${i}\``).join(", ")}.` : ""
11725
+ ].filter(Boolean);
11726
+ return [
11727
+ "I\u2019m building an app with modelform studio. Make me a modelform template for this:",
11728
+ "",
11729
+ request.trim().replace(/^/gm, "> "),
11730
+ "",
11731
+ ...context,
11732
+ "",
11733
+ "Reply with the template as one ```json code block. A sentence before it is fine; nothing after it.",
11734
+ "",
11735
+ AUTHORING_GUIDE,
11736
+ "## Example",
11737
+ "",
11738
+ "```json",
11739
+ JSON.stringify(EXAMPLE),
11740
+ "```"
11741
+ ].join("\n");
11742
+ }
11743
+ function jsonFromAnswer(text) {
11744
+ const blocks = [...text.matchAll(/```(?:json|JSON)?[ \t]*\r?\n([\s\S]*?)```/g)].map((m) => m[1]);
11745
+ const start = text.indexOf("{");
11746
+ const end = text.lastIndexOf("}");
11747
+ if (start >= 0 && end > start) blocks.push(text.slice(start, end + 1));
11748
+ for (const block of blocks.reverse()) {
11749
+ try {
11750
+ return JSON.parse(block);
11751
+ } catch {
11752
+ }
11753
+ }
11754
+ throw new Error("There\u2019s no JSON in that answer");
11755
+ }
11756
+ function readTemplateAnswer(text) {
11757
+ let json;
11758
+ try {
11759
+ json = jsonFromAnswer(text);
11760
+ } catch (e) {
11761
+ return { error: e.message };
11762
+ }
11763
+ const parsed = parseTemplate(JSON.stringify(json));
11764
+ if ("error" in parsed) return parsed;
11765
+ const { template } = parsed;
11766
+ const raw = json;
11767
+ const warnings = raw.documents.flatMap(
11768
+ (d) => prepareDashboard(d.dashboard, d.id).issues.filter((i) => i.severity === "warning").map((i) => `${i.path}: ${i.message}`)
11769
+ );
11770
+ const kept = new Set(template.tabs.map((t) => t.id));
11771
+ for (const [i, tab] of (Array.isArray(raw.tabs) ? raw.tabs : []).entries()) {
11772
+ const id = tab?.id;
11773
+ if (typeof id !== "string" || !kept.has(id)) warnings.push(`tabs[${i}] was left out: it needs an id, a title and a screen showing only this template\u2019s documents`);
11774
+ }
11775
+ const kinds = new Map(template.documents.map((d) => [d.id, d.kind]));
11776
+ for (const tab of template.tabs)
11777
+ for (const ref of screenDocuments(tab.screen)) {
11778
+ const kind = kinds.get(ref.id);
11779
+ if (kind && kind !== ref.kind) warnings.push(`tab "${tab.id}" shows "${ref.id}" as a ${ref.kind}, but it\u2019s a ${kind}`);
11780
+ }
11781
+ return { template, warnings };
11782
+ }
11783
+ function fixTemplatePrompt(problems) {
11784
+ return [
11785
+ "modelform couldn\u2019t use that template as it was:",
11786
+ "",
11787
+ ...problems.map((p) => `- ${p}`),
11788
+ "",
11789
+ "Fix these and reply with the whole corrected template as one ```json code block."
11790
+ ].join("\n");
11791
+ }
11792
+
11570
11793
  export {
11571
11794
  frameLength,
11572
11795
  timeField,
@@ -11790,5 +12013,11 @@ export {
11790
12013
  makeTemplate,
11791
12014
  parseTemplate,
11792
12015
  templateNeeds,
11793
- applyTemplate
12016
+ applyTemplate,
12017
+ AUTHORING_GUIDE,
12018
+ EXAMPLE_TEMPLATE,
12019
+ templatePrompt,
12020
+ jsonFromAnswer,
12021
+ readTemplateAnswer,
12022
+ fixTemplatePrompt
11794
12023
  };
@@ -0,0 +1,30 @@
1
+ import { type AppTemplate } from './templates';
2
+ /** How to write a modelform template, for an assistant. Kept next to the format so they change together. */
3
+ export declare const AUTHORING_GUIDE = "# modelform templates\n\nA template is JSON that adds forms (for recording entries) and dashboards (for charting them) to an app, plus tabs to show them.\n\n```\n{\n \"$modelform\": \"template\",\n \"version\": 1,\n \"title\": \"Short name\",\n \"description\": \"One sentence on what it's for.\",\n \"documents\": [ { \"kind\": \"form\" | \"dashboard\", \"id\": \"letters-digits-dashes\", \"dashboard\": { ...document } } ],\n \"tabs\": [ ...tabs ]\n}\n```\n\n## Documents\n\nA document is a subset of Grafana's dashboard JSON: `{ \"kind\": \"form\" | \"dashboard\", \"title\": \"\u2026\", \"panels\": [ \u2026 ] }`, and dashboards add `\"time\": { \"from\": \"now-30d\", \"to\": \"now\" }`. Its `kind` matches its entry in `documents`.\n\nEvery panel has an `id` (a number, unique in its document), a `type`, a `title`, and a `gridPos` `{ \"x\", \"y\", \"w\", \"h\" }` on a 24-column grid: `w: 24` is full width, `w: 12` half. Stack panels top to bottom with no gaps or overlaps (each `y` is the previous `y + h` unless they sit side by side). On phones panels show full width in that order.\n\nA `\"row\"` panel (`h: 1`, no options) is a section heading for the panels under it, in forms and dashboards.\n\n## Forms\n\nForms hold input panels. Each records to a `metric` (lowercase words joined with dashes, e.g. `\"body-weight\"`), and charts read entries by that metric. Two inputs never share a metric. Use `h: 3` for inputs.\n\n| type | what | options besides metric |\n|---|---|---|\n| input-number | a number typed or stepped with + and \u2212 | unit, step, min, max |\n| input-slider | a value dragged along a range | min, max, step, unit, labels (text spread along the track) |\n| input-select | one of a set of choices | choices: [{ \"label\", \"value\" }], multi (allow several) |\n| input-toggle | yes or no (records 1 or 0) | |\n| input-rating | a score, e.g. 1 to 5 | min, max |\n| input-text | free text | placeholder, suggest (offer earlier values) |\n| input-counter | taps that add up, e.g. glasses of water | increment, unit |\n| input-duration | a length of time, recorded in seconds | placeholder |\n\nAny input (not counter) can also take `required: true`, `default` (a value, or `\"last\"` for the last one saved), and `record: \"always\"` to record its value on every save even when it wasn't changed.\n\n`input-group` repeats fields once per item, for things like the sets of a workout or the dishes of a meal. Give it `h: 12` and options `{ \"itemTitle\": \"Set\", \"titleFrom\": \"<a field's metric>\", \"start\": 1 | \"last\", \"min\", \"max\", \"fields\": [ { \"type\": \"input-\u2026\", \"title\", \"span\": 1\u201324, \"options\": { \"metric\", \u2026 } } ] }`. Fields can be any input but input-counter.\n\n## Dashboards\n\nChart panels read the app's entries with `\"datasource\": { \"type\": \"modelform-local\" }` and `\"targets\": [ { \"refId\": \"A\", \"metric\": \"\u2026\" } ]` (refIds A, B, C\u2026 for more series). A target can also have:\n\n- `aggregate`: \"sum\", \"avg\", \"min\", \"max\", \"count\" or \"last\", with `bucket`: \"1h\", \"1d\", \"1w\" or \"1M\". Without them each entry is a point.\n- `groupBy`: \"text\" for one series per text or choice value; `{ \"field\": \"<metric>\" }` for one series per value of another input saved at the same time (in an input-group, of the same item, e.g. weight per exercise).\n- `alias`: the series name. `fillZero: false` leaves empty buckets out.\n\n| type | use for | h |\n|---|---|---|\n| timeseries | values over time | 7\u20138 |\n| barchart | totals per day, week or category | 7\u20138 |\n| stat | one big number; `\"options\": { \"reduceOptions\": { \"calcs\": [\"lastNotNull\" or \"mean\" or \"sum\"] } }` | 4 |\n| gauge, bargauge | a value against a range (set min and max) | 5\u20136 |\n| piechart | how a total splits, e.g. by choice with groupBy \"text\" and aggregate \"count\" | 8 |\n| table | rows of values | 8 |\n| text | markdown notes: `\"options\": { \"content\": \"\u2026\" }`, no targets | 3\u20134 |\n\nUnits and ranges go in `\"fieldConfig\": { \"defaults\": { \"unit\": \"\u2026\", \"min\", \"max\", \"decimals\" } }`. Units are Grafana's, e.g. \"percent\", \"masskg\", \"lengthkm\", \"s\", or \"suffix: <text>\" for anything else (`\"suffix: glasses\"`). Don't use trend, xychart or geomap panels.\n\nCharts can't do arithmetic across metrics (weight \u00D7 reps, a ratio of two inputs). Chart what's recorded instead, or add an input for the combined value, and say which you did in the sentence before the JSON.\n\n## Tabs\n\n`{ \"id\": \"\u2026\", \"title\": \"\u2026\", \"icon\": \"\u2026\", \"screen\": \u2026 }`, where the screen is one of:\n\n- `{ \"type\": \"forms\", \"forms\": [\"<form id>\", \u2026] }`\n- `{ \"type\": \"dashboard\", \"dashboard\": \"<dashboard id>\" }`\n- `{ \"type\": \"menu\", \"items\": [ { \"form\": \"<id>\" } or { \"dashboard\": \"<id>\", \"description\": \"\u2026\" } ] }`\n\nUsually one tab for the forms and one per dashboard.\n";
4
+ /** The example the guide ends with, for tests and editors. */
5
+ export declare const EXAMPLE_TEMPLATE: AppTemplate;
6
+ export interface PromptContext {
7
+ /** Metrics the app already records, so new charts can read them and new forms don't clash with them. */
8
+ recorded?: string[];
9
+ /** Icon names tabs can use. */
10
+ icons?: string[];
11
+ }
12
+ /**
13
+ * A prompt asking an assistant for a template that does what `request` describes, with the
14
+ * guide, an example, and what the app already has.
15
+ */
16
+ export declare function templatePrompt(request: string, { recorded, icons }?: PromptContext): string;
17
+ /** The JSON in an assistant's reply: its last ```json block that parses, else the outermost braces. */
18
+ export declare function jsonFromAnswer(text: string): unknown;
19
+ /**
20
+ * Reads a template out of an assistant's reply. Warnings are things that were dropped or look
21
+ * wrong but don't stop it being used, worth sending back with fixTemplatePrompt.
22
+ */
23
+ export declare function readTemplateAnswer(text: string): {
24
+ template: AppTemplate;
25
+ warnings: string[];
26
+ } | {
27
+ error: string;
28
+ };
29
+ /** A follow-up asking the assistant to fix what was wrong with its template. */
30
+ export declare function fixTemplatePrompt(problems: string[]): string;
@@ -27,3 +27,4 @@ export * from './panelOptions';
27
27
  export * from './sample';
28
28
  export * from './snippets';
29
29
  export * from './templates';
30
+ export * from './authoring';