@kayjs/kay 1.109.0 → 1.110.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 (115) hide show
  1. package/dist/eslint.js +332 -52
  2. package/editors/zed/extension.toml +2 -2
  3. package/llms/actions-from-islands.md +1 -1
  4. package/llms/components.md +1 -1
  5. package/llms/deprecated-lints.md +1 -1
  6. package/llms/island-and-form-lints.md +2 -1
  7. package/llms/islands.md +4 -2
  8. package/llms/live-values.md +1 -1
  9. package/llms/navigation-from-code.md +1 -1
  10. package/llms/navigation.md +4 -2
  11. package/llms/templates-elements-slots-snippets.md +2 -2
  12. package/llms/upgrading-archive.md +31 -1
  13. package/llms/upgrading.md +26 -32
  14. package/llms/whats-new.md +15 -0
  15. package/llms.txt +1 -1
  16. package/package.json +6 -6
  17. package/src/build/variants.ts +132 -18
  18. package/src/check/env-types.ts +1 -1
  19. package/src/check/project.ts +4 -0
  20. package/src/check/schema-builders.ts +125 -26
  21. package/src/commands/upgrade.ts +2 -1
  22. package/src/compiler/allow-comments.ts +38 -2
  23. package/src/compiler/ast.ts +4 -4
  24. package/src/compiler/codegen.ts +3 -3
  25. package/src/compiler/deprecated-lints-1-106.ts +2 -2
  26. package/src/compiler/hand-parts.ts +36 -8
  27. package/src/compiler/helper-imports.ts +2 -2
  28. package/src/compiler/index.ts +4 -3
  29. package/src/compiler/island-arguments.ts +9 -0
  30. package/src/compiler/island-lints.ts +7 -0
  31. package/src/compiler/items.ts +12 -0
  32. package/src/compiler/jsx.ts +5 -4
  33. package/src/compiler/lints.ts +5 -6
  34. package/src/compiler/markup.ts +16 -21
  35. package/src/compiler/names.ts +1 -1
  36. package/src/compiler/removed-lints.ts +90 -0
  37. package/src/compiler/signal-from-prop.ts +141 -0
  38. package/src/compiler/template-reads.ts +16 -0
  39. package/src/runtime/checks.ts +14 -2
  40. package/src/runtime/client.ts +5 -9
  41. package/src/runtime/dom.ts +1 -1
  42. package/src/runtime/html.ts +1 -1
  43. package/src/runtime/image.ts +2 -19
  44. package/src/runtime/index.ts +1 -1
  45. package/src/runtime/island.server.ts +40 -10
  46. package/src/runtime/navigate.ts +9 -0
  47. package/src/runtime/navigation.ts +5 -1
  48. package/src/runtime/page-swap.ts +2 -2
  49. package/src/runtime/swap-flight.ts +10 -10
  50. package/src/runtime/swap-kept.ts +69 -29
  51. package/src/runtime/swap-morph.ts +49 -9
  52. package/src/runtime/text-hash.ts +17 -0
  53. package/src/runtime/uid.server.ts +6 -4
  54. package/src/runtime/values.ts +12 -0
  55. package/src/server/render-document.ts +8 -6
  56. package/src/server/render.ts +1 -1
  57. package/types/build/variants.d.ts +9 -1
  58. package/types/build/variants.d.ts.map +1 -1
  59. package/types/check/project.d.ts.map +1 -1
  60. package/types/check/schema-builders.d.ts.map +1 -1
  61. package/types/commands/upgrade.d.ts.map +1 -1
  62. package/types/compiler/allow-comments.d.ts +2 -0
  63. package/types/compiler/allow-comments.d.ts.map +1 -1
  64. package/types/compiler/ast.d.ts +1 -1
  65. package/types/compiler/ast.d.ts.map +1 -1
  66. package/types/compiler/deprecated-lints-1-106.d.ts +2 -2
  67. package/types/compiler/deprecated-lints-1-106.d.ts.map +1 -1
  68. package/types/compiler/deprecated-lints.d.ts +2 -2
  69. package/types/compiler/hand-parts.d.ts +6 -3
  70. package/types/compiler/hand-parts.d.ts.map +1 -1
  71. package/types/compiler/index.d.ts.map +1 -1
  72. package/types/compiler/island-arguments.d.ts +5 -0
  73. package/types/compiler/island-arguments.d.ts.map +1 -1
  74. package/types/compiler/island-lints.d.ts +7 -0
  75. package/types/compiler/island-lints.d.ts.map +1 -1
  76. package/types/compiler/items.d.ts +1 -0
  77. package/types/compiler/items.d.ts.map +1 -1
  78. package/types/compiler/jsx.d.ts.map +1 -1
  79. package/types/compiler/lints.d.ts +11 -4
  80. package/types/compiler/lints.d.ts.map +1 -1
  81. package/types/compiler/markup.d.ts +1 -1
  82. package/types/compiler/markup.d.ts.map +1 -1
  83. package/types/compiler/names.d.ts.map +1 -1
  84. package/types/compiler/removed-lints.d.ts +3 -0
  85. package/types/compiler/removed-lints.d.ts.map +1 -0
  86. package/types/compiler/signal-from-prop.d.ts +4 -0
  87. package/types/compiler/signal-from-prop.d.ts.map +1 -0
  88. package/types/compiler/template-reads.d.ts +1 -0
  89. package/types/compiler/template-reads.d.ts.map +1 -1
  90. package/types/runtime/checks.d.ts +8 -2
  91. package/types/runtime/checks.d.ts.map +1 -1
  92. package/types/runtime/client.d.ts.map +1 -1
  93. package/types/runtime/dom.d.ts +1 -1
  94. package/types/runtime/dom.d.ts.map +1 -1
  95. package/types/runtime/html.d.ts +1 -1
  96. package/types/runtime/html.d.ts.map +1 -1
  97. package/types/runtime/image.d.ts.map +1 -1
  98. package/types/runtime/index.d.ts +1 -1
  99. package/types/runtime/index.d.ts.map +1 -1
  100. package/types/runtime/island.server.d.ts +1 -0
  101. package/types/runtime/island.server.d.ts.map +1 -1
  102. package/types/runtime/navigate.d.ts.map +1 -1
  103. package/types/runtime/navigation.d.ts +2 -0
  104. package/types/runtime/navigation.d.ts.map +1 -1
  105. package/types/runtime/swap-flight.d.ts +1 -1
  106. package/types/runtime/swap-flight.d.ts.map +1 -1
  107. package/types/runtime/swap-kept.d.ts.map +1 -1
  108. package/types/runtime/swap-morph.d.ts.map +1 -1
  109. package/types/runtime/text-hash.d.ts +2 -0
  110. package/types/runtime/text-hash.d.ts.map +1 -0
  111. package/types/runtime/uid.server.d.ts.map +1 -1
  112. package/types/runtime/values.d.ts +4 -0
  113. package/types/runtime/values.d.ts.map +1 -1
  114. package/types/server/render-document.d.ts +1 -1
  115. package/types/server/render-document.d.ts.map +1 -1
@@ -5,10 +5,13 @@ import { dirname, join } from 'node:path'
5
5
  import { elementsIn } from '../compiler/ast'
6
6
  import { changeName } from '../compiler/bound-props'
7
7
  import { parseExpanded } from '../compiler/markdown-block'
8
+ import { analyzeScript } from '../compiler/script'
8
9
 
9
10
  // A component names the features an app may leave out with `uses('selectable')`, the `uses` it imports from kayjs-ui's marker module: a call that is true while the prop is there to be written, and that a browser build replaces with `true` or `false` once it has read the props the files of the project write at their call sites. See `specializedSource`.
10
11
  const USES_CALL = /\buses\(\s*'(\w+)'(\s*,\s*true)?\s*\)/y
11
12
  const KAY_IMPORT = /^import\s+(\w+)\s+from\s+(["'])([^"'\n]+\.kay)\2/gm
13
+ // Whether a file imports a `.kay` component, one that may hand its rest props on to a component with features.
14
+ const HAS_KAY_IMPORT = /^import\s+\w+\s+from\s+(["'])[^"'\n]+\.kay\1/m
12
15
  // A component the compiler imports lazily, `KayLazy(key, () => import("./it.kay"))`.
13
16
  const LAZY_IMPORT = /\bimport\(\s*(["'])([^"'\n]+\.kay)\1\s*\)/g
14
17
  const USES_IMPORT = /^import\s*\{[^}]*\buses\b[^}]*\}\s*from\s*(["'])([^"'\n]+)\1/m
@@ -20,6 +23,7 @@ const FENCE = /^---(?:\s|$)/
20
23
  const USES_IF = /^([ \t]*)((?:else )?if) (.*\buses\(.*)$/
21
24
  const IDENTIFIER_CHAR = /[\w$.]/
22
25
  const BACKSLASH = /\\/g
26
+ const COMMENT_LINE = /^[ \t]*\/\/.*$/gm
23
27
 
24
28
  // The suffix an import of a variant carries: the features, joined by dashes (a dot would end the stem of the file name the bundler gives an entry), the call sites of the project use.
25
29
  // `~` and the props the call sites write follow when the project reads them all: the props a spread may carry are not known.
@@ -176,14 +180,18 @@ function replaceCalls(text: string, answer: (feature: string, onByDefault: boole
176
180
  interface Declared {
177
181
  names: string[]
178
182
  defaults: ReadonlySet<string>
183
+ // Whether the file imports a `.kay` component, so its callers' props may reach a feature through it.
184
+ imports?: boolean
179
185
  }
180
186
 
181
187
  const NONE: Declared = { names: [], defaults: new Set() }
182
188
  const featuresOf = new Map<string, { stamp: number, declared: Promise<Declared> }>()
183
189
 
184
190
  function usesIn(source: string, file: string): Declared {
191
+ const imports = HAS_KAY_IMPORT.test(source)
192
+
185
193
  if (file !== '' && !importsMarker(source, file))
186
- return NONE
194
+ return imports ? { ...NONE, imports } : NONE
187
195
 
188
196
  const found = new Set<string>()
189
197
  const defaults = new Set<string>()
@@ -197,7 +205,7 @@ function usesIn(source: string, file: string): Declared {
197
205
  return ''
198
206
  })
199
207
 
200
- return { names: [...found], defaults }
208
+ return { names: [...found], defaults, imports }
201
209
  }
202
210
 
203
211
  // The features a text names: the `uses('x')` of a file importing the marker, none otherwise.
@@ -466,12 +474,18 @@ export function specializedSource(source: string, present: ReadonlySet<string>,
466
474
  // Stands for every prop of a component: it is called with a spread or read as a value, so any may be written.
467
475
  export const ANY = Symbol('any')
468
476
 
477
+ // Stands in a call's props for a spread of the file's own rest props: what the file's callers write reaches the component, minus the props the file takes by name.
478
+ const PASSED = '...'
479
+ // Starts what stands in the props for `name={prop}`, `prop` a prop the file takes by name with no default: `name` is written when the file's callers write `prop`.
480
+ const FORWARDED = '>'
481
+
469
482
  // What stands for a call that leaves a feature on by default (`uses('x', true)`) on: the prop left out or written with anything but a literal `false`.
470
483
  const ON_PREFIX = '+'
471
484
  const PROP_NAME = /^\w+$/
472
485
 
473
486
  // The props the call sites of each `.kay` component a file imports write, by the name the file gives it; `defaults` names, by local, the features on when the prop is left out, which a call keeps on by adding `+name`.
474
- export function propsWritten(source: string, locals: readonly string[], defaults: ReadonlyMap<string, ReadonlySet<string>> = new Map()): Map<string, Set<string> | typeof ANY> {
487
+ // A spread of `rest.name`, the file's own rest props, hands its callers' props on instead of any: `PASSED` stands in the props for it. An attribute written as a prop `rest.forwards` names is written when that prop is.
488
+ export function propsWritten(source: string, locals: readonly string[], defaults: ReadonlyMap<string, ReadonlySet<string>> = new Map(), rest?: Pick<Rest, 'name' | 'forwards'>): Map<string, Set<string> | typeof ANY> {
475
489
  const { file } = parseExpanded(source)
476
490
  const written = new Map<string, Set<string>>()
477
491
  const calls = new Map<string, number>()
@@ -488,10 +502,17 @@ export function propsWritten(source: string, locals: readonly string[], defaults
488
502
  written.set(element.name, props)
489
503
 
490
504
  const off = new Set<string>()
505
+ let passed = false
491
506
 
492
507
  for (const attribute of element.attributes) {
493
508
  if (attribute.kind === 'spread') {
494
- open.delete(element.name)
509
+ if (rest !== undefined && source.slice(attribute.expression.start, attribute.expression.end).trim() === rest.name) {
510
+ props.add(PASSED)
511
+ passed = true
512
+ }
513
+ else {
514
+ open.delete(element.name)
515
+ }
495
516
 
496
517
  continue
497
518
  }
@@ -506,14 +527,18 @@ export function propsWritten(source: string, locals: readonly string[], defaults
506
527
  continue
507
528
  }
508
529
 
509
- props.add(name)
530
+ const value = attribute.kind === 'expression' ? source.slice(attribute.expression.start, attribute.expression.end).trim() : undefined
531
+ const forwarded = value === undefined ? undefined : rest?.forwards.get(value)
532
+
533
+ props.add(forwarded === undefined ? name : `${FORWARDED}${name}=${forwarded}`)
510
534
 
511
- if (attribute.kind === 'expression' && source.slice(attribute.expression.start, attribute.expression.end).trim() === 'false')
535
+ if (value === 'false')
512
536
  off.add(name)
513
537
  }
514
538
 
515
539
  for (const feature of defaults.get(element.name) ?? []) {
516
- if (!off.has(feature))
540
+ // A spread may bring the prop back on, whatever was written before it.
541
+ if (passed || !off.has(feature))
517
542
  props.add(ON_PREFIX + feature)
518
543
  }
519
544
 
@@ -522,15 +547,42 @@ export function propsWritten(source: string, locals: readonly string[], defaults
522
547
  }
523
548
  }
524
549
 
550
+ // A comment line naming the component is no read of it.
551
+ const code = source.replace(COMMENT_LINE, '')
552
+
525
553
  for (const local of locals) {
526
554
  // The import names it once, each call once more.
527
- if ((source.match(new RegExp(`\\b${local}\\b`, 'g'))?.length ?? 0) !== 1 + (calls.get(local) ?? 0))
555
+ if ((code.match(new RegExp(`\\b${local}\\b`, 'g'))?.length ?? 0) !== 1 + (calls.get(local) ?? 0))
528
556
  open.delete(local)
529
557
  }
530
558
 
531
559
  return new Map(locals.map(local => [local, open.has(local) ? written.get(local) ?? new Set<string>() : ANY]))
532
560
  }
533
561
 
562
+ // The name of a file's rest props (none when it has none), the props it takes by name (which its spread of the rest does not hand on) and, of those with no default, the key by the name the file reads it as.
563
+ interface Rest {
564
+ name: string
565
+ taken: Set<string>
566
+ forwards: Map<string, string>
567
+ }
568
+
569
+ function restOf(source: string): Rest | undefined {
570
+ try {
571
+ const { file } = parseExpanded(source)
572
+ const { props } = analyzeScript(file.source, file.script, [], file.module)
573
+
574
+ if (props === undefined)
575
+ return undefined
576
+
577
+ const forwards = new Map(props.bindings.filter(binding => binding.fallback === undefined).map(binding => [file.source.slice(binding.local.start, binding.local.end), binding.key]))
578
+
579
+ return { name: props.rest === undefined ? '' : file.source.slice(props.rest.start, props.rest.end), taken: new Set(props.bindings.map(binding => binding.key)), forwards }
580
+ }
581
+ catch {
582
+ return undefined
583
+ }
584
+ }
585
+
534
586
  interface Candidate {
535
587
  local: string
536
588
  specifier: string
@@ -539,8 +591,8 @@ interface Candidate {
539
591
  defaults: ReadonlySet<string>
540
592
  }
541
593
 
542
- // The `.kay` components a file imports that name features.
543
- async function candidatesOf(code: string, file: string): Promise<Candidate[]> {
594
+ // The `.kay` components a file imports that name features, and with `passing` those importing a component too, whose callers may reach a feature through them.
595
+ async function candidatesOf(code: string, file: string, passing = false): Promise<Candidate[]> {
544
596
  const found: Candidate[] = []
545
597
 
546
598
  for (const [local, specifier] of [...code.matchAll(KAY_IMPORT).map(([, name, , from]) => [name!, from!] as const), ...code.matchAll(LAZY_IMPORT).map(([, , from]) => ['', from!] as const)]) {
@@ -553,9 +605,9 @@ async function candidatesOf(code: string, file: string): Promise<Candidate[]> {
553
605
  continue
554
606
  }
555
607
 
556
- const { names: features, defaults } = await declaredFeatures(path)
608
+ const { names: features, defaults, imports } = await declaredFeatures(path)
557
609
 
558
- if (features.length > 0)
610
+ if (features.length > 0 || (passing && imports === true))
559
611
  found.push({ local, specifier, path, features, defaults })
560
612
  }
561
613
 
@@ -565,6 +617,8 @@ async function candidatesOf(code: string, file: string): Promise<Candidate[]> {
565
617
  // What the `.kay` files of a project write of each component with features, all of them together: a component has one variant, so the chunks of two islands using a Table share it.
566
618
  export class VariantIndex {
567
619
  private readonly union = new Map<string, Set<string> | typeof ANY>()
620
+ // The files handing their rest props on to a component, by its path: what their own callers write reaches it.
621
+ private readonly through = new Map<string, { from: string, taken: ReadonlySet<string>, forwards: [name: string, key: string][] }[]>()
568
622
  private readonly indexed = new Map<string, Promise<void>>()
569
623
  private scan: Promise<void> | undefined
570
624
 
@@ -594,15 +648,16 @@ export class VariantIndex {
594
648
  }
595
649
 
596
650
  private async read(file: string, source: string): Promise<void> {
597
- const candidates = (await candidatesOf(source, file)).filter(candidate => candidate.local !== '')
651
+ const candidates = (await candidatesOf(source, file, true)).filter(candidate => candidate.local !== '')
598
652
 
599
653
  if (candidates.length === 0)
600
654
  return
601
655
 
602
656
  let written: ReturnType<typeof propsWritten>
657
+ const rest = restOf(source)
603
658
 
604
659
  try {
605
- written = propsWritten(source, candidates.map(candidate => candidate.local), new Map(candidates.map(candidate => [candidate.local, candidate.defaults])))
660
+ written = propsWritten(source, candidates.map(candidate => candidate.local), new Map(candidates.map(candidate => [candidate.local, candidate.defaults])), rest)
606
661
  }
607
662
  catch {
608
663
  written = new Map(candidates.map(candidate => [candidate.local, ANY]))
@@ -612,13 +667,62 @@ export class VariantIndex {
612
667
  const props = written.get(local) ?? new Set<string>()
613
668
  const before = this.union.get(path)
614
669
 
670
+ if (props !== ANY && rest !== undefined) {
671
+ const forwards = [...props].filter(name => name.startsWith(FORWARDED)).map(name => name.slice(1).split('=') as [string, string])
672
+
673
+ for (const name of [...props].filter(name => name.startsWith(FORWARDED)))
674
+ props.delete(name)
675
+
676
+ if (props.delete(PASSED) || forwards.length > 0)
677
+ this.through.set(path, [...this.through.get(path) ?? [], { from: realFile(file), taken: rest.taken, forwards }])
678
+ }
679
+
615
680
  this.union.set(path, before === ANY || props === ANY ? ANY : new Set([...before ?? [], ...props]))
616
681
  }
617
682
  }
618
683
 
684
+ // What the call sites of a component write, the ones handing their rest props on counted by what their own callers write.
685
+ private writtenOf(path: string, seen = new Set<string>()): Set<string> | typeof ANY {
686
+ const own = this.union.get(path)
687
+
688
+ if (own === ANY)
689
+ return ANY
690
+
691
+ const links = this.through.get(path)
692
+
693
+ if (links === undefined || seen.has(path))
694
+ return own ?? new Set<string>()
695
+
696
+ const all = new Set(own)
697
+
698
+ seen.add(path)
699
+
700
+ for (const { from, taken, forwards } of links) {
701
+ // A file no scanned call site writes is called from where the scan does not look (a route, a layout, a `.ts` module, a package), so what reaches it is unknown.
702
+ const outer = this.union.has(from) || this.through.has(from) ? this.writtenOf(from, seen) : ANY
703
+
704
+ if (outer === ANY)
705
+ return ANY
706
+
707
+ for (const [name, key] of forwards) {
708
+ if (outer.has(key))
709
+ all.add(name)
710
+ }
711
+
712
+ for (const name of outer) {
713
+ if (!name.startsWith(ON_PREFIX) && !taken.has(name))
714
+ all.add(name)
715
+ }
716
+ }
717
+
718
+ seen.delete(path)
719
+
720
+ return all
721
+ }
722
+
619
723
  // The query of a variant: its features, then the props written.
620
724
  private usedOf(path: string, features: string[], defaults: ReadonlySet<string>): string {
621
- const props = this.union.get(path) ?? new Set<string>()
725
+ const props = this.writtenOf(path)
622
726
 
623
727
  if (props === ANY)
624
728
  return [...features].sort().join('-')
@@ -642,12 +746,12 @@ export class VariantIndex {
642
746
  async variantImports(code: string, file: string, source: string): Promise<string> {
643
747
  const candidates = await candidatesOf(code, file)
644
748
 
645
- if (candidates.length === 0)
646
- return code
647
-
648
749
  await this.scanned()
649
750
  await this.add(file, source)
650
751
 
752
+ if (candidates.length === 0)
753
+ return code
754
+
651
755
  let result = code
652
756
 
653
757
  for (const { specifier, path, features, defaults } of candidates) {
@@ -661,6 +765,16 @@ export class VariantIndex {
661
765
  }
662
766
  }
663
767
 
768
+ // A file by the path its importers resolve it to.
769
+ function realFile(file: string): string {
770
+ try {
771
+ return Bun.resolveSync(file, dirname(file))
772
+ }
773
+ catch {
774
+ return file
775
+ }
776
+ }
777
+
664
778
  // The `.kay` files under a directory, leaving out what a project installs and builds.
665
779
  export function kayFiles(dir: string): string[] {
666
780
  const found: string[] = []
@@ -182,7 +182,7 @@ function environment(patterns: string[], files: string[], api: { mount: string,
182
182
  ' function KayFormError<Target extends string | Action>(target: Target, field?: FieldName<Target>): null',
183
183
  ' function KayProp<Component>(component: Component): <Value>(value: Value & IslandProp<Component, Value>) => Value',
184
184
  ' function KayPlainProp<Component>(component: Component): <Value>(value: Value & PlainIslandProp<Component, Value>) => Value',
185
- ' function KayFunctionProp<Component>(component: Component): (attribute: FunctionProp<Component>) => Record<never, never>',
185
+ ' function KayFunctionProp<Component, Names extends object = Record<string, unknown>>(component: Component, names?: Names): (attribute: FunctionProp<Component, Names>) => Record<never, never>',
186
186
  ' function KayHandsPart<Component>(component: Component): <Name extends string>(name: Name & HandsPart<Component, Name>) => Record<never, never>',
187
187
  ' function KayBound<Component>(component: Component): <Key extends string, Value>(key: Key & BoundProp<Component, Key>, value: Value, write: (value: BoundValue<Component, Key>) => unknown) => Value',
188
188
  ' function KayList<Each extends Iterable<any> | null | undefined | false>(each: Each): Each',
@@ -19,6 +19,7 @@ import { importedSignals } from '../build/signals'
19
19
  import { browserRole, onceReadChecks } from '../compiler'
20
20
  import { moduleChecks, turnsCaptchaOff } from '../compiler/fence-checks'
21
21
  import { isLaunchLint, isLint, isLintGroup, LEVELS, lintLevel, lintLevels } from '../compiler/lints'
22
+ import { REMOVED_LINTS } from '../compiler/removed-lints'
22
23
  import { CONFIG_FILE } from '../config'
23
24
  import { EXTENSIONS_MARKER, FEEDS_MARKER, PROBLEMS_MARKER, ROUTES_MARKER, USES_MARKER } from '../content/claims'
24
25
  import { projectPaths } from '../project'
@@ -295,6 +296,9 @@ function lintConfigProblems(root: string, lints: LintLevels = {}): CheckDiagnost
295
296
  return levelEntries(lints).flatMap(([name, level]) => {
296
297
  const at = { file, ...locate(['lints', name]) }
297
298
 
299
+ if ((REMOVED_LINTS as readonly string[]).includes(name))
300
+ return [{ ...at, severity: 'warning' as const, message: `\`lints\` names \`${name}\`, a lint kay has removed with the form it reported`, help: 'remove the entry: it changes nothing' }]
301
+
298
302
  if (!isLint(name) && !isLintGroup(name))
299
303
  return [{ ...at, message: `\`lints\` names \`${name}\`, which is no lint or group`, help: '`kay explain` lists them' }]
300
304
 
@@ -31,6 +31,39 @@ const OLD_SIZE = /^\d+(?:\.\d+)?[kmg]$/i
31
31
  const KAY = /^kay(?:\/|$)/
32
32
  const NEEDLE = /\.(?:String|Secret|Number|Numeric|Integer|Boolean|BooleanString|Date|File|Files|Literal|Union|Array|Object|UnionEnum|UnionKeys|Public|Optional)\(|\.(?:file|files)\(/
33
33
 
34
+ interface Mapped {
35
+ record: Node
36
+ literal: Node
37
+ }
38
+
39
+ // `Object.keys(R).map(key => s.Literal(key))`, a cast on the key allowed: the record whose keys are the literals.
40
+ function mappedKeys(node: Node, receivers: Set<string>): Mapped | undefined {
41
+ if (node.type !== 'CallExpression' || node.callee.type !== 'MemberExpression' || node.callee.computed || node.callee.property.type !== 'Identifier' || node.callee.property.name !== 'map' || node.arguments.length !== 1)
42
+ return undefined
43
+
44
+ const keys = node.callee.object
45
+ const [callback] = node.arguments
46
+
47
+ if (keys.type !== 'CallExpression' || keys.arguments.length !== 1 || keys.callee.type !== 'MemberExpression' || keys.callee.computed || keys.callee.object.type !== 'Identifier' || keys.callee.object.name !== 'Object' || keys.callee.property.type !== 'Identifier' || keys.callee.property.name !== 'keys')
48
+ return undefined
49
+
50
+ const [param] = callback?.type === 'ArrowFunctionExpression' ? callback.params : []
51
+
52
+ if (callback?.type !== 'ArrowFunctionExpression' || callback.params.length !== 1 || param?.type !== 'Identifier')
53
+ return undefined
54
+
55
+ const literal = builderCall(callback.body, receivers)
56
+ let inner = literal?.node.arguments[0]
57
+
58
+ while (inner && (inner.type === 'TSAsExpression' || inner.type === 'TSNonNullExpression'))
59
+ inner = inner.expression
60
+
61
+ if (literal?.name !== 'Literal' || literal.node.arguments.length !== 1 || inner?.type !== 'Identifier' || inner.name !== param.name)
62
+ return undefined
63
+
64
+ return { record: keys.arguments[0]!, literal: callback.body }
65
+ }
66
+
34
67
  interface Call {
35
68
  node: Node & { type: 'CallExpression' }
36
69
  name: string
@@ -79,10 +112,44 @@ function renames(call: Call, base: number): Edit[] {
79
112
  return edits
80
113
  }
81
114
 
82
- // Where `optional: true` goes in a builder's call: into its options object, or after its last argument. Undefined for options that are not an object literal, which the fix leaves to the app.
83
- function optionalEdit(call: Call, base: number): Edit | undefined {
115
+ // The options the lowercase builder needs to read as the PascalCase one did: a list takes `max` where it had none (the lowercase one stops at 1,000 items, except a list of files), and an object `extra: 'strip'` (the lowercase one refuses a key its shape lacks). Undefined when the options are not an object literal of known keys, which the fix cannot add to.
116
+ function keptOptions(call: Call): string[] | undefined {
117
+ const index = BUILDERS[call.name]!.options
118
+ const options = call.node.arguments[index]
119
+ const keys = new Set<string>()
120
+
121
+ if (options !== undefined && options.type !== 'ObjectExpression')
122
+ return call.name === 'Array' || call.name === 'Object' ? undefined : []
123
+
124
+ for (const entry of options?.properties ?? []) {
125
+ const name = keyName(entry)
126
+
127
+ if (name === undefined)
128
+ return call.name === 'Array' || call.name === 'Object' ? undefined : []
129
+
130
+ keys.add(name)
131
+ }
132
+
133
+ if (call.name === 'Object')
134
+ return keys.has('extra') ? [] : ['extra: \'strip\'']
135
+
136
+ if (call.name !== 'Array')
137
+ return []
138
+
139
+ const [item] = call.node.arguments
140
+
141
+ return keys.has('max') || keys.has('maxItems') || (item && FILES.has(builderCallName(item))) ? [] : ['max: Number.MAX_SAFE_INTEGER']
142
+ }
143
+
144
+ function builderCallName(node: Node): string {
145
+ return node.type === 'CallExpression' && node.callee.type === 'MemberExpression' && node.callee.property.type === 'Identifier' ? node.callee.property.name : ''
146
+ }
147
+
148
+ // Where options go in a builder's call: into its options object, or after its last argument. Undefined for options that are not an object literal, which the fix leaves to the app.
149
+ function addOptions(call: Call, base: number, added: string[]): Edit | undefined {
84
150
  const index = BUILDERS[call.name]!.options
85
151
  const options = call.node.arguments[index]
152
+ const text = added.join(', ')
86
153
 
87
154
  if (options === undefined) {
88
155
  if (call.node.arguments.length < index)
@@ -90,7 +157,7 @@ function optionalEdit(call: Call, base: number): Edit | undefined {
90
157
 
91
158
  const close = base + call.node.end - 1
92
159
 
93
- return { start: close, end: close, text: call.node.arguments.length === 0 ? '{ optional: true }' : ', { optional: true }' }
160
+ return { start: close, end: close, text: call.node.arguments.length === 0 ? `{ ${text} }` : `, { ${text} }` }
94
161
  }
95
162
 
96
163
  if (options.type !== 'ObjectExpression')
@@ -98,7 +165,7 @@ function optionalEdit(call: Call, base: number): Edit | undefined {
98
165
 
99
166
  const open = base + options.start
100
167
 
101
- return { start: open, end: open + 1, text: options.properties.length === 0 ? '{ optional: true ' : '{ optional: true,' }
168
+ return { start: open, end: open + 1, text: options.properties.length === 0 ? `{ ${text} ` : `{ ${text},` }
102
169
  }
103
170
 
104
171
  type Program = Parameters<typeof importsOf>[0]
@@ -146,8 +213,26 @@ function dropUnreadImport(ast: Program, receivers: Set<string>, dropped: number,
146
213
  }
147
214
  }
148
215
 
216
+ // `defineEnv(s.Object({ ... }))`: an env reads only the names its schema declares, so the record changes nothing. True when it reported one.
217
+ function envRecord(node: Node, records: Set<string>, receivers: Set<string>, base: number, taken: Set<Node>, report: Report): boolean {
218
+ if (node.type !== 'CallExpression' || node.callee.type !== 'Identifier' || !records.has(node.callee.name))
219
+ return false
220
+
221
+ const [schema] = node.arguments
222
+ const inner = schema === undefined ? undefined : builderCall(schema, receivers)
223
+ const shape = inner?.node.arguments[0]
224
+
225
+ if (!schema || inner?.name !== 'Object' || inner.node.arguments.length !== 1 || shape?.type !== 'ObjectExpression')
226
+ return false
227
+
228
+ taken.add(schema)
229
+ report(base + schema.start, base + schema.end, 'a plain record of fields is the schema of a defineEnv since 1.106, `s.Object` being the PascalCase builder it replaces; the old form works until 2.0', 'write the record of fields', [{ start: base + schema.start, end: base + shape.start, text: '' }, { start: base + shape.end, end: base + schema.end, text: '' }])
230
+
231
+ return true
232
+ }
233
+
149
234
  // The PascalCase builders of `s`, which kay 1.106 replaces with its own lowercase ones, and the `'2m'` sizes of a file field, which are `'2mb'` as every size is.
150
- // Found on the `s` a file imports from `kay`, in the TypeScript files and the fences of `.kay` files. `s.Optional(x)` of one of these builders is `optional: true` in its options; an `s.Object({ ... })` that is the schema of an `action` or a `defineEnv` is the record alone.
235
+ // Found on the `s` a file imports from `kay`, in the TypeScript files and the fences of `.kay` files. `s.Optional(x)` of one of these builders is `optional: true` in its options; an `s.Array` takes `max: Number.MAX_SAFE_INTEGER` and an `s.Object` `extra: 'strip'`, which keeps what they did.
151
236
  export async function schemaBuilders(root: string, options: CheckOptions): Promise<CheckDiagnostic[]> {
152
237
  if (lintLevel('deprecated-schema-builders', options.lints) === 'allow')
153
238
  return []
@@ -155,33 +240,22 @@ export async function schemaBuilders(root: string, options: CheckOptions): Promi
155
240
  return scan(root, options, 'deprecated-schema-builders', NEEDLE, ({ parsed, report }) => {
156
241
  for (const { ast, base, text } of parsed) {
157
242
  const receivers = importsOf(ast, source => KAY.test(source), 's').locals
158
- const records = new Set([...importsOf(ast, source => KAY.test(source), 'action').locals, ...importsOf(ast, source => KAY.test(source), 'defineEnv').locals])
243
+ const records = importsOf(ast, source => KAY.test(source), 'defineEnv').locals
159
244
 
160
245
  if (receivers.size === 0)
161
246
  continue
162
247
 
163
- // What an `s.Optional(...)` or a record has taken over, so the call inside is not reported on its own.
248
+ // What an `s.Optional(...)` has taken over, so the call inside is not reported on its own.
164
249
  const taken = new Set<Node>()
165
- // The uses of `s` a fix takes away: an `s.Optional(` and the `s.Object(` of a record.
250
+ // The uses of `s` a fix takes away: an `s.Object(` of an env record.
166
251
  let dropped = 0
167
252
 
168
253
  walk(ast, (node) => {
169
254
  const call = builderCall(node, receivers)
170
255
 
171
256
  if (call === undefined) {
172
- // `action(s.Object({ ... }), ...)`
173
- if (node.type === 'CallExpression' && node.callee.type === 'Identifier' && records.has(node.callee.name)) {
174
- const [schema] = node.arguments
175
- const inner = schema === undefined ? undefined : builderCall(schema, receivers)
176
-
177
- if (schema && inner?.name === 'Object' && inner.node.arguments.length === 1 && inner.node.arguments[0]!.type === 'ObjectExpression') {
178
- const shape = inner.node.arguments[0]
179
-
180
- taken.add(schema)
181
- dropped++
182
- report(base + schema.start, base + schema.end, 'a plain record of fields is the object schema of an action or a defineEnv since 1.106, `s.Object` being the PascalCase builder it replaces; the old form works until 2.0', 'write the record of fields', [{ start: base + schema.start, end: base + shape.start, text: '' }, { start: base + shape.end, end: base + schema.end, text: '' }])
183
- }
184
- }
257
+ if (envRecord(node, records, receivers, base, taken, report))
258
+ dropped++
185
259
 
186
260
  return
187
261
  }
@@ -190,7 +264,8 @@ export async function schemaBuilders(root: string, options: CheckOptions): Promi
190
264
  const [inner, ...others] = call.node.arguments
191
265
  const wrapped = inner === undefined ? undefined : builderCall(inner, receivers)
192
266
  const known = wrapped && wrapped.name !== 'Public' && BUILDERS[wrapped.name] && !taken.has(inner!)
193
- const edit = known ? optionalEdit(wrapped, base) : undefined
267
+ const kept = known ? keptOptions(wrapped) : undefined
268
+ const edit = known && kept ? addOptions(wrapped, base, ['optional: true', ...kept]) : undefined
194
269
 
195
270
  // Anything but a builder of `s`, such as the `imageField()` of kay/content, has no `optional` option to write yet.
196
271
  if (!known)
@@ -203,7 +278,6 @@ export async function schemaBuilders(root: string, options: CheckOptions): Promi
203
278
  }
204
279
 
205
280
  taken.add(inner!)
206
- dropped++
207
281
  report(base + node.start, base + node.end, '`s.Optional(field)` is `optional: true` in the options of the field since 1.106, the same option on every builder; the old form works until 2.0', 'write `optional: true` in the field\'s options', [
208
282
  { start: base + node.start, end: base + inner!.start, text: '' },
209
283
  ...renames(wrapped, base),
@@ -216,13 +290,38 @@ export async function schemaBuilders(root: string, options: CheckOptions): Promi
216
290
 
217
291
  const builder = BUILDERS[call.name]
218
292
 
293
+ // A mapped array is no tuple, so `s.union(...)` of one is a type error: `s.enum(record)` when it is the keys of a record, else the app writes it.
294
+ if (call.name === 'Union' && !taken.has(node) && call.node.arguments[0]?.type !== 'ArrayExpression') {
295
+ const mapped = call.node.arguments.length === 1 ? mappedKeys(call.node.arguments[0]!, receivers) : undefined
296
+ const message = '`s.Union` is `s.union` since 1.106, and `s.union` takes its schemas written out as a list, so an array built at run time is a type error'
297
+ const receiver = (call.node.callee as { object: { name: string } }).object.name
298
+
299
+ if (mapped) {
300
+ taken.add(mapped.literal)
301
+ report(base + node.start, base + node.end, `${message}; \`s.enum(record)\` takes the keys of a record`, 'write `s.enum` with the record', [
302
+ { start: base + node.start, end: base + mapped.record.start, text: `${receiver}.enum(` },
303
+ { start: base + mapped.record.end, end: base + node.end, text: ')' },
304
+ ])
305
+ }
306
+ else {
307
+ report(base + node.start, base + node.end, `${message}; write the schemas out as a list, or \`s.enum\` for the keys of a record`, 'write the schemas as a list, or `s.enum`', null)
308
+ }
309
+
310
+ return
311
+ }
312
+
219
313
  if (builder && !taken.has(node)) {
220
- const object = call.name === 'Object' ? 'unknown keys are refused by `s.object` where kay reads the schema itself, where `s.Object` let them by; write `extra: \'strip\'` to keep the old way' : ''
314
+ const kept = keptOptions(call)
315
+ const edit = kept && kept.length > 0 ? addOptions(call, base, kept) : undefined
316
+ const object = call.name === 'Object' ? 'unknown keys are refused by `s.object` where kay reads the schema itself, where `s.Object` let them by, so the fix writes `extra: \'strip\'` to keep the old way' : ''
221
317
  const message = call.name === 'UnionKeys' || call.name === 'UnionEnum'
222
318
  ? '`s.enum()` takes the values, or a record whose keys are the values, since 1.106, in place of `s.UnionEnum` and `s.UnionKeys`; the old forms work until 2.0'
223
- : `\`s.${call.name}\` is \`s.${builder.name}\` since 1.106, kay's own lowercase builders with short options (\`min\`, \`max\`, \`optional\`) replacing the PascalCase ones of TypeBox${object ? `; ${object}` : ''}; the old form works until 2.0`
319
+ : `\`s.${call.name}\` is \`s.${builder.name}\` since 1.106, kay's own lowercase builders with short options (\`min\`, \`max\`, \`optional\`) replacing the PascalCase ones of TypeBox${object ? `; ${object}` : ''}; the old form works until 2.0${call.name === 'Array' ? '; `s.list` is at most 1,000 items where `s.Array` had no limit, so the fix writes `max: Number.MAX_SAFE_INTEGER`' : ''}`
320
+
321
+ // Without the option that keeps the old behaviour the rename would change it, so the fix is left to the app.
322
+ const keeps = kept !== undefined && (kept.length === 0 || edit !== undefined)
224
323
 
225
- report(base + node.start, base + node.end, message, `write \`s.${builder.name}\``, renames(call, base))
324
+ report(base + node.start, base + node.end, message, `write \`s.${builder.name}\``, keeps ? [...renames(call, base), ...edit ? [edit] : []] : null)
226
325
  }
227
326
  })
228
327
 
@@ -6,7 +6,8 @@ import { dirname, join } from 'node:path'
6
6
  import process from 'node:process'
7
7
  import { engines } from '../../package.json'
8
8
  import { renameProjectFiles } from '../check/renamed-packages'
9
- import { DEPRECATION_MINORS, minorAfter, minorOf, UPGRADE_FROM } from '../compiler/lints'
9
+ import { DEPRECATION_MINORS, UPGRADE_FROM } from '../compiler/lints'
10
+ import { minorAfter, minorOf } from '../compiler/minor'
10
11
  import { isKayPackage, RENAMED_IN, renamePackages } from '../package-names'
11
12
  import { done, formatOption, printDocument, printFailure, projectRoot } from './command'
12
13
  import { majorWarning } from './upgrade-majors'
@@ -1,5 +1,6 @@
1
1
  import type { Diagnostic } from './ast'
2
2
  import { positionAt } from './mapping'
3
+ import { REMOVED_LINTS } from './removed-lints'
3
4
 
4
5
  // What `lints.comments` in kay.config.ts asks of a `// kay-allow` comment: a comment that fails one of these allows nothing and is reported.
5
6
  export interface AllowRules {
@@ -14,6 +15,7 @@ export interface AllowRules {
14
15
  // A lint's name starts with a letter, so the `--` of a reason is never read as one: `// kay-allow a, b -- why`.
15
16
  const ALLOW_COMMENT = /\/\/[ \t]*(kay-allow(?:-file)?)[ \t]+(\w[\w-]*(?:[ \t]*,[ \t]*\w[\w-]*)*)([^\n]*)/g
16
17
  const LINT_NAME = /[\w-]+/g
18
+ const BLANK_END = /[ \t]*$/
17
19
  const REASON = /^[ \t]*--[ \t]*\S/
18
20
 
19
21
  export interface AllowComment {
@@ -22,8 +24,9 @@ export interface AllowComment {
22
24
  file: boolean
23
25
  // The line it allows: its own when it ends a line of code, the next when it is alone on its line; unused for a file comment.
24
26
  line: number
25
- // The offset of the comment's `//`.
27
+ // The offset of the comment's `//`, and of the end of what it holds.
26
28
  start: number
29
+ end: number
27
30
  // Whether a reason follows the names.
28
31
  reasoned: boolean
29
32
  }
@@ -35,7 +38,40 @@ export function allowComments(source: string): AllowComment[] {
35
38
  const names = Array.from(comment[2]!.matchAll(LINT_NAME), name => ({ name: name[0], start: listStart + name.index }))
36
39
 
37
40
  // A comment alone on its line allows the next one; one ending a line of code allows that line.
38
- return { names, file: comment[1] === 'kay-allow-file', line: source.slice(comment.index - column + 1, comment.index).trim() === '' ? line + 1 : line, start: comment.index, reasoned: REASON.test(comment[3]!) }
41
+ return { names, file: comment[1] === 'kay-allow-file', line: source.slice(comment.index - column + 1, comment.index).trim() === '' ? line + 1 : line, start: comment.index, end: comment.index + comment[0].length, reasoned: REASON.test(comment[3]!) }
42
+ })
43
+ }
44
+
45
+ // The names a comment holds that `known` does not know: a lint kay removed is a warning with a fix that drops the name, or the comment (its line when it stands alone) when it was the only one left, and any other name is the error `unknown-lint`.
46
+ export function unknownNames(comment: AllowComment, source: string, known: (name: string) => boolean, help: string): Diagnostic[] {
47
+ const unknown = comment.names.filter(({ name }) => !known(name))
48
+ const removed = new Set<string>(REMOVED_LINTS)
49
+ const lastKept = comment.names.findLastIndex(({ name }) => !removed.has(name))
50
+ const lineStart = source.lastIndexOf('\n', comment.start - 1) + 1
51
+ const whole = source.slice(lineStart, comment.start).trim() === ''
52
+ const after = comment.end + (source.startsWith('\r\n', comment.end) ? 2 : Number(source[comment.end] === '\n'))
53
+ const before = comment.start - (BLANK_END.exec(source.slice(lineStart, comment.start))?.[0].length ?? 0)
54
+ const last = comment.names.at(-1)!
55
+
56
+ return unknown.map(({ name, start }): Diagnostic => {
57
+ const end = start + name.length
58
+
59
+ if (!removed.has(name))
60
+ return { start, end, code: 'unknown-lint', message: `Unknown lint \`${name}\``, help, checkOnly: true }
61
+
62
+ const position = comment.names.findIndex(other => other.start === start)
63
+ const diagnostic: Diagnostic = { start, end, code: 'unknown-lint', severity: 'warning', message: `\`${name}\` is a lint kay has removed`, help: 'remove it from the comment: it allows nothing', checkOnly: true }
64
+
65
+ // The removed names after the last live one go in one edit, on the first of them, so no two edits overlap; the comment itself goes when no name is live.
66
+ if (position > lastKept && position !== lastKept + 1)
67
+ return diagnostic
68
+
69
+ const kept = comment.names[lastKept]
70
+ const dropped = whole ? { start: lineStart, end: after } : { start: before, end: comment.end }
71
+ const tail = kept ? { start: kept.start + kept.name.length, end: last.start + last.name.length } : dropped
72
+ const edit = position > lastKept ? tail : { start, end: comment.names[position + 1]!.start }
73
+
74
+ return { ...diagnostic, fixes: [{ title: kept || position < lastKept ? `remove \`${name}\`` : 'remove the comment', safe: true, edits: [{ ...edit, text: '' }] }] }
39
75
  })
40
76
  }
41
77