@malloy-publisher/sdk 0.4.0 → 0.5.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.
Files changed (72) hide show
  1. package/README.md +19 -0
  2. package/dist/{DocumentStorageProvider-CyOJ0hqf.es.js → DocumentStorage-B04sZ5Ie.es.js} +2307 -2334
  3. package/dist/{DocumentStorageProvider-DGPQEd_l.cjs.js → DocumentStorage-B_MMJ0Ot.cjs.js} +20 -20
  4. package/dist/{RenderedResult-BnPzJ9Jf.es.js → RenderedResult-BB7eokcf.es.js} +100 -80
  5. package/dist/RenderedResult-DVuGhatg.cjs.js +135 -0
  6. package/dist/ServerProvider-D-jjzfE5.cjs.js +1 -0
  7. package/dist/{ServerProvider-BWOEKg0O.es.js → ServerProvider-Do-GBvpn.es.js} +492 -481
  8. package/dist/builder/index.cjs.js +57 -52
  9. package/dist/builder/index.es.js +4421 -3738
  10. package/dist/client/api.d.ts +14 -1
  11. package/dist/client/index.cjs.js +1 -1
  12. package/dist/client/index.es.js +1 -1
  13. package/dist/components/Dashboard/TileCard.d.ts +7 -3
  14. package/dist/components/Dashboard/telemetry.d.ts +20 -8
  15. package/dist/components/DashboardBuilder/DashboardBuilder.d.ts +16 -4
  16. package/dist/components/DashboardBuilder/DashboardEditor.d.ts +31 -8
  17. package/dist/components/DashboardBuilder/controls.d.ts +8 -6
  18. package/dist/components/DashboardBuilder/document.d.ts +19 -5
  19. package/dist/components/DashboardBuilder/malloyText.d.ts +0 -30
  20. package/dist/components/DashboardBuilder/malloyTree.d.ts +232 -0
  21. package/dist/components/DashboardBuilder/preview.d.ts +17 -0
  22. package/dist/components/DashboardBuilder/readDocument.d.ts +23 -28
  23. package/dist/components/DashboardBuilder/spliceDocument.d.ts +12 -0
  24. package/dist/components/DocumentStorage/DocumentStorage.d.ts +69 -5
  25. package/dist/components/DocumentStorage/index.d.ts +1 -0
  26. package/dist/index.cjs.js +9 -9
  27. package/dist/index.es.js +508 -506
  28. package/dist/theme/resolveTheme.d.ts +1 -1
  29. package/dist/theme/types.d.ts +12 -2
  30. package/package.json +1 -1
  31. package/src/components/Dashboard/TileCard.tsx +8 -4
  32. package/src/components/Dashboard/telemetry.ts +20 -8
  33. package/src/components/DashboardBuilder/BuilderToolbar.tsx +4 -5
  34. package/src/components/DashboardBuilder/DashboardBuilder.tsx +21 -3
  35. package/src/components/DashboardBuilder/DashboardEditor.authoritative.spec.tsx +706 -0
  36. package/src/components/DashboardBuilder/DashboardEditor.resourceUri.spec.tsx +356 -0
  37. package/src/components/DashboardBuilder/DashboardEditor.tsx +468 -103
  38. package/src/components/DashboardBuilder/FilterDialog.tsx +19 -6
  39. package/src/components/DashboardBuilder/TileFrame.tsx +11 -2
  40. package/src/components/DashboardBuilder/TileMenu.tsx +6 -0
  41. package/src/components/DashboardBuilder/__test__/inventory.ts +367 -0
  42. package/src/components/DashboardBuilder/controls.spec.ts +53 -3
  43. package/src/components/DashboardBuilder/controls.ts +9 -7
  44. package/src/components/DashboardBuilder/document.ts +17 -5
  45. package/src/components/DashboardBuilder/invariants.spec.ts +297 -0
  46. package/src/components/DashboardBuilder/malloyText.spec.ts +27 -66
  47. package/src/components/DashboardBuilder/malloyText.ts +4 -109
  48. package/src/components/DashboardBuilder/malloyTree.spec.ts +362 -0
  49. package/src/components/DashboardBuilder/malloyTree.ts +954 -0
  50. package/src/components/DashboardBuilder/preview.spec.ts +18 -0
  51. package/src/components/DashboardBuilder/preview.ts +24 -6
  52. package/src/components/DashboardBuilder/readDocument.spec.ts +312 -21
  53. package/src/components/DashboardBuilder/readDocument.ts +144 -165
  54. package/src/components/DashboardBuilder/scannerShapes.spec.ts +550 -0
  55. package/src/components/DashboardBuilder/spliceDocument.spec.ts +955 -21
  56. package/src/components/DashboardBuilder/spliceDocument.ts +509 -119
  57. package/src/components/DashboardBuilder/statementExtent.spec.ts +606 -0
  58. package/src/components/DocumentStorage/BrowserDocumentStorage.ts +7 -6
  59. package/src/components/DocumentStorage/DocumentStorage.ts +78 -5
  60. package/src/components/DocumentStorage/index.ts +1 -0
  61. package/src/components/Package/Package.tsx +12 -7
  62. package/src/components/RenderedResult/RenderedResult.tsx +21 -1
  63. package/src/components/given/GivensPanel.tsx +15 -3
  64. package/src/theme/buildTableCssVars.spec.ts +3 -0
  65. package/src/theme/buildTableCssVars.ts +6 -0
  66. package/src/theme/defaults.ts +16 -12
  67. package/src/theme/resolveTheme.spec.ts +14 -7
  68. package/src/theme/resolveTheme.ts +14 -8
  69. package/src/theme/types.ts +12 -2
  70. package/tsconfig.spec.json +5 -1
  71. package/dist/RenderedResult-Dp22kZsQ.cjs.js +0 -115
  72. package/dist/ServerProvider-Cc489A3f.cjs.js +0 -1
@@ -5,10 +5,14 @@ import { describe, expect, it } from "bun:test";
5
5
  import * as fs from "fs";
6
6
  import * as path from "path";
7
7
  import type { DashboardDocument } from "./document";
8
- import { givenDeclarations } from "./malloyText";
9
- import { blockAbove, readDashboardDocument, readFailed } from "./readDocument";
10
- import { spliceDashboardDocument, spliceFailed } from "./spliceDocument";
8
+ import { readDashboardDocument, readFailed } from "./readDocument";
9
+ import {
10
+ spliceDashboardDocument,
11
+ spliceFailed,
12
+ syntaxErrors,
13
+ } from "./spliceDocument";
11
14
  import { openDocument, refused, splice, spliced } from "./testing/fixtures";
15
+ import { whatMoved } from "./__test__/inventory";
12
16
 
13
17
  const REPO = path.resolve(import.meta.dir, "../../../../..");
14
18
 
@@ -84,6 +88,101 @@ describe("spliceDashboardDocument: what it preserves", () => {
84
88
  });
85
89
  });
86
90
 
91
+ /**
92
+ * Two edits that share a start offset: a tag line inserted above a declaration,
93
+ * and a rewrite of that declaration. Applied in the wrong order the insertion
94
+ * moves the text out from under the rewrite's end offset and the rewrite lands
95
+ * inside what was just inserted, so the save is refused with nothing to tell
96
+ * the person which of the two changes it could not make. In the browser this is
97
+ * what "add a filter" hit: the width change was the tile's FIRST modelled tag.
98
+ */
99
+ describe("spliceDashboardDocument: a new tag over a rewritten declaration", () => {
100
+ const UNTAGGED = `##! experimental.givens
101
+ ## artifact { title="Probe" tiles=["a -> by_cat"] }
102
+ import "../data_app.malloy"
103
+
104
+ source: a is scoped_orders extend {
105
+ view: by_cat is by_category
106
+ }`;
107
+
108
+ it("writes both when the tile had no tags at all", async () => {
109
+ const out = await spliced(UNTAGGED, (d) => {
110
+ d.tiles[0].colspan = 4;
111
+ d.tiles[0].filters = [{ field: "category", given: "CATEGORY" }];
112
+ });
113
+ expect(out).toContain(
114
+ " # colspan=4\n view: by_cat is by_category + { where: category ~ $CATEGORY }",
115
+ );
116
+ });
117
+ });
118
+
119
+ /**
120
+ * A trailing `// …` on the declaration line. The refinement goes at the END of
121
+ * that line, so appended blind it lands inside the comment. Driven in a browser
122
+ * against a real draft package, that is what made "add a filter" refuse on a
123
+ * tile the builder could plainly write: the file was rewritten, Malloy saw no
124
+ * binding, and the readback gate refused the save with no way to tell why.
125
+ *
126
+ * With a refinement already on the line it is worse than a refusal: the reader's
127
+ * greedy match finds the binding inside the comment, so the gate passes a file
128
+ * whose filter Malloy never applies.
129
+ */
130
+ describe("spliceDashboardDocument: a comment at the end of the declaration", () => {
131
+ const commented = (declaration: string) => `##! experimental.givens
132
+ ## artifact { title="Probe" tiles=["a -> by_cat"] }
133
+ import "../data_app.malloy"
134
+
135
+ source: a is scoped_orders extend {
136
+ ${declaration}
137
+ }`;
138
+
139
+ const bind = (d: DashboardDocument) => {
140
+ d.tiles[0].filters = [{ field: "category", given: "CATEGORY" }];
141
+ };
142
+
143
+ it("puts the binding before the comment, not inside it", async () => {
144
+ const out = await spliced(
145
+ commented(" view: by_cat is by_category // the lead tile"),
146
+ bind,
147
+ );
148
+ expect(out).toContain(
149
+ " view: by_cat is by_category + { where: category ~ $CATEGORY } // the lead tile",
150
+ );
151
+ });
152
+
153
+ it("keeps an existing refinement ahead of the binding", async () => {
154
+ const out = await spliced(
155
+ commented(" view: by_cat is by_category + { limit: 5 } // top five"),
156
+ bind,
157
+ );
158
+ expect(out).toContain(
159
+ " view: by_cat is by_category + { limit: 5 where: category ~ $CATEGORY } // top five",
160
+ );
161
+ });
162
+
163
+ it("takes the binding off without disturbing the comment", async () => {
164
+ const source = commented(
165
+ " view: by_cat is by_category + { where: category ~ $CATEGORY } // the lead tile",
166
+ );
167
+ const out = await spliced(source, (d) => {
168
+ delete d.tiles[0].filters;
169
+ d.tiles[0].colspan = 4;
170
+ });
171
+ expect(out).toContain(" view: by_cat is by_category // the lead tile");
172
+ });
173
+
174
+ // `//` inside a filter literal is text, not the start of a comment.
175
+ it("does not mistake a slash pair inside a literal for a comment", async () => {
176
+ const out = await spliced(
177
+ commented(" view: by_cat is by_category + { where: path ~ 'a//b' }"),
178
+ bind,
179
+ );
180
+ expect(out).toContain(
181
+ " view: by_cat is by_category + { where: path ~ 'a//b' where: category ~ $CATEGORY }",
182
+ );
183
+ });
184
+ });
185
+
87
186
  describe("spliceDashboardDocument: what it writes", () => {
88
187
  it("adds a tag that was not there", async () => {
89
188
  const out = await spliced(SOURCE, (d) => {
@@ -204,7 +303,7 @@ describe("spliceDashboardDocument: bindings", () => {
204
303
  it("keeps an unmodelled clause in the refinement", async () => {
205
304
  const source = SOURCE.replace(
206
305
  "view: by_cat is by_category",
207
- "view: by_cat is by_category + { limit: 5, where: category ~ $CATEGORY }",
306
+ "view: by_cat is by_category + { limit: 5 where: category ~ $CATEGORY }",
208
307
  );
209
308
  const out = await spliced(source, (d) => {
210
309
  d.tiles[0].filters = [
@@ -213,7 +312,7 @@ describe("spliceDashboardDocument: bindings", () => {
213
312
  ];
214
313
  });
215
314
  expect(out).toContain(
216
- "view: by_cat is by_category + { limit: 5, where: category ~ $CATEGORY, where: brand ~ $BRAND }",
315
+ "view: by_cat is by_category + { limit: 5 where: category ~ $CATEGORY, where: brand ~ $BRAND }",
217
316
  );
218
317
  // And clearing the bindings leaves the clause that was never ours.
219
318
  const cleared = await spliced(source, (d) => {
@@ -223,6 +322,467 @@ describe("spliceDashboardDocument: bindings", () => {
223
322
  });
224
323
  });
225
324
 
325
+ /**
326
+ * `canBind` used to exclude an inline tile outright, because a `+ { where: …
327
+ * }` refinement written onto a query body would not read back. It does, once
328
+ * the binding is written INSIDE the body as a depth-1 `where:` statement in
329
+ * its first stage instead of a refinement after it — which is how the
330
+ * bundled `tiled.malloy` fixture, and most real dashboards, actually write a
331
+ * tile. These are that writer path.
332
+ */
333
+ describe("spliceDashboardDocument: inline body bindings", () => {
334
+ const MULTILINE = `## artifact { title="T" tiles=["a -> kpis"] }
335
+ import "../m.malloy"
336
+
337
+ source: a is one extend {
338
+ view: kpis is {
339
+ group_by: category
340
+ aggregate: n is count()
341
+ }
342
+ }`;
343
+
344
+ it("adds a binding as a new depth-1 where: line before the closing brace", async () => {
345
+ const out = await spliced(MULTILINE, (d) => {
346
+ d.tiles[0].filters = [{ field: "category", given: "CATEGORY" }];
347
+ });
348
+ expect(out).toContain(
349
+ " view: kpis is {\n group_by: category\n aggregate: n is count()\n where: category ~ $CATEGORY\n }",
350
+ );
351
+ });
352
+
353
+ it("rewrites an existing binding line in place", async () => {
354
+ const source = MULTILINE.replace(
355
+ "view: kpis is {\n group_by: category",
356
+ "view: kpis is {\n where: category ~ $CATEGORY\n group_by: category",
357
+ );
358
+ const out = await spliced(source, (d) => {
359
+ d.tiles[0].filters = [{ field: "brand_name", given: "CATEGORY" }];
360
+ });
361
+ expect(out).toContain(
362
+ " view: kpis is {\n where: brand_name ~ $CATEGORY\n group_by: category",
363
+ );
364
+ // Still one line, not a rewrite-in-place plus a stray append.
365
+ expect(out.match(/where:/g)).toHaveLength(1);
366
+ });
367
+
368
+ it("drops a removed binding's line entirely, no blank line left behind", async () => {
369
+ const source = MULTILINE.replace(
370
+ "view: kpis is {\n group_by: category",
371
+ "view: kpis is {\n where: category ~ $CATEGORY\n group_by: category",
372
+ );
373
+ const out = await spliced(source, (d) => {
374
+ delete d.tiles[0].filters;
375
+ });
376
+ expect(out).toContain(MULTILINE);
377
+ expect(out).not.toContain("where:");
378
+ });
379
+
380
+ // A `nest:`'s own `where:` is depth 2, one level inside the nest's own
381
+ // brace, so it is never in the set of lines this scan owns — it survives a
382
+ // binding change to the OUTER tile exactly as written, and the new binding
383
+ // goes after the nest's closing brace, not inside it.
384
+ it("leaves a nest's own where: untouched and adds the new line after it", async () => {
385
+ const source = `## artifact { title="T" tiles=["a -> kpis"] }
386
+ import "../m.malloy"
387
+
388
+ source: a is one extend {
389
+ view: kpis is {
390
+ group_by: category
391
+ nest: by_mth is {
392
+ where: mth ~ $MONTH
393
+ aggregate: n is count()
394
+ }
395
+ }
396
+ }`;
397
+ const out = await spliced(source, (d) => {
398
+ d.tiles[0].filters = [{ field: "category", given: "CATEGORY" }];
399
+ });
400
+ expect(out).toContain("where: mth ~ $MONTH");
401
+ expect(out).toContain(
402
+ " nest: by_mth is {\n where: mth ~ $MONTH\n aggregate: n is count()\n }\n where: category ~ $CATEGORY\n }",
403
+ );
404
+ });
405
+
406
+ // The compound line is unmodelled Malloy — never in the set this writer
407
+ // owns — so it survives a binding change exactly as written, and the new
408
+ // binding is its own line, not folded into it.
409
+ it("keeps a compound predicate untouched and adds the new binding beside it", async () => {
410
+ const source = `## artifact { title="T" tiles=["a -> kpis"] }
411
+ import "../m.malloy"
412
+
413
+ source: a is one extend {
414
+ view: kpis is {
415
+ where: category ~ $CATEGORY and status = 'open'
416
+ aggregate: n is count()
417
+ }
418
+ }`;
419
+ const out = await spliced(source, (d) => {
420
+ d.tiles[0].filters = [{ field: "region", given: "REGION" }];
421
+ });
422
+ expect(out).toContain("where: category ~ $CATEGORY and status = 'open'");
423
+ expect(out).toContain(
424
+ " where: category ~ $CATEGORY and status = 'open'\n aggregate: n is count()\n where: region ~ $REGION\n }",
425
+ );
426
+ });
427
+
428
+ // The bug this fix exists for: `isBindingOnly` used to check only that the
429
+ // first clause starts at 0 and the last reaches the end, never the gap
430
+ // BETWEEN two clauses — so this whole line read as binding-only, and a
431
+ // splice that dropped one binding rewrote it down to just the surviving
432
+ // `where:`, deleting the tile's actual measure with nothing catching it
433
+ // (the reader only ever reported bindings, so the round-trip compared
434
+ // equal). Fixed, the line does not tile end to end and is never ours to
435
+ // touch, so a filter change leaves it exactly as written — the assertion
436
+ // is on the SURVIVING TEXT, not on the splice merely succeeding, because
437
+ // the un-fixed path also returns `ok: true`.
438
+ const TWO_BINDINGS_ONE_STATEMENT = `## artifact { title="T" tiles=["a -> kpis"] }
439
+ import "../m.malloy"
440
+
441
+ source: a is one extend {
442
+ view: kpis is {
443
+ where: a ~ $A, aggregate: n is count(), where: b ~ $B
444
+ }
445
+ }`;
446
+
447
+ // Leaving the line alone is necessary but not sufficient: $A and $B still
448
+ // filter from text the builder cannot rewrite, so writing a managed
449
+ // `where:` for either would filter on that control twice, and only one of
450
+ // the two could ever be unticked again. Refused, and named.
451
+ // Both `where:`s are ordinary statements to the parser, so each clause is
452
+ // removed or rewritten by its own SPAN and the measure between them is not
453
+ // in any of those spans. What used to need a refusal is now just an edit.
454
+ it("drops one binding and leaves the measure between them", async () => {
455
+ const out = await spliced(TWO_BINDINGS_ONE_STATEMENT, (d) => {
456
+ d.tiles[0].filters = [{ field: "a", given: "A" }];
457
+ });
458
+ expect(out).toContain(" where: a ~ $A, aggregate: n is count()");
459
+ expect(out).not.toContain("$B");
460
+ });
461
+
462
+ it("rewrites each binding in place, measure untouched", async () => {
463
+ const out = await spliced(TWO_BINDINGS_ONE_STATEMENT, (d) => {
464
+ d.tiles[0].filters = [
465
+ { field: "a2", given: "A" },
466
+ { field: "b", given: "B" },
467
+ ];
468
+ });
469
+ expect(out).toContain(
470
+ " where: a2 ~ $A, aggregate: n is count(), where: b ~ $B",
471
+ );
472
+ });
473
+
474
+ // And an edit that touches neither given leaves the line exactly as written.
475
+ it("leaves the unmanaged line alone on an unrelated change", async () => {
476
+ const out = await spliced(TWO_BINDINGS_ONE_STATEMENT, (d) => {
477
+ d.tiles[0].colspan = 4;
478
+ });
479
+ expect(out).toContain(
480
+ "where: a ~ $A, aggregate: n is count(), where: b ~ $B",
481
+ );
482
+ });
483
+
484
+ // Guards the gap check above against over-tightening: a one-liner's
485
+ // binding and query necessarily share a line, so `oneLinerFilters` reads
486
+ // every isolated clause in the braces rather than requiring the whole
487
+ // content to be binding-only, and must keep doing so.
488
+ it("still reads and keeps a one-line body's binding alongside its measure", async () => {
489
+ const oneLiner = `## artifact { title="T" tiles=["a -> kpis"] }
490
+ import "../m.malloy"
491
+
492
+ source: a is one extend {
493
+ view: kpis is { where: c ~ $C, aggregate: n is count() }
494
+ }`;
495
+ const before = await openDocument(oneLiner);
496
+ expect(before.tiles[0].filters).toEqual([{ field: "c", given: "C" }]);
497
+ const out = await spliced(oneLiner, (d) => {
498
+ d.tiles[0].filters = [{ field: "c", given: "C2" }];
499
+ });
500
+ expect(out).toContain(
501
+ "view: kpis is { aggregate: n is count() where: c ~ $C2 }",
502
+ );
503
+ });
504
+
505
+ it("writes a one-line body's binding inline, before the closing brace", async () => {
506
+ const oneLiner = `## artifact { title="T" tiles=["a -> kpis"] }
507
+ import "../m.malloy"
508
+
509
+ source: a is one extend {
510
+ view: kpis is { aggregate: n is count() }
511
+ }`;
512
+ const out = await spliced(oneLiner, (d) => {
513
+ d.tiles[0].filters = [{ field: "category", given: "CATEGORY" }];
514
+ });
515
+ expect(out).toContain(
516
+ "view: kpis is { aggregate: n is count() where: category ~ $CATEGORY }",
517
+ );
518
+ // And unbinding restores the file exactly as it was.
519
+ const restored = await spliced(out, (d) => {
520
+ delete d.tiles[0].filters;
521
+ });
522
+ expect(restored).toBe(oneLiner);
523
+ });
524
+
525
+ // The first stage of a `{ … } -> { … }` body IS the tile's own, so a filter
526
+ // goes there. Only a later stage is out of reach, and nothing is written
527
+ // into one.
528
+ it("writes a filter into the first stage of a multi-stage body", async () => {
529
+ const source = `## artifact { title="T" tiles=["a -> kpis"] }
530
+ import "../m.malloy"
531
+
532
+ source: a is one extend {
533
+ view: kpis is {
534
+ group_by: category
535
+ aggregate: n is count()
536
+ } -> {
537
+ where: n > 10
538
+ select: category, n
539
+ }
540
+ }`;
541
+ const out = await spliced(source, (d) => {
542
+ d.tiles[0].filters = [{ field: "category", given: "CATEGORY" }];
543
+ });
544
+ expect(out).toContain(
545
+ " aggregate: n is count()\n where: category ~ $CATEGORY\n } -> {",
546
+ );
547
+ expect(out).toContain(" where: n > 10");
548
+ });
549
+
550
+ it("refuses a filter change on a compound { … } + { … } body", async () => {
551
+ const source = `## artifact { title="T" tiles=["a -> kpis"] }
552
+ import "../m.malloy"
553
+
554
+ source: a is one extend {
555
+ view: kpis is { aggregate: n is count() } + { limit: 5 }
556
+ }`;
557
+ expect(
558
+ await refused(source, (d) => {
559
+ d.tiles[0].filters = [{ field: "category", given: "CATEGORY" }];
560
+ }),
561
+ ).toContain("compound refinement");
562
+ });
563
+
564
+ // The source-level `where:` sits outside every view's extent. Changing an
565
+ // unrelated tile's own binding must not touch it.
566
+ it("never touches a source-level where: while binding a tile", async () => {
567
+ const source = `## artifact { title="T" tiles=["a -> kpis", "a -> other"] }
568
+ import "../m.malloy"
569
+
570
+ source: a is one extend {
571
+ where: brand_name ~ $BRAND
572
+
573
+ view: kpis is { aggregate: n is count() }
574
+ view: other is { aggregate: m is count() }
575
+ }`;
576
+ const out = await spliced(source, (d) => {
577
+ d.tiles[0].filters = [{ field: "category", given: "CATEGORY" }];
578
+ });
579
+ expect(out).toContain(" where: brand_name ~ $BRAND\n");
580
+ expect(out).toContain(
581
+ "view: kpis is { aggregate: n is count() where: category ~ $CATEGORY }",
582
+ );
583
+ });
584
+
585
+ it("round-trips: bind, read back, unbind, read back to the original bytes", async () => {
586
+ const bound = await spliced(MULTILINE, (d) => {
587
+ d.tiles[0].filters = [{ field: "category", given: "CATEGORY" }];
588
+ });
589
+ const reopened = await openDocument(bound);
590
+ expect(reopened.tiles[0].filters).toEqual([
591
+ { field: "category", given: "CATEGORY" },
592
+ ]);
593
+ const unbound = await spliced(bound, (d) => {
594
+ delete d.tiles[0].filters;
595
+ });
596
+ expect(unbound).toBe(MULTILINE);
597
+ const reread = await openDocument(unbound);
598
+ expect(reread.tiles[0].filters).toBeUndefined();
599
+ });
600
+
601
+ // The end-to-end shape of the corruption a quoted literal's brace used to
602
+ // cause: with the brace counted as structure, `kpis`'s own extent ran
603
+ // through `other`, an unrelated sibling view, and the new binding landed
604
+ // after it, at source scope — outside the tile it was meant for. The
605
+ // round-trip gate could not catch this on its own, because the reader
606
+ // shared the same scan and read the stray clause back as `kpis`'s own, so
607
+ // this checks the WRITTEN TEXT's placement directly rather than trusting
608
+ // a read-back.
609
+ it("places a new binding inside its own tile, not after a sibling view holding a brace in a literal", async () => {
610
+ const source = `## artifact { title="T" tiles=["a -> kpis"] }
611
+ import "../m.malloy"
612
+
613
+ source: a is scoped_orders extend {
614
+ view: kpis is {
615
+ where: path ~ 'a{b'
616
+ aggregate: n is count()
617
+ }
618
+
619
+ view: other is { aggregate: m is count() }
620
+ }`;
621
+ const out = await spliced(source, (d) => {
622
+ d.tiles[0].filters = [{ field: "cat", given: "CATEGORY" }];
623
+ });
624
+ expect(out).toContain(
625
+ " view: kpis is {\n where: path ~ 'a{b'\n aggregate: n is count()\n where: cat ~ $CATEGORY\n }",
626
+ );
627
+ expect(out).toContain(" view: other is { aggregate: m is count() }\n}");
628
+ expect(out.match(/where: cat ~ \$CATEGORY/g)).toHaveLength(1);
629
+ const reopened = await openDocument(out);
630
+ expect(reopened.tiles[0].filters).toEqual([
631
+ { field: "cat", given: "CATEGORY" },
632
+ ]);
633
+ });
634
+
635
+ // The `}` variant: before the fix this refused outright, wrongly, on "a
636
+ // multi-stage pipeline" — the brace count went negative and the scan
637
+ // mistook it for an overshoot into the enclosing block.
638
+ it("places a new binding inside its own tile past a sibling holding a closing brace in a literal", async () => {
639
+ const source = `## artifact { title="T" tiles=["a -> kpis"] }
640
+ import "../m.malloy"
641
+
642
+ source: a is scoped_orders extend {
643
+ view: kpis is {
644
+ where: path ~ 'a}b'
645
+ aggregate: n is count()
646
+ }
647
+
648
+ view: other is { aggregate: m is count() }
649
+ }`;
650
+ const out = await spliced(source, (d) => {
651
+ d.tiles[0].filters = [{ field: "cat", given: "CATEGORY" }];
652
+ });
653
+ expect(out).toContain(
654
+ " view: kpis is {\n where: path ~ 'a}b'\n aggregate: n is count()\n where: cat ~ $CATEGORY\n }",
655
+ );
656
+ });
657
+
658
+ // The one-line-body bug end to end: an already-bound one-liner whose
659
+ // where: shares its line with the query, ticked again for the same value.
660
+ // Before the fix the read said unbound, so the "same" bind was actually
661
+ // a fresh add, appending a second where: beside the first.
662
+ it("round-trips a one-line body's where: shared with query text without duplicating it", async () => {
663
+ const boundOneLiner = `## artifact { title="T" tiles=["a -> kpis"] }
664
+ import "../m.malloy"
665
+
666
+ source: a is one extend {
667
+ view: kpis is { where: category ~ $CATEGORY, aggregate: n is count() }
668
+ }`;
669
+ const before = await openDocument(boundOneLiner);
670
+ expect(before.tiles[0].filters).toEqual([
671
+ { field: "category", given: "CATEGORY" },
672
+ ]);
673
+ const rebound = await spliced(boundOneLiner, (d) => {
674
+ d.tiles[0].filters = [{ field: "category", given: "CATEGORY" }];
675
+ });
676
+ expect(rebound).toBe(boundOneLiner);
677
+ expect(rebound.match(/where:/g)).toHaveLength(1);
678
+ const after = await openDocument(rebound);
679
+ expect(after.tiles[0].filters).toEqual([
680
+ { field: "category", given: "CATEGORY" },
681
+ ]);
682
+ });
683
+
684
+ // The opening/closing-line bug end to end: a where: sharing its line with
685
+ // the body's own `{` or `}` read as unbound, so re-binding the same value
686
+ // appended a duplicate rather than being a no-op.
687
+ it("round-trips a where: sharing the body's opening brace line without duplicating it", async () => {
688
+ const sharedOpen = `## artifact { title="T" tiles=["a -> kpis"] }
689
+ import "../m.malloy"
690
+
691
+ source: a is one extend {
692
+ view: kpis is { where: category ~ $CATEGORY
693
+ aggregate: n is count()
694
+ }
695
+ }`;
696
+ const before = await openDocument(sharedOpen);
697
+ expect(before.tiles[0].filters).toEqual([
698
+ { field: "category", given: "CATEGORY" },
699
+ ]);
700
+ const rebound = await spliced(sharedOpen, (d) => {
701
+ d.tiles[0].filters = [{ field: "category", given: "CATEGORY" }];
702
+ });
703
+ expect(rebound).toBe(sharedOpen);
704
+ expect(rebound.match(/where:/g)).toHaveLength(1);
705
+ const after = await openDocument(rebound);
706
+ expect(after.tiles[0].filters).toEqual([
707
+ { field: "category", given: "CATEGORY" },
708
+ ]);
709
+ });
710
+
711
+ it("round-trips a where: sharing the body's closing brace line without duplicating it", async () => {
712
+ const sharedClose = `## artifact { title="T" tiles=["a -> kpis"] }
713
+ import "../m.malloy"
714
+
715
+ source: a is one extend {
716
+ view: kpis is {
717
+ aggregate: n is count()
718
+ where: category ~ $CATEGORY }
719
+ }`;
720
+ const before = await openDocument(sharedClose);
721
+ expect(before.tiles[0].filters).toEqual([
722
+ { field: "category", given: "CATEGORY" },
723
+ ]);
724
+ const rebound = await spliced(sharedClose, (d) => {
725
+ d.tiles[0].filters = [{ field: "category", given: "CATEGORY" }];
726
+ });
727
+ expect(rebound).toBe(sharedClose);
728
+ expect(rebound.match(/where:/g)).toHaveLength(1);
729
+ const after = await openDocument(rebound);
730
+ expect(after.tiles[0].filters).toEqual([
731
+ { field: "category", given: "CATEGORY" },
732
+ ]);
733
+ });
734
+
735
+ // Dropping a binding that shares the body's closing line must leave the
736
+ // brace behind, not delete it along with the clause.
737
+ it("drops a binding sharing the closing brace line without losing the brace", async () => {
738
+ const sharedClose = `## artifact { title="T" tiles=["a -> kpis"] }
739
+ import "../m.malloy"
740
+
741
+ source: a is one extend {
742
+ view: kpis is {
743
+ aggregate: n is count()
744
+ where: category ~ $CATEGORY }
745
+ }`;
746
+ const out = await spliced(sharedClose, (d) => {
747
+ delete d.tiles[0].filters;
748
+ });
749
+ // The closing brace itself, not just the text before it: dropped whole
750
+ // line and all, the view's own `}` would go with the where: clause.
751
+ expect(out).toContain(" aggregate: n is count()\n }\n}");
752
+ expect(out).not.toContain("where:");
753
+ const reopened = await openDocument(out);
754
+ expect(reopened.tiles[0].declaration).toEqual({ kind: "inline" });
755
+ });
756
+
757
+ // Adding a second binding when the first already shares the closing
758
+ // brace line must keep it INSIDE the body, in the order asked for, not
759
+ // ahead of the surviving one and not past the `}`.
760
+ it("adds a second binding after one that shares the closing brace line, in order", async () => {
761
+ const sharedClose = `## artifact { title="T" tiles=["a -> kpis"] }
762
+ import "../m.malloy"
763
+
764
+ source: a is one extend {
765
+ view: kpis is {
766
+ aggregate: n is count()
767
+ where: category ~ $CATEGORY }
768
+ }`;
769
+ const out = await spliced(sharedClose, (d) => {
770
+ d.tiles[0].filters = [
771
+ { field: "category", given: "CATEGORY" },
772
+ { field: "brand", given: "BRAND" },
773
+ ];
774
+ });
775
+ expect(out).toContain(
776
+ " where: category ~ $CATEGORY\n where: brand ~ $BRAND }",
777
+ );
778
+ const reopened = await openDocument(out);
779
+ expect(reopened.tiles[0].filters).toEqual([
780
+ { field: "category", given: "CATEGORY" },
781
+ { field: "brand", given: "BRAND" },
782
+ ]);
783
+ });
784
+ });
785
+
226
786
  describe("spliceDashboardDocument: the dashboard's own givens", () => {
227
787
  // The convention: a filter the builder adds is a declaration in THIS file.
228
788
  // A file that had none gets the experiment switch too, since a `given:`
@@ -718,14 +1278,29 @@ const MODELLED_TAG =
718
1278
  * above. Comparing this before and after an edit catches what a file-wide
719
1279
  * count cannot: a tag that survived but moved onto a different declaration,
720
1280
  * which in Malloy is a change of meaning rather than a change of layout.
1281
+ *
1282
+ * The walk upward is written out here rather than taken from `blockAbove`, for
1283
+ * the same reason the scan below does not ask the reader where a declaration
1284
+ * is: a differential check that shares code with what it checks cannot see that
1285
+ * code being wrong.
721
1286
  */
722
1287
  function unmodelledTagsByDeclaration(text: string): Record<string, string[]> {
723
1288
  const lines = text.split("\n");
724
1289
  const out: Record<string, string[]> = {};
725
1290
  const record = (key: string, line: number) => {
726
- const tags = blockAbove(lines, line)
727
- .tags.map((t) => t.text)
728
- .filter((t) => !MODELLED_TAG.test(t));
1291
+ const tags: string[] = [];
1292
+ for (let i = line - 1; i >= 0; i--) {
1293
+ const at = lines[i].trim();
1294
+ if (at === "") break;
1295
+ if (at.startsWith("##")) continue;
1296
+ if (at.startsWith("#")) {
1297
+ if (!MODELLED_TAG.test(at)) tags.unshift(at);
1298
+ continue;
1299
+ }
1300
+ if (at.startsWith("//") || at.startsWith("--") || at.startsWith("/*"))
1301
+ continue;
1302
+ break;
1303
+ }
729
1304
  if (tags.length > 0) out[key] = tags;
730
1305
  };
731
1306
  // Keyed by the enclosing source as well as the name: `view:x` repeats
@@ -741,8 +1316,12 @@ function unmodelledTagsByDeclaration(text: string): Record<string, string[]> {
741
1316
  if (m[1] === "source") scope = m[2];
742
1317
  record(`${scope}/${m[1]}:${m[2]}`, i);
743
1318
  });
744
- for (const [name, at] of givenDeclarations(lines))
745
- record(`given:${name}`, at.line);
1319
+ // Scanned here rather than taken from the reader: a differential check
1320
+ // that shares code with what it checks cannot see that code being wrong.
1321
+ lines.forEach((line, i) => {
1322
+ const m = /^\s*(?:given:\s*)?([A-Za-z_][A-Za-z0-9_]*)\s*::/.exec(line);
1323
+ if (m) record(`given:${m[1]}`, i);
1324
+ });
746
1325
  return out;
747
1326
  }
748
1327
 
@@ -797,11 +1376,10 @@ describe("every composite dashboard survives an edit", () => {
797
1376
  const reread = await readDashboardDocument(result.source);
798
1377
  if (readFailed(reread)) throw new Error(reread.reason);
799
1378
  expect(reread.document.tiles[target].colspan).toBe(3);
800
- // Everything the file said that the builder does not model is still
801
- // there: the comment count is the cheapest proof.
802
- const comments = (text: string) =>
803
- text.split("\n").filter((l) => l.trim().startsWith("//")).length;
804
- expect(comments(result.source)).toBe(comments(source));
1379
+ // Every comment is still there, still attached to the same code.
1380
+ const moved = await whatMoved(source, result.source);
1381
+ expect(moved.comments).toEqual([]);
1382
+ expect(moved.attached).toEqual([]);
805
1383
  // And every `#` tag the builder does not model is still there, on the
806
1384
  // same declaration. A file-wide count cannot see a tag that moved to
807
1385
  // the declaration below, which is how one silently changes meaning.
@@ -810,6 +1388,144 @@ describe("every composite dashboard survives an edit", () => {
810
1388
  );
811
1389
  });
812
1390
 
1391
+ // The filter planner is the one this file's history says is hardest to
1392
+ // get right, so it gets the corpus treatment too: bind a control onto a
1393
+ // tile, and nothing the builder does not model may move.
1394
+ it(`round-trips a filter change in ${name}`, async () => {
1395
+ const source = fs.readFileSync(file, "utf8");
1396
+ const doc = await readDashboardDocument(source);
1397
+ if (readFailed(doc)) throw new Error(doc.reason);
1398
+ const target = doc.document.tiles.findIndex(
1399
+ (t) => t.declaration.kind !== "inherited",
1400
+ );
1401
+ // No tile declared here: a real shape, not a gap in the sweep.
1402
+ if (target < 0) return;
1403
+ // A name of its own where the file has one, else a synthetic one --
1404
+ // what is under test is where the clause LANDS, and most fixtures
1405
+ // declare no control, which would skip almost the whole corpus.
1406
+ const given = doc.document.localGivens?.[0]?.name ?? "PROBE_GIVEN";
1407
+
1408
+ const next = structuredClone(doc.document);
1409
+ const binding = { field: "_probe", given };
1410
+ next.tiles[target].filters = [
1411
+ ...(next.tiles[target].filters ?? []),
1412
+ binding,
1413
+ ];
1414
+ const result = await spliceDashboardDocument(source, next);
1415
+ // A refusal is a legitimate answer -- a given the tile already
1416
+ // filters on in text the builder does not manage, say -- but it has
1417
+ // to be a refusal, never a silent partial write.
1418
+ if (spliceFailed(result)) {
1419
+ expect(result.reason.length).toBeGreaterThan(0);
1420
+ return;
1421
+ }
1422
+ expect(await syntaxErrors(result.source)).toEqual([]);
1423
+ const reread = await readDashboardDocument(result.source);
1424
+ if (readFailed(reread)) throw new Error(reread.reason);
1425
+ expect(reread.document.tiles[target].filters).toContainEqual(binding);
1426
+ const moved = await whatMoved(source, result.source);
1427
+ expect(moved.comments).toEqual([]);
1428
+ expect(moved.attached).toEqual([]);
1429
+ expect(unmodelledTagsByDeclaration(result.source)).toEqual(
1430
+ unmodelledTagsByDeclaration(source),
1431
+ );
1432
+ });
1433
+
1434
+ /**
1435
+ * The REMOVAL kinds. Every case above adds or rewrites; removal is the
1436
+ * half that deletes a range wider than one node's own text, which is
1437
+ * where a comment or a declaration beside it goes without either gate
1438
+ * noticing. Measured: three of these five files declare every tile on
1439
+ * their source, so tile removal never reaches the deletion path in them
1440
+ * -- which is a real shape rather than a gap, and why the fixture sweep
1441
+ * in `invariants.spec.ts` carries the guarantee and this stays a
1442
+ * tripwire.
1443
+ */
1444
+ const survives = async (
1445
+ before: string,
1446
+ after: string,
1447
+ gone: string[],
1448
+ ) => {
1449
+ expect(await syntaxErrors(after)).toEqual([]);
1450
+ const moved = await whatMoved(before, after);
1451
+ expect(moved.declarations).toEqual(gone);
1452
+ expect(moved.tags).toEqual([]);
1453
+ expect(moved.block).toEqual([]);
1454
+ expect(moved.indent).toEqual([]);
1455
+ // A comment may leave with the declaration that was removed; none may
1456
+ // appear, and none may land on a statement that had none.
1457
+ expect(moved.attached.filter((e) => !e.startsWith("-"))).toEqual([]);
1458
+ expect(moved.comments.filter((e) => !e.startsWith("-"))).toEqual([]);
1459
+ expect(moved.residue).toEqual([]);
1460
+ };
1461
+
1462
+ it(`removes a tile from ${name} and disturbs nothing beside it`, async () => {
1463
+ const source = fs.readFileSync(file, "utf8");
1464
+ const doc = await readDashboardDocument(source);
1465
+ if (readFailed(doc)) throw new Error(doc.reason);
1466
+ const target = doc.document.tiles.findIndex(
1467
+ (t) => t.declaration.kind !== "inherited",
1468
+ );
1469
+ // One tile left, or every tile declared on its source: nothing here
1470
+ // reaches the declaration-deletion path.
1471
+ if (target < 0 || doc.document.tiles.length < 2) return;
1472
+
1473
+ const next = structuredClone(doc.document);
1474
+ const [gone] = next.tiles.splice(target, 1);
1475
+ const result = await spliceDashboardDocument(source, next);
1476
+ if (spliceFailed(result)) {
1477
+ expect(result.reason.length).toBeGreaterThan(0);
1478
+ return;
1479
+ }
1480
+ const reread = await readDashboardDocument(result.source);
1481
+ if (readFailed(reread)) throw new Error(reread.reason);
1482
+ expect(reread.document.tiles.map((t) => t.name)).not.toContain(
1483
+ gone.name,
1484
+ );
1485
+ await survives(source, result.source, [
1486
+ `-view:${gone.source}.${gone.name}`,
1487
+ ]);
1488
+ });
1489
+
1490
+ it(`unbinds a filter in ${name} and disturbs nothing beside it`, async () => {
1491
+ const source = fs.readFileSync(file, "utf8");
1492
+ const doc = await readDashboardDocument(source);
1493
+ if (readFailed(doc)) throw new Error(doc.reason);
1494
+ const target = doc.document.tiles.findIndex((t) => t.filters?.length);
1495
+ // No tile binds a control here: a real shape, not a gap.
1496
+ if (target < 0) return;
1497
+
1498
+ const next = structuredClone(doc.document);
1499
+ next.tiles[target].filters = next.tiles[target].filters!.slice(0, -1);
1500
+ const result = await spliceDashboardDocument(source, next);
1501
+ if (spliceFailed(result)) {
1502
+ expect(result.reason.length).toBeGreaterThan(0);
1503
+ return;
1504
+ }
1505
+ const tile = next.tiles[target];
1506
+ await survives(source, result.source, [
1507
+ `~view:${tile.source}.${tile.name}`,
1508
+ ]);
1509
+ });
1510
+
1511
+ it(`removes a control from ${name} and disturbs nothing beside it`, async () => {
1512
+ const source = fs.readFileSync(file, "utf8");
1513
+ const doc = await readDashboardDocument(source);
1514
+ if (readFailed(doc)) throw new Error(doc.reason);
1515
+ const givens = doc.document.localGivens;
1516
+ // Most dashboards declare no controls of their own.
1517
+ if (!givens?.length) return;
1518
+
1519
+ const next = structuredClone(doc.document);
1520
+ const gone = next.localGivens!.pop()!;
1521
+ const result = await spliceDashboardDocument(source, next);
1522
+ if (spliceFailed(result)) {
1523
+ expect(result.reason.length).toBeGreaterThan(0);
1524
+ return;
1525
+ }
1526
+ await survives(source, result.source, [`-given:${gone.name}`]);
1527
+ });
1528
+
813
1529
  it(`retags a control in ${name} and leaves every other tag where it was`, async () => {
814
1530
  const source = fs.readFileSync(file, "utf8");
815
1531
  const doc = await readDashboardDocument(source);
@@ -962,9 +1678,72 @@ given: SINCE :: date is @2023-01-01`);
962
1678
  });
963
1679
  });
964
1680
 
1681
+ /**
1682
+ * Two ways a save can fail with nothing written, and they want different
1683
+ * answers: nothing was recognized at all, or something was written and it read
1684
+ * back as a different dashboard. Reported identically, the person who hits one
1685
+ * cannot say which -- which is how an add-filter refusal went a round trip
1686
+ * before anyone knew whether a planner had even run.
1687
+ */
1688
+ /**
1689
+ * Malloy spells a comment three ways and the reader takes a tile's tags from
1690
+ * the parser, which knows all three. The writer walked the same block as text
1691
+ * and stopped at anything that was not `//`, so every tag above it was
1692
+ * invisible to it: a retag wrote a SECOND `# colspan` below the comment, the
1693
+ * reader read the lower one, and the read-back gate passed on a file now
1694
+ * carrying two.
1695
+ */
1696
+ describe("spliceDashboardDocument: a comment inside a tag block", () => {
1697
+ const dashed = (comment: string) => `##! experimental.givens
1698
+ ## artifact { title="T" tiles=["a -> revenue"] }
1699
+ import "../m.malloy"
1700
+
1701
+ source: a is one extend {
1702
+ # colspan=6
1703
+ ${comment}
1704
+ view: revenue is sales
1705
+ }`;
1706
+
1707
+ for (const [kind, comment] of [
1708
+ ["a `--` line", " -- six across, to sit beside the trend"],
1709
+ ["a `/* ... */` line", " /* six across, to sit beside the trend */"],
1710
+ [
1711
+ "a block comment over several lines",
1712
+ " /* six across,\n to sit beside the trend */",
1713
+ ],
1714
+ // The comment's own text is prose. Walking up past it to reach the real
1715
+ // tag must not turn a line inside it into a tag to rewrite.
1716
+ [
1717
+ "a block comment holding a line that looks like a tag",
1718
+ " /* it was\n # colspan=12\n until the map stopped fitting */",
1719
+ ],
1720
+ ] as const) {
1721
+ it(`patches the tag above ${kind} rather than writing a second one`, async () => {
1722
+ const out = await spliced(dashed(comment), (d) => {
1723
+ d.tiles[0].colspan = 3;
1724
+ });
1725
+ // The comment survives to the byte, the one real tag is rewritten in
1726
+ // place, and no second one appears under the comment.
1727
+ expect(out).toContain(
1728
+ ` # colspan=3\n${comment}\n view: revenue is sales`,
1729
+ );
1730
+ expect(out).not.toContain("# colspan=6");
1731
+ });
1732
+
1733
+ it(`takes the tag off above ${kind} rather than leaving it there`, async () => {
1734
+ const out = await spliced(dashed(comment), (d) => {
1735
+ delete d.tiles[0].colspan;
1736
+ });
1737
+ expect(out).toContain(`${comment}\n view: revenue is sales`);
1738
+ expect(out).not.toContain("# colspan=6");
1739
+ });
1740
+ }
1741
+ });
1742
+
965
1743
  describe("spliceDashboardDocument: an ask no planner could place", () => {
966
- it("refuses rather than reporting a write that never happened", async () => {
967
- const source = `##! experimental.givens
1744
+ // A `drill` sharing a line with a `label` is not the `# drill` line
1745
+ // `planDrills` looks for, so taking the drill off plans no edit at all.
1746
+ const UNPLACEABLE = `##! experimental.givens
968
1747
  ## artifact { title="T" tiles=["a -> x"] }
969
1748
  import "../m.malloy"
970
1749
 
@@ -974,12 +1753,22 @@ source: a is one extend {
974
1753
 
975
1754
  view: x is vx
976
1755
  }`;
977
- const reason = await refused(source, (d) => {
1756
+
1757
+ it("says nothing was recognized when no planner placed an edit", async () => {
1758
+ const reason = await refused(UNPLACEABLE, (d) => {
978
1759
  delete d.drills;
979
1760
  });
980
- expect(reason).toContain(
981
- "did not produce the dashboard that was asked for",
982
- );
1761
+ expect(reason).toContain("No part of this edit was recognized");
1762
+ });
1763
+
1764
+ // The same unplaceable ask, stacked on a title change that does plan an
1765
+ // edit: now something IS written, and it is the readback that refuses.
1766
+ it("says the readback differed when an edit was written", async () => {
1767
+ const reason = await refused(UNPLACEABLE, (d) => {
1768
+ d.title = "Renamed";
1769
+ delete d.drills;
1770
+ });
1771
+ expect(reason).toContain("did not read back as what was asked for");
983
1772
  });
984
1773
  });
985
1774
 
@@ -1159,3 +1948,148 @@ source: b is scoped_orders extend {
1159
1948
  expect(b).not.toContain("A by month");
1160
1949
  });
1161
1950
  });
1951
+
1952
+ /**
1953
+ * A source whose block opens on a LATER line than its `source:` line, because
1954
+ * the base is a multi-line `duckdb.sql("""…""")` literal. Any reader that
1955
+ * takes a declaration's extent to be its first line places all four of these
1956
+ * edits inside the SQL text, or before the source rather than after its close.
1957
+ */
1958
+ describe("spliceDashboardDocument: a source whose block opens after multi-line SQL", () => {
1959
+ const MULTILINE = `## artifact { title="T" tiles=["regional -> by_region", "regional -> by_month"] }
1960
+ import { other_source } from "../data_app.malloy"
1961
+
1962
+ source: regional is duckdb.sql("""
1963
+ select region, sum(amount) as total from orders group by 1
1964
+ """) extend {
1965
+ view: by_region is region_view
1966
+
1967
+ view: by_month is month_view
1968
+ }`;
1969
+
1970
+ // viewDeclarationLine: retagging a tile requires finding its `view:` line
1971
+ // WITHIN the source's own extent, which used to be just the `source:` line.
1972
+ it("finds and retags a view declared inside the source, not just its own line", async () => {
1973
+ const out = await spliced(MULTILINE, (d) => {
1974
+ d.tiles[0].colspan = 6;
1975
+ });
1976
+ expect(out).toContain(" # colspan=6\n view: by_region is region_view");
1977
+ });
1978
+
1979
+ // planRemovedTiles: the LAST view before the extend's own closing brace.
1980
+ // Nothing of `by_month`'s own declaration ever opens a block, so the scan
1981
+ // has to recognize the source's `}` as out of scope rather than deleting it
1982
+ // along with the view — over-deletion that would leave the source's
1983
+ // `extend {` unclosed.
1984
+ it("removes the last view before the extend's closing brace without touching it", async () => {
1985
+ const out = await spliced(MULTILINE, (d) => {
1986
+ d.tiles = d.tiles.filter((t) => t.name !== "by_month");
1987
+ });
1988
+ expect(out).toContain('tiles=["regional -> by_region"]');
1989
+ expect(out).not.toContain("by_month");
1990
+ // The closing brace is exactly one, and it is still the extend's own:
1991
+ // over-deletion would either take it or leave the block unclosed.
1992
+ expect(out.match(/^}/gm)).toHaveLength(1);
1993
+ expect(out).toContain(
1994
+ 'select region, sum(amount) as total from orders group by 1\n""") extend {\n view: by_region is region_view',
1995
+ );
1996
+ });
1997
+
1998
+ // planAddedTiles's `close`: a new view on THIS source is inserted before
1999
+ // its own closing brace, which is AFTER the SQL literal — never before the
2000
+ // `source:` line, where the old bug anchored every insertion.
2001
+ it("adds a tile inside the extension, after the SQL literal", async () => {
2002
+ const out = await spliced(MULTILINE, (d) => {
2003
+ d.tiles.push({
2004
+ name: "by_year",
2005
+ source: "regional",
2006
+ declaration: { kind: "reference", from: "year_view" },
2007
+ });
2008
+ });
2009
+ expect(out).toContain(` view: by_month is month_view
2010
+
2011
+ view: by_year is year_view
2012
+ }`);
2013
+ // Never inside the literal, and never ahead of the `source:` line.
2014
+ expect(out.indexOf("view: by_year")).toBeGreaterThan(
2015
+ out.indexOf('""") extend'),
2016
+ );
2017
+ });
2018
+
2019
+ // planAddedTiles's `lastExtensionEnd`: anchoring a brand NEW extension after
2020
+ // the LAST one in the file has to know where this one actually ends.
2021
+ it("anchors a new extension after this source's real close, not its source line", async () => {
2022
+ const out = await spliced(MULTILINE, (d) => {
2023
+ d.sources.push({ name: "other_tiles", base: "other_source" });
2024
+ d.tiles.push({
2025
+ name: "by_year",
2026
+ source: "other_tiles",
2027
+ declaration: { kind: "reference", from: "year_view" },
2028
+ });
2029
+ });
2030
+ const sourceEnd = out.indexOf('""") extend {\n');
2031
+ const newExtension = out.indexOf("source: other_tiles");
2032
+ expect(newExtension).toBeGreaterThan(sourceEnd);
2033
+ expect(out).toContain(`source: other_tiles is other_source extend {
2034
+ view: by_year is year_view
2035
+ }`);
2036
+ });
2037
+
2038
+ // A brace inside the `"""` span is the one case the round-trip gate cannot
2039
+ // catch: a spliced-in `view:` would read back as belonging to the source
2040
+ // above it either way. Refused outright rather than risked.
2041
+ // A brace inside the literal used to be unresolvable by a text scan, so
2042
+ // this refused. The lexer knows where the literal ends, so the tile lands
2043
+ // inside the extension instead.
2044
+ it("adds a tile past a brace inside the SQL literal", async () => {
2045
+ const source = MULTILINE.replace(
2046
+ "select region, sum(amount) as total from orders group by 1",
2047
+ "select {'region': 'West'} as region",
2048
+ );
2049
+ const out = await spliced(source, (d) => {
2050
+ d.tiles.push({
2051
+ name: "by_year",
2052
+ source: "regional",
2053
+ declaration: { kind: "reference", from: "year_view" },
2054
+ });
2055
+ });
2056
+ expect(out).toContain("select {'region': 'West'} as region");
2057
+ expect(out).toContain("view: by_year is year_view");
2058
+ });
2059
+ });
2060
+
2061
+ /**
2062
+ * Both brace scanners in malloyText.ts used to count a `{` inside a trailing
2063
+ * `//` comment as structure. `kpis`'s own extent ran through `other`, an
2064
+ * unrelated view, out to the enclosing source's closing brace — so a filter
2065
+ * bound to `kpis` returned `ok: true` and wrote the `where:` refinement after
2066
+ * `other`, at the end of the source block, instead of inside `kpis`. The
2067
+ * round-trip gate cannot catch this: the written text still reads back as a
2068
+ * `view:` under the right source either way.
2069
+ */
2070
+ describe("spliceDashboardDocument: a trailing comment holding an unbalanced brace", () => {
2071
+ const SOURCE = `## artifact { title="T" tiles=["a -> kpis", "a -> other"] }
2072
+ import "../m.malloy"
2073
+
2074
+ source: a is scoped_orders extend {
2075
+ view: kpis is {
2076
+ group_by: cat // the { brace here is unbalanced
2077
+ aggregate: n is count()
2078
+ }
2079
+
2080
+ view: other is { aggregate: m is count() }
2081
+ }`;
2082
+
2083
+ it("binds inside kpis's own body and never touches the unrelated view", async () => {
2084
+ const out = await spliced(SOURCE, (d) => {
2085
+ d.tiles[0].filters = [{ field: "cat", given: "CATEGORY" }];
2086
+ });
2087
+ expect(out).toContain(
2088
+ " view: kpis is {\n group_by: cat // the { brace here is unbalanced\n aggregate: n is count()\n where: cat ~ $CATEGORY\n }",
2089
+ );
2090
+ expect(out).toContain(" view: other is { aggregate: m is count() }\n}");
2091
+ expect(out).not.toContain(
2092
+ " view: other is { aggregate: m is count() }\n where:",
2093
+ );
2094
+ });
2095
+ });