@forinda/kickjs-view 0.5.0 → 0.6.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 (42) hide show
  1. package/dist/{ast-bZ1jJ5-w.d.ts → ast-Pq3XT2Xi.d.ts} +163 -8
  2. package/dist/ast-Pq3XT2Xi.d.ts.map +1 -0
  3. package/dist/cli.d.ts +60 -2
  4. package/dist/cli.d.ts.map +1 -1
  5. package/dist/cli.js +5 -2
  6. package/dist/cli.js.map +1 -1
  7. package/dist/edge.d.ts +9 -5
  8. package/dist/edge.js +2 -2
  9. package/dist/exports-BsyGvnEU.js +17 -0
  10. package/dist/exports-BsyGvnEU.js.map +1 -0
  11. package/dist/file-loader.d.ts +2 -2
  12. package/dist/file-loader.js +3 -3
  13. package/dist/file-loader.js.map +1 -1
  14. package/dist/format-DBjtuDUY.js +18 -0
  15. package/dist/format-DBjtuDUY.js.map +1 -0
  16. package/dist/index.d.ts +13 -5
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +2 -2
  19. package/dist/index.js.map +1 -1
  20. package/dist/{project-XUrj8cl0.d.ts → project-DeGFHgGJ.d.ts} +24 -5
  21. package/dist/project-DeGFHgGJ.d.ts.map +1 -0
  22. package/dist/project-XTTCeVf3.js +12 -0
  23. package/dist/project-XTTCeVf3.js.map +1 -0
  24. package/dist/serve-Hc5UlJ56.d.ts +174 -0
  25. package/dist/serve-Hc5UlJ56.d.ts.map +1 -0
  26. package/dist/summary-EefMyOjo.js +20 -0
  27. package/dist/summary-EefMyOjo.js.map +1 -0
  28. package/dist/{views-_eQ9NTKn.d.ts → types-D-OIrXCW.d.ts} +190 -34
  29. package/dist/types-D-OIrXCW.d.ts.map +1 -0
  30. package/package.json +10 -10
  31. package/dist/ast-bZ1jJ5-w.d.ts.map +0 -1
  32. package/dist/exports-DNeTdtX4.js +0 -17
  33. package/dist/exports-DNeTdtX4.js.map +0 -1
  34. package/dist/format-Cig7Gm1h.js +0 -18
  35. package/dist/format-Cig7Gm1h.js.map +0 -1
  36. package/dist/project-XUrj8cl0.d.ts.map +0 -1
  37. package/dist/rolldown-runtime-BLRzqIEa.js +0 -11
  38. package/dist/serve-fHP-Eia9.d.ts +0 -97
  39. package/dist/serve-fHP-Eia9.d.ts.map +0 -1
  40. package/dist/template-DU9sjMgd.js +0 -20
  41. package/dist/template-DU9sjMgd.js.map +0 -1
  42. package/dist/views-_eQ9NTKn.d.ts.map +0 -1
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/strip-types.ts","../src/index.ts"],"sourcesContent":["/**\n * Node's TypeScript stripper for `<script client>` (Node 22.13+). Only the\n * Node entry registers it: an edge bundle carries plain JS from the build and\n * must not reference `node:module`.\n */\nimport * as nodeModule from 'node:module'\nimport { NO_STRIPPER } from './client-scripts'\n\nexport function stripTypes(code: string): string {\n const strip = (\n nodeModule as {\n stripTypeScriptTypes?: (code: string, options?: { mode?: 'strip' | 'transform' }) => string\n }\n ).stripTypeScriptTypes\n if (!strip) throw new Error(NO_STRIPPER)\n // `transform`, not the default `strip`: enums and namespaces compile, as\n // they do in a build.\n return strip(code, { mode: 'transform' })\n}\n","/**\n * The Node entry (Node, Bun, Deno): everything, plus the file loader as the\n * default template source. Edge runtimes resolve `./edge` instead.\n */\nimport { stripTypes } from './strip-types'\nimport { readFile } from 'node:fs/promises'\nimport { useClientFiles, useFileLoader, useStripTypes } from './views'\n\nuseFileLoader(() => import('./loaders/file'))\nuseStripTypes(stripTypes)\nuseClientFiles((url) => readFile(url))\n\nexport * from './exports'\nexport { format, type FormatOptions } from './format'\n"],"mappings":";;;;;;;;;;A,m6BAQA,SAAgB,WAAW,KAAsB,CAC/C,IAAM,MACJ,WAGA,qBACF,GAAI,CAAC,MAAO,MAAU,MAAM,WAAW,EAGvC,OAAO,MAAM,KAAM,CAAE,KAAM,WAAY,CAAC,CAC1C,CCVA,kBAAoB,OAAO,mBAAiB,EAC5C,cAAc,UAAU,EACxB,eAAgB,KAAQ,SAAS,GAAG,CAAC,E"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/strip-types.ts","../src/index.ts"],"sourcesContent":["/**\n * Node's TypeScript stripper for `<script client>` (Node 22.13+). Only the\n * Node entry registers it: an edge bundle carries plain JS from the build and\n * must not reference `node:module`.\n */\nimport * as nodeModule from 'node:module'\nimport { NO_STRIPPER } from './client-scripts'\n\nexport function stripTypes(code: string): string {\n const strip = (\n nodeModule as {\n stripTypeScriptTypes?: (code: string, options?: { mode?: 'strip' | 'transform' }) => string\n }\n ).stripTypeScriptTypes\n if (!strip) throw new Error(NO_STRIPPER)\n // `transform`, not the default `strip`: enums and namespaces compile, as\n // they do in a build.\n return strip(code, { mode: 'transform' })\n}\n","/**\n * The Node entry (Node, Bun, Deno): everything, plus the file loader as the\n * default template source. Edge runtimes resolve `./edge` instead.\n */\nimport { stripTypes } from './strip-types'\nimport { readFile } from 'node:fs/promises'\nimport { useClientFiles, useFileLoader, useStripTypes } from './views'\n\nuseFileLoader(() => import('./loaders/file'))\nuseStripTypes(stripTypes)\nuseClientFiles((url) => readFile(url))\n\nexport * from './exports'\nexport { format, type FormatOptions } from './format'\n"],"mappings":";;;;;;;;;;A,8gCAQA,SAAgB,WAAW,KAAsB,CAC/C,IAAM,MACJ,WAGA,qBACF,GAAI,CAAC,MAAO,MAAU,MAAM,WAAW,EAGvC,OAAO,MAAM,KAAM,CAAE,KAAM,WAAY,CAAC,CAC1C,CCVA,kBAAoB,OAAO,mBAAiB,EAC5C,cAAc,UAAU,EACxB,eAAgB,KAAQ,SAAS,GAAG,CAAC,E"}
@@ -1,5 +1,5 @@
1
1
 
2
- import { _ as TemplateAst } from "./ast-bZ1jJ5-w.js";
2
+ import { _ as TemplateAst } from "./ast-Pq3XT2Xi.js";
3
3
  /** Everything `check` knows about an app's views — built the same way by the runtime, the build and the editor. */
4
4
  interface Project {
5
5
  /** Template name (`users/show`, `components/user-card`) → its parsed source. */
@@ -21,9 +21,28 @@ interface Project {
21
21
  * `admin/users` the admin layout and everything else the main one.
22
22
  */
23
23
  declare function layoutResolver(layouts?: string | Record<string, string>): (page: string) => string | undefined;
24
- /** A valid template name, or `undefined`: `/`-joined segments, no `..`, no extension, no absolute path. */
24
+ /** `billing::invoices/show` → root `billing`, path `invoices/show`; an app template has no root. */
25
+ declare function splitName(name: string): {
26
+ root?: string;
27
+ path: string;
28
+ };
29
+ /** The full name of `path` in `root` (the app's own when `root` is undefined). */
30
+ declare const qualify: (root: string | undefined, path: string) => string;
31
+ /**
32
+ * A valid template name, or `undefined`: `/`-joined segments, no `..`, no
33
+ * extension, no absolute path; optionally after a view root (`billing::`).
34
+ */
25
35
  declare function templateName(name: string): string | undefined;
26
- /** `components/forms/text-field` → `forms-text-field`. */
36
+ /**
37
+ * What `ref`, written in template `from`, names: a qualified `ref` as is; an
38
+ * unqualified one in `from`'s own root when that has it, else the app's.
39
+ */
40
+ declare function resolveRef(from: string, ref: string, has: (name: string) => boolean): string;
41
+ /**
42
+ * `components/forms/text-field` → `forms-text-field`; a root's component
43
+ * starts with the root (`ui::components/button` → `ui-button`): custom
44
+ * element names are global in the browser.
45
+ */
27
46
  declare function componentTag(name: string, componentsDir: string): string;
28
- export { templateName as i, componentTag as n, layoutResolver as r, Project as t };
29
- //# sourceMappingURL=project-XUrj8cl0.d.ts.map
47
+ export { resolveRef as a, qualify as i, componentTag as n, splitName as o, layoutResolver as r, templateName as s, Project as t };
48
+ //# sourceMappingURL=project-DeGFHgGJ.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"project-DeGFHgGJ.d.ts","names":[],"sources":["../src/check/project.ts"],"mappings":";;;UAGiB;;EAEf,WAAW,YAAY;;EAEvB,OAAO;;EAEP,aAAa;;EAEb;;EAEA,mBAAmB;;EAEnB;;;;;;;iBAQc,eACd,mBAAmB,0BACjB;;iBAwBY,UAAU;EAAiB;EAAe;;;cAM7C,UAAO,0BAA4B;;;;;iBAOhC,aAAa;;;;;iBAab,WAAW,cAAc,aAAa,MAAM;;;;;;iBAa5C,aAAa,cAAc"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @forinda/kickjs-view v0.6.0
3
+ *
4
+ * Copyright (c) Felix Orinda
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
8
+ *
9
+ * @license MIT
10
+ */
11
+ function layoutResolver(layouts){if(layouts===void 0)return()=>void 0;if(typeof layouts==`string`)return()=>layouts;let prefixes=Object.keys(layouts).toSorted((a,b)=>b.length-a.length);return page=>{let hit=prefixes.find(p=>p===``||page===p||page.startsWith(`${p}/`));return hit===void 0?void 0:layouts[hit]}}function configuredLayouts(project){let names=/* @__PURE__ */ new Set;if(typeof project.layouts==`string`)names.add(project.layouts);else if(project.layouts)for(let v of Object.values(project.layouts))names.add(v);return project.baseLayout&&names.add(project.baseLayout),names}const SEGMENT=/^[A-Za-z0-9_-]+$/,ROOT_NAME=/^[a-z][a-z0-9-]*$/;function splitName(name){let at=name.indexOf(`::`);return at<0?{path:name}:{root:name.slice(0,at),path:name.slice(at+2)}}const qualify=(root,path)=>root===void 0?path:`${root}::${path}`;function templateName(name){if(typeof name!=`string`||!name)return;let{root,path}=splitName(name);if((root===void 0||ROOT_NAME.test(root))&&path)return path.split(`/`).every(s=>SEGMENT.test(s))?name:void 0}function resolveRef(from,ref,has){if(ref.includes(`::`))return ref;let{root}=splitName(from);if(root===void 0)return ref;let own=qualify(root,ref);return has(own)?own:ref}function componentTag(name,componentsDir){let{root,path}=splitName(name),tag=path.slice(componentsDir.length+1).split(`/`).join(`-`).toLowerCase();return root===void 0?tag:`${root}-${tag}`}const isComponent=(name,componentsDir)=>splitName(name).path.startsWith(`${componentsDir}/`);export{layoutResolver as a,splitName as c,isComponent as i,templateName as l,componentTag as n,qualify as o,configuredLayouts as r,resolveRef as s,ROOT_NAME as t};
12
+ //# sourceMappingURL=project-XTTCeVf3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"project-XTTCeVf3.js","names":[],"sources":["../src/check/project.ts"],"sourcesContent":["import type { TemplateAst } from '../ast'\n\n/** Everything `check` knows about an app's views — built the same way by the runtime, the build and the editor. */\nexport interface Project {\n /** Template name (`users/show`, `components/user-card`) → its parsed source. */\n templates: Map<string, TemplateAst>\n /** Pipe names: the built-ins and the app's. */\n pipes: Set<string>\n /** The app's validator names, from `validators.ts` (the built-ins are always known). */\n validators?: Set<string>\n /** Folder (inside the views folder) holding components. Default `components`. */\n componentsDir: string\n /** A page's layout when it declares none: one name, or folder prefix → layout. */\n layouts?: string | Record<string, string>\n /** The shell around every page's outermost layout. */\n baseLayout?: string\n}\n\n/**\n * The layout for a page that declares none. A map's longest matching folder\n * prefix wins: `{ admin: 'layouts/admin', '': 'layouts/main' }` gives\n * `admin/users` the admin layout and everything else the main one.\n */\nexport function layoutResolver(\n layouts?: string | Record<string, string>,\n): (page: string) => string | undefined {\n if (layouts === undefined) return () => undefined\n if (typeof layouts === 'string') return () => layouts\n const prefixes = Object.keys(layouts).toSorted((a, b) => b.length - a.length)\n return (page) => {\n const hit = prefixes.find((p) => p === '' || page === p || page.startsWith(`${p}/`))\n return hit === undefined ? undefined : layouts[hit]\n }\n}\n\n/** Templates that are layouts by configuration — they never get a mapped layout themselves. */\nexport function configuredLayouts(project: Project): Set<string> {\n const names = new Set<string>()\n if (typeof project.layouts === 'string') names.add(project.layouts)\n else if (project.layouts) for (const v of Object.values(project.layouts)) names.add(v)\n if (project.baseLayout) names.add(project.baseLayout)\n return names\n}\n\nconst SEGMENT = /^[A-Za-z0-9_-]+$/\n/** A view root's name: `billing`, `acme-ui`. */\nexport const ROOT_NAME = /^[a-z][a-z0-9-]*$/\n\n/** `billing::invoices/show` → root `billing`, path `invoices/show`; an app template has no root. */\nexport function splitName(name: string): { root?: string; path: string } {\n const at = name.indexOf('::')\n return at < 0 ? { path: name } : { root: name.slice(0, at), path: name.slice(at + 2) }\n}\n\n/** The full name of `path` in `root` (the app's own when `root` is undefined). */\nexport const qualify = (root: string | undefined, path: string): string =>\n root === undefined ? path : `${root}::${path}`\n\n/**\n * A valid template name, or `undefined`: `/`-joined segments, no `..`, no\n * extension, no absolute path; optionally after a view root (`billing::`).\n */\nexport function templateName(name: string): string | undefined {\n if (typeof name !== 'string' || !name) return undefined\n const { root, path } = splitName(name)\n if (root !== undefined && !ROOT_NAME.test(root)) return undefined\n if (!path) return undefined\n const segments = path.split('/')\n return segments.every((s) => SEGMENT.test(s)) ? name : undefined\n}\n\n/**\n * What `ref`, written in template `from`, names: a qualified `ref` as is; an\n * unqualified one in `from`'s own root when that has it, else the app's.\n */\nexport function resolveRef(from: string, ref: string, has: (name: string) => boolean): string {\n if (ref.includes('::')) return ref\n const { root } = splitName(from)\n if (root === undefined) return ref\n const own = qualify(root, ref)\n return has(own) ? own : ref\n}\n\n/**\n * `components/forms/text-field` → `forms-text-field`; a root's component\n * starts with the root (`ui::components/button` → `ui-button`): custom\n * element names are global in the browser.\n */\nexport function componentTag(name: string, componentsDir: string): string {\n const { root, path } = splitName(name)\n const tag = path\n .slice(componentsDir.length + 1)\n .split('/')\n .join('-')\n .toLowerCase()\n return root === undefined ? tag : `${root}-${tag}`\n}\n\nexport const isComponent = (name: string, componentsDir: string): boolean =>\n splitName(name).path.startsWith(`${componentsDir}/`)\n"],"mappings":";;;;;;;;;;AAuBA,SAAgB,eACd,QACsC,CACtC,GAAI,UAAY,IAAA,GAAW,UAAa,IAAA,GACxC,GAAI,OAAO,SAAY,SAAU,UAAa,QAC9C,IAAM,SAAW,OAAO,KAAK,OAAO,CAAC,CAAC,UAAU,EAAG,IAAM,EAAE,OAAS,EAAE,MAAM,EAC5E,MAAQ,OAAS,CACf,IAAM,IAAM,SAAS,KAAM,GAAM,IAAM,IAAM,OAAS,GAAK,KAAK,WAAW,GAAG,EAAE,EAAE,CAAC,EACnF,OAAO,MAAQ,IAAA,GAAY,IAAA,GAAY,QAAQ,IACjD,CACF,CAGA,SAAgB,kBAAkB,QAA+B,CAC/D,IAAM,sBAAQ,IAAI,IAClB,GAAI,OAAO,QAAQ,SAAY,SAAU,MAAM,IAAI,QAAQ,OAAO,OAC7D,GAAI,QAAQ,QAAS,IAAK,IAAM,KAAK,OAAO,OAAO,QAAQ,OAAO,EAAG,MAAM,IAAI,CAAC,EAErF,OADI,QAAQ,YAAY,MAAM,IAAI,QAAQ,UAAU,EAC7C,KACT,CAEA,MAAM,QAAU,mBAEH,UAAY,oBAGzB,SAAgB,UAAU,KAA+C,CACvE,IAAM,GAAK,KAAK,QAAQ,IAAI,EAC5B,OAAO,GAAK,EAAI,CAAE,KAAM,IAAK,EAAI,CAAE,KAAM,KAAK,MAAM,EAAG,EAAE,EAAG,KAAM,KAAK,MAAM,GAAK,CAAC,CAAE,CACvF,CAGA,MAAa,SAAW,KAA0B,OAChD,OAAS,IAAA,GAAY,KAAO,GAAG,KAAK,IAAI,OAM1C,SAAgB,aAAa,KAAkC,CAC7D,GAAI,OAAO,MAAS,UAAY,CAAC,KAAM,OACvC,GAAM,CAAE,KAAM,MAAS,UAAU,IAAI,EACrC,IAAI,OAAS,IAAA,IAAc,UAAU,KAAK,IAAI,IACzC,KAEL,OADiB,KAAK,MAAM,GACd,CAAC,CAAC,MAAO,GAAM,QAAQ,KAAK,CAAC,CAAC,EAAI,KAAO,IAAA,EACzD,CAMA,SAAgB,WAAW,KAAc,IAAa,IAAwC,CAC5F,GAAI,IAAI,SAAS,IAAI,EAAG,OAAO,IAC/B,GAAM,CAAE,MAAS,UAAU,IAAI,EAC/B,GAAI,OAAS,IAAA,GAAW,OAAO,IAC/B,IAAM,IAAM,QAAQ,KAAM,GAAG,EAC7B,OAAO,IAAI,GAAG,EAAI,IAAM,GAC1B,CAOA,SAAgB,aAAa,KAAc,cAA+B,CACxE,GAAM,CAAE,KAAM,MAAS,UAAU,IAAI,EAC/B,IAAM,KACT,MAAM,cAAc,OAAS,CAAC,CAAC,CAC/B,MAAM,GAAG,CAAC,CACV,KAAK,GAAG,CAAC,CACT,YAAY,EACf,OAAO,OAAS,IAAA,GAAY,IAAM,GAAG,KAAK,GAAG,KAC/C,CAEA,MAAa,aAAe,KAAc,gBACxC,UAAU,IAAI,CAAC,CAAC,KAAK,WAAW,GAAG,cAAc,EAAE,E"}
@@ -0,0 +1,174 @@
1
+
2
+ import { _ as TemplateAst, s as CheckedTemplate, u as Expr, v as Diagnostic, y as Pos } from "./ast-Pq3XT2Xi.js";
3
+ import { t as Project } from "./project-DeGFHgGJ.js";
4
+ import { _ as Views, y as ViewsOptions } from "./types-D-OIrXCW.js";
5
+ /** Property names a template never reads, even through `[...]` (checked at runtime). */
6
+ declare const FORBIDDEN_NAMES: ReadonlySet<string>;
7
+ /**
8
+ * Parse one expression. `base` is where `src` starts in the template, so
9
+ * positions in diagnostics and spans point into the template file.
10
+ */
11
+ declare function parseExpression(src: string, file: string, base: Pos): {
12
+ expr?: Expr;
13
+ diagnostics: Diagnostic[];
14
+ };
15
+ /** What `parse` returns: the template AST and any diagnostics. */
16
+ interface ParseResult {
17
+ ast: TemplateAst;
18
+ diagnostics: Diagnostic[];
19
+ }
20
+ /** Parse a `.kick` source. A leading BOM is dropped; positions refer to the rest. */
21
+ declare function parse(source: string, file: string): ParseResult;
22
+ /** What `check` returns: `template` is absent when any diagnostic is an error. */
23
+ interface CheckResult {
24
+ template?: CheckedTemplate;
25
+ diagnostics: Diagnostic[];
26
+ }
27
+ /** Check one template of `project` by name. */
28
+ declare function check(name: string, project: Project): CheckResult;
29
+ /**
30
+ * Attributes whose value is a URL a browser may navigate to, load or run.
31
+ * Their assembled value is scheme-checked when rendered.
32
+ */
33
+ declare const URL_ATTRS: ReadonlySet<string>;
34
+ /** Whether `attr` on `tag` holds a URL, so its value is scheme-checked when rendered (`data` counts only on `<object>`). */
35
+ declare function isUrlAttr(tag: string, attr: string): boolean;
36
+ /** The shape of a value, as far as the template's reads reveal it. */
37
+ type Shape = {
38
+ k: 'unknown';
39
+ } | {
40
+ k: 'object';
41
+ props: Record<string, Field>;
42
+ } | {
43
+ k: 'list';
44
+ item: Shape;
45
+ } | {
46
+ k: 'pairs';
47
+ value: Shape;
48
+ };
49
+ /** A name or property: its shape, and whether it may be missing / null. */
50
+ interface Field {
51
+ shape: Shape;
52
+ optional: boolean;
53
+ nullable: boolean;
54
+ }
55
+ /** What a page reads, declares and imports. */
56
+ interface DataSummary {
57
+ fields: Record<string, Field>;
58
+ /** `@input name: Type` in the page: its type, and optional when it has a default. */
59
+ declared: Record<string, {
60
+ type?: string;
61
+ optional: boolean;
62
+ }>;
63
+ /** `@input name = value` defaults. */
64
+ defaults?: Record<string, unknown>;
65
+ /** `@import type …` lines, as written. */
66
+ imports: string[];
67
+ /**
68
+ * Per `@fragment`: its needs (names bound around it — the caller passes
69
+ * them, `share()` doesn't count) and the page data it reads.
70
+ */
71
+ fragments: Record<string, {
72
+ needs: Record<string, Field>;
73
+ reads: Record<string, Field>;
74
+ }>;
75
+ /** The page's `@layout`: `null` for none, absent when it declares none. */
76
+ layout?: string | null;
77
+ }
78
+ /** Two reads of one field: required if either requires it, shapes merged. */
79
+ declare function merge(a: Field, b: Field): Field;
80
+ /** `from`'s fields merged into `into` (a layout's reads into its page's). */
81
+ declare function mergeSummary(into: DataSummary, from: DataSummary): DataSummary;
82
+ /** The names a pipes file exports. */
83
+ declare function readPipeExports(source: string, file: string): {
84
+ names: string[];
85
+ diagnostics: Diagnostic[];
86
+ };
87
+ /** The component tag the app's validators are served under: `kick-validators.<hash>.js`. */
88
+ declare const VALIDATORS_TAG = "kick-validators";
89
+ /** The built-in validator names, for editors. */
90
+ declare const BUILTIN_VALIDATORS: string[];
91
+ /** The validators `validators.ts` exports, refusing the built-in names. */
92
+ declare function readValidatorExports(source: string, file: string): {
93
+ names: string[];
94
+ diagnostics: Diagnostic[];
95
+ };
96
+ /**
97
+ * Appended to `validators.ts` when it's served without a bundler: the module
98
+ * imports its own namespace and registers every export for the validator script.
99
+ */
100
+ declare const VALIDATORS_REGISTER = "\nimport(import.meta.url).then((m) => Object.assign((globalThis.__kickValidators ??= {}), m))\n";
101
+ type Next = (err?: unknown) => void;
102
+ /**
103
+ * The web fetch entry's middleware (`createWebApp({ middlewares: [viewsMiddleware(views)] })`),
104
+ * which takes `(ctx, next)` middleware rather than adapters.
105
+ */
106
+ declare function viewsMiddleware(views: Views): (ctx: {
107
+ req: object;
108
+ }, next: () => unknown) => unknown;
109
+ /** Options for `KickView`: the `createViews` options, or a views instance to reuse. */
110
+ interface KickViewOptions extends ViewsOptions {
111
+ /** A views instance to use — share it with error pages and emails. */
112
+ views?: Views;
113
+ }
114
+ /**
115
+ * Adds KickJS views to the app: `ctx.render(name, data)` renders
116
+ * `src/views/<name>.kick` on every runtime. Pass `...kickViews` from
117
+ * `virtual:kick-views` so a build renders from its bundle; without a bundle
118
+ * or `loader`, templates are read from disk (Node only).
119
+ *
120
+ * @example
121
+ * ```ts
122
+ * import kickViews from 'virtual:kick-views'
123
+ *
124
+ * bootstrap({ modules, adapters: [KickView({ ...kickViews })] })
125
+ * // in a controller
126
+ * await ctx.render('users/show', { user })
127
+ * ```
128
+ *
129
+ * @see https://kickjs.app/guide/views
130
+ */
131
+ declare function KickView(options?: KickViewOptions): {
132
+ name: string;
133
+ views: Views;
134
+ middleware: () => {
135
+ handler: (req: object, res: unknown, next: Next) => void;
136
+ phase: 'beforeGlobal';
137
+ }[];
138
+ };
139
+ /** One entry of a Vite build manifest. */
140
+ interface ViteManifestChunk {
141
+ file: string;
142
+ css?: string[];
143
+ imports?: string[];
144
+ isEntry?: boolean;
145
+ }
146
+ /** A Vite build manifest (`.vite/manifest.json`), keyed by source path. */
147
+ type ViteManifest = Record<string, ViteManifestChunk>;
148
+ /** Dev (Vite's dev server under `base`) or production (the build's manifest). */
149
+ type AssetsMode = {
150
+ dev: true;
151
+ base: string;
152
+ } | {
153
+ dev: false;
154
+ manifest: ViteManifest;
155
+ base: string;
156
+ };
157
+ /**
158
+ * The `<script>` and `<link>` tags for a Vite entry: the Vite client and the entry module in dev,
159
+ * the hashed script, stylesheets and module preloads from the manifest in production.
160
+ * Throws when the entry isn't in the manifest.
161
+ *
162
+ * @see https://kickjs.app/guide/views/assets
163
+ */
164
+ declare function assetTags(entry: string, mode: AssetsMode, nonce?: string): string;
165
+ /**
166
+ * A component script's response, or `undefined` for anything else:
167
+ *
168
+ * ```ts
169
+ * export default { fetch: async (req) => (await clientScriptResponse(views, req)) ?? web.fetch(req) }
170
+ * ```
171
+ */
172
+ declare function clientScriptResponse(views: Views, request: Request): Promise<Response | undefined>;
173
+ export { ParseResult as C, parseExpression as E, check as S, FORBIDDEN_NAMES as T, merge as _, assetTags as a, isUrlAttr as b, viewsMiddleware as c, VALIDATORS_TAG as d, readValidatorExports as f, Shape as g, Field as h, ViteManifestChunk as i, VALIDATORS_REGISTER as l, DataSummary as m, AssetsMode as n, KickView as o, readPipeExports as p, ViteManifest as r, KickViewOptions as s, clientScriptResponse as t, BUILTIN_VALIDATORS as u, mergeSummary as v, parse as w, CheckResult as x, URL_ATTRS as y };
174
+ //# sourceMappingURL=serve-Hc5UlJ56.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serve-Hc5UlJ56.d.ts","names":[],"sources":["../src/parse/expression.ts","../src/parse/template.ts","../src/check/check.ts","../src/urls.ts","../src/check/summary.ts","../src/pipes/read-exports.ts","../src/validators.ts","../src/validate-runtime.ts","../src/adapter.ts","../src/assets.ts","../src/serve.ts"],"mappings":";;;;;cAWa,iBAAiB;;;;;iBA+Yd,gBACd,aACA,cACA,MAAM;EACH,OAAO;EAAM,aAAa;;;UCvYd;EACf,KAAK;EACL,aAAa;;;iBA6jCC,MAAM,gBAAgB,eAAe;;UC5iCpC;EACf,WAAW;EACX,aAAa;;;iBAs0CC,MAAM,cAAc,SAAS,UAAU;;;;;cC92C1C,WAAW;;iBAcR,UAAU,aAAa;;KCL3B;EACN;;EACA;EAAa,OAAO,eAAe;;EACnC;EAAW,MAAM;;EACjB;EAAY,OAAO;;;UAGR;EACf,OAAO;EACP;EACA;;;UAIe;EACf,QAAQ,eAAe;;EAEvB,UAAU;IAAiB;IAAe;;;EAE1C,WAAW;;EAEX;;;;;EAKA,WAAW;IAAiB,OAAO,eAAe;IAAQ,OAAO,eAAe;;;EAEhF;;;iBA8qBc,MAAM,GAAG,OAAO,GAAG,QAAQ;;iBAU3B,aAAa,MAAM,aAAa,MAAM,cAAc;;iBClpBpD,gBACd,gBACA;EACG;EAAiB,aAAa;;;cCrEtB;;cAeA;;iBAKG,qBACd,gBACA;EACG;EAAiB,aAAa;;;;;;cC0ItB;KCnKR,QAAQ;;;;;iBAwEG,gBACd,OAAO,SACL;EAAO;GAAe;;UAST,wBAAwB;;EAEvC,QAAQ;;;;;;;;;;;;;;;;;;;iBA6BM,SAAS,UAAS;;;;IAvEM,UAAA,aAAM,cAAc,MAAQ;IAgF3B;;;;UC9HxB;EACf;EACA;EACA;EACA;;;KAIU,eAAe,eAAe;;KAG9B;EACN;EAAW;;EACX;EAAY,UAAU;EAAc;;;;;;;;;iBAS1B,UAAU,eAAe,MAAM,YAAY;;;;;;;;iBCOrC,qBACpB,OAAO,OACP,SAAS,UACR,QAAQ"}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * @forinda/kickjs-view v0.6.0
3
+ *
4
+ * Copyright (c) Felix Orinda
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
8
+ *
9
+ * @license MIT
10
+ */
11
+ import{a as layoutResolver,i as isComponent,l as templateName,n as componentTag,r as configuredLayouts,s as resolveRef}from"./project-XTTCeVf3.js";const FORM_STATE_KEYS={flash:`__inertia_flash`,errors:`__inertia_errors`,old:`__kick_old`,previous:`__inertia_previous`},SECRET_FIELD=/pass(word|code)?|passwd|pwd|secret|token|card|cvv|cvc|csrf|otp|(^|[_-])pin($|[_-])/i;function rememberPage(ctx,layout){if(layout===!1)return;let c=ctx,data=c?.session?.data,method=String(c?.req?.method??``).toUpperCase(),url=c?.req?.originalUrl??c?.req?.url;data&&method===`GET`&&typeof url==`string`&&(data[FORM_STATE_KEYS.previous]=url)}const FORM_GLOBALS=/* @__PURE__ */ new Set([`$errors`,`$old`,`$flash`]),emptyFormState=()=>({$errors:{},$old:{},$flash:{}});function takeFormState(ctx){let data=ctx?.session?.data,out={};if(!data)return out;let take=(name,key)=>{if(data[key]===void 0)return;let value=data[key];delete data[key],out[name]=value&&typeof value==`object`?value:{}};return take(`$errors`,FORM_STATE_KEYS.errors),take(`$old`,FORM_STATE_KEYS.old),take(`$flash`,FORM_STATE_KEYS.flash),out}const AST_FORMAT_VERSION=3;function advance(base,text,upTo){let{line,column}=base;for(let i=0;i<upTo;i++){let c=text.charCodeAt(i);c===10?(line++,column=1):c===13?text.charCodeAt(i+1)!==10&&(line++,column=1):column++}return{offset:base.offset+upTo,line,column}}const START={offset:0,line:1,column:1},positionAt=(source,offset)=>advance(START,source,offset),error=(file,span,message)=>({file,span,message,severity:`error`}),warning=(file,span,message)=>({file,span,message,severity:`warning`}),FORBIDDEN_NAMES=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`,`__defineGetter__`,`__defineSetter__`,`__lookupGetter__`,`__lookupSetter__`]),KEYWORDS$1={new:`constructing objects`,typeof:"`typeof`",instanceof:"`instanceof`",in:"`in`",delete:"`delete`",void:"`void`",function:`functions`,class:`classes`,await:"`await`",yield:"`yield`",this:"`this`"},FORBIDDEN_PUNCT={"(":`calls`,"=":`assignment`,"=>":`functions`,"*":"`*`","/":"`/`","%":"`%`","`":`template literals`,"{":`object literals`,"}":"`}`","...":`spread`,";":"`;`",",":"`,`","&":"`&`","^":"`^`","~":"`~`"},PUNCT=/* @__PURE__ */ "=== !== ... ?. ?? == != <= >= && || => ? : | ! < > + - . [ ] ( ) = * / % ` { } ; , & ^ ~".split(` `);var Fail=class extends Error{start;end;constructor(start,end,message){super(message),this.start=start,this.end=end}};const ESCAPES={"\\":`\\`,"'":`'`,'"':`"`,n:`
12
+ `,t:` `,r:`\r`};function tokenize(src){let out=[],i=0;for(;i<src.length;){let c=src[i];if(/\s/.test(c)){i++;continue}let start=i;if(/[A-Za-z_$]/.test(c)){for(;i<src.length&&/[\w$]/.test(src[i]);)i++;out.push({t:`ident`,v:src.slice(start,i),start,end:i});continue}if(/\d/.test(c)){for(;i<src.length&&/\d/.test(src[i]);)i++;if(src[i]===`.`&&/\d/.test(src[i+1]??``))for(i++;i<src.length&&/\d/.test(src[i]);)i++;out.push({t:`num`,v:Number(src.slice(start,i)),start,end:i});continue}if(c===`'`||c===`"`){let v=``;for(i++;i<src.length&&src[i]!==c;)if(src[i]===`\\`){let e=src[i+1]??``;if(e===`u`){let hex=src.slice(i+2,i+6);if(!/^[0-9a-fA-F]{4}$/.test(hex))throw new Fail(i,i+2,`a \\u escape needs four hex digits`);v+=String.fromCharCode(parseInt(hex,16)),i+=6;continue}if(!(e in ESCAPES))throw new Fail(i,i+2,`unknown escape \\${e}`);v+=ESCAPES[e],i+=2}else v+=src[i],i++;if(i>=src.length)throw new Fail(start,i,`unterminated string`);i++,out.push({t:`str`,v,start,end:i});continue}let p=PUNCT.find(op=>src.startsWith(op,i));if(!p)throw new Fail(i,i+1,`unexpected character '${c}'`);i+=p.length,out.push({t:`punct`,v:p,start,end:i})}return out.push({t:`eof`,v:``,start:src.length,end:src.length}),out}const BP={pipe:1,ternary:2,nullish:3,or:4,and:5,eq:6,rel:7,add:8,unary:9},BINARY={"??":[BP.nullish,`logical`],"||":[BP.or,`logical`],"&&":[BP.and,`logical`],"==":[BP.eq,`binary`],"!=":[BP.eq,`binary`],"===":[BP.eq,`binary`],"!==":[BP.eq,`binary`],"<":[BP.rel,`binary`],">":[BP.rel,`binary`],"<=":[BP.rel,`binary`],">=":[BP.rel,`binary`],"+":[BP.add,`binary`],"-":[BP.add,`binary`]};var Parser=class{src;base;tokens;i=0;constructor(src,base,tokens){this.src=src,this.base=base,this.tokens=tokens}peek(){return this.tokens[this.i]}next(){return this.tokens[this.i++]}span(start,end){return{start:advance(this.base,this.src,start),end:advance(this.base,this.src,end)}}isPunct(v){let t=this.peek();return t.t===`punct`&&t.v===v}expect(v){let t=this.peek();if(t.t!==`punct`||t.v!==v)throw new Fail(t.start,t.end,t.t===`eof`?`expected '${v}'`:`expected '${v}', found '${this.text(t)}'`);return this.next()}text(t){return this.src.slice(t.start,t.end)}forbidden(t){let what=t.t===`punct`?FORBIDDEN_PUNCT[t.v]:KEYWORDS$1[t.v];throw new Fail(t.start,t.end,`${what??`'${this.text(t)}'`} aren't allowed in templates`)}parseAll(){let e=this.expr(0),t=this.peek();if(t.t!==`eof`)throw(t.t===`punct`&&Object.hasOwn(FORBIDDEN_PUNCT,t.v)||t.t===`ident`&&Object.hasOwn(KEYWORDS$1,t.v))&&this.forbidden(t),new Fail(t.start,t.end,`unexpected '${this.text(t)}'`);return e}expr(min){let left=this.prefix();for(;;){let t=this.peek();if(t.t===`ident`&&(t.v===`in`||t.v===`instanceof`)&&this.forbidden(t),t.t!==`punct`)break;if(t.v===`|`){if(min>BP.pipe)break;this.next();let name=this.next();if(name.t!==`ident`)throw new Fail(name.start,name.end,`expected a pipe name after |`);let args=[];for(;this.isPunct(`:`);)if(this.next(),args.push(this.expr(BP.nullish)),this.isPunct(`?`)){let q=this.peek();throw new Fail(q.start,q.end,`wrap a conditional pipe argument in parentheses`)}left={kind:`pipe`,input:left,name:name.v,args,span:this.join(left,name.end)};continue}if(t.v===`?`){if(min>BP.ternary)break;this.next();let whenTrue=this.expr(BP.ternary);this.expect(`:`);let whenFalse=this.expr(BP.ternary);left={kind:`conditional`,test:left,whenTrue,whenFalse,span:this.joinExpr(left,whenFalse)};continue}let bin=BINARY[t.v];if(bin){let[bp,kind]=bin;if(bp<min)break;this.next();let right=this.expr(bp+1);left={kind,op:t.v,left,right,span:this.joinExpr(left,right)}}else{Object.hasOwn(FORBIDDEN_PUNCT,t.v)&&this.forbidden(t);break}}return left}join(left,end){return{start:left.span.start,end:advance(this.base,this.src,end)}}joinExpr(left,right){return{start:left.span.start,end:right.span.end}}prefix(){let t=this.next();switch(t.t){case`num`:return{kind:`literal`,value:t.v,span:this.span(t.start,t.end)};case`str`:return{kind:`literal`,value:t.v,span:this.span(t.start,t.end)};case`ident`:if(Object.hasOwn(KEYWORDS$1,t.v)&&this.forbidden(t),t.v===`true`||t.v===`false`)return{kind:`literal`,value:t.v===`true`,span:this.span(t.start,t.end)};if(t.v===`null`)return{kind:`literal`,value:null,span:this.span(t.start,t.end)};if(FORBIDDEN_NAMES.has(t.v))throw new Fail(t.start,t.end,`'${t.v}' is not allowed in templates`);return this.path(t);case`punct`:if(t.v===`!`||t.v===`-`){let arg=this.expr(BP.unary);return{kind:`unary`,op:t.v,arg,span:{start:this.span(t.start,t.end).start,end:arg.span.end}}}if(t.v===`(`){let e=this.expr(0);if(this.expect(`)`),this.isPunct(`.`)||this.isPunct(`[`)||this.isPunct(`?.`)){let m=this.peek();throw new Fail(m.start,m.end,`property access needs a name in front: (…).x is not allowed`)}return e}throw t.v===`[`?new Fail(t.start,t.end,`array literals aren't allowed in templates`):(Object.hasOwn(FORBIDDEN_PUNCT,t.v)&&this.forbidden(t),new Fail(t.start,t.end,`unexpected '${t.v}'`));case`eof`:throw new Fail(t.start,t.end,`expected an expression`)}}path(root){let segments=[],end=root.end;for(;;){let t=this.peek();if(t.t!==`punct`)break;if(t.v===`.`||t.v===`?.`){this.next();let optional=t.v===`?.`;if(optional&&this.isPunct(`[`)){this.next();let computed=this.expr(0);end=this.expect(`]`).end,segments.push({computed,optional});continue}optional&&this.isPunct(`(`)&&this.forbidden(this.peek());let name=this.next();if(name.t!==`ident`)throw new Fail(name.start,name.end,`expected a property name`);if(FORBIDDEN_NAMES.has(name.v))throw new Fail(name.start,name.end,`'${name.v}' is not allowed in templates`);segments.push({name:name.v,optional}),end=name.end}else if(t.v===`[`){this.next();let computed=this.expr(0);end=this.expect(`]`).end,segments.push({computed,optional:!1})}else{t.v===`(`&&this.forbidden(t);break}}return{kind:`path`,root:root.v,segments,span:this.span(root.start,end)}}};function parseExpression(src,file,base){try{return{expr:new Parser(src,base,tokenize(src)).parseAll(),diagnostics:[]}}catch(err){if(!(err instanceof Fail))throw err;let span={start:advance(base,src,err.start),end:advance(base,src,err.end)};return{diagnostics:[error(file,span,err.message)]}}}const URL_ATTRS=/* @__PURE__ */ new Set([`href`,`src`,`action`,`formaction`,`poster`,`cite`,`background`,`ping`,`xlink:href`,`srcset`]);function isUrlAttr(tag,attr){let name=attr.toLowerCase();return URL_ATTRS.has(name)||name===`data`&&tag.toLowerCase()===`object`}var SafeHtml=class{html;constructor(html){this.html=html}toString(){return this.html}};function read(obj,key){if(obj==null)return;let k=typeof key==`number`||typeof key==`symbol`?key:String(key);if(typeof k==`string`&&FORBIDDEN_NAMES.has(k))return;let value=obj[k];return typeof value==`function`?void 0:value}const HTML_ESCAPES={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`},escapeHtml=s=>s.replace(/[&<>"']/g,c=>HTML_ESCAPES[c]),SAFE_SCHEMES=/* @__PURE__ */ new Set([`http`,`https`,`mailto`,`tel`]);function sanitizeUrl(value){let normalised=value.replace(/[\u0000- \u007F]/g,``),m=/^([a-z][a-z0-9+.-]*):/i.exec(normalised);return m?SAFE_SCHEMES.has(m[1].toLowerCase())?value:`#`:value}function sanitizeSrcset(value){return value.split(`,`).map(candidate=>{let m=/^(\s*)(\S+)([\s\S]*)$/.exec(candidate);return m?`${m[1]}${sanitizeUrl(m[2])}${m[3]}`:candidate}).join(`,`)}const JSON_ESCAPES={"<":`\\u003c`,">":`\\u003e`,"&":`\\u0026`,"\u2028":`\\u2028`,"\u2029":`\\u2029`},escapeJsonForScript=json=>json.replace(/[<>&\u2028\u2029]/g,c=>JSON_ESCAPES[c]);function safeStyleValue(v){return/[;{}\\"'<]|\/\*|url\s*\(|expression\s*\(/i.test(v)?void 0:v}const BUILTIN_PIPES=[`uppercase`,`lowercase`,`titlecase`,`json`,`slice`,`join`,`compact`,`keys`,`entries`,`url`,`raw`,`date`,`number`,`currency`,`percent`,`kvRoute`,`kvQuery`],DATE_FORMATS={short:{dateStyle:`short`,timeStyle:`short`},medium:{dateStyle:`medium`,timeStyle:`medium`},long:{dateStyle:`long`,timeStyle:`long`},full:{dateStyle:`full`,timeStyle:`long`},shortDate:{dateStyle:`short`},mediumDate:{dateStyle:`medium`},longDate:{dateStyle:`long`},fullDate:{dateStyle:`full`},shortTime:{timeStyle:`short`},mediumTime:{timeStyle:`medium`}};function digits(info){if(info==null)return{};let m=/^(\d+)\.(\d+)-(\d+)$/.exec(String(info));if(!m)throw Error(`digits must look like '1.0-2', got '${String(info)}'`);return{minimumIntegerDigits:Number(m[1]),minimumFractionDigits:Number(m[2]),maximumFractionDigits:Number(m[3])}}const formatters=/* @__PURE__ */ new Map;function remember(key,f){return formatters.size>=256&&formatters.clear(),formatters.set(key,f),f}function cached(key,make){return formatters.get(key)??remember(key,make())}const toNumber=v=>{if(v==null||v===``)return;let n=Number(v);return Number.isNaN(n)?void 0:n},str=v=>v==null?``:String(v);function builtinPipes(env){return{kvQuery:(url,...pairs)=>{if(pairs.length%2)throw Error(`kvQuery takes key/value pairs: kvQuery:'page':page`);let parts=[];for(let i=0;i<pairs.length;i+=2){let key=encodeURIComponent(str(pairs[i]));for(let v of Array.isArray(pairs[i+1])?pairs[i+1]:[pairs[i+1]])v!=null&&v!==``&&parts.push(`${key}=${encodeURIComponent(str(v))}`)}let s=str(url);if(!parts.length)return s;let at=s.indexOf(`#`),[base,hash]=at<0?[s,``]:[s.slice(0,at),s.slice(at)];return`${base}${base.includes(`?`)?`&`:`?`}${parts.join(`&`)}${hash}`},kvRoute:(name,...params)=>{if(!env.urlFor)throw Error(`kvRoute needs a request (ctx.render): outside one, pass the URLs in as data, built with ROUTE_URLS`);return env.urlFor(str(name),params.map(p=>typeof p==`number`?p:str(p)))},uppercase:v=>str(v).toUpperCase(),lowercase:v=>str(v).toLowerCase(),titlecase:v=>str(v).replace(/\b\p{L}/gu,c=>c.toUpperCase()),json:v=>JSON.stringify(v,null,2),slice:(v,start,end)=>typeof v==`string`||Array.isArray(v)?v.slice(start,end):v,join:(v,separator=`, `)=>Array.isArray(v)||v instanceof Set?[...v].map(str).join(str(separator)):str(v),compact:v=>Array.isArray(v)||v instanceof Set?[...v].filter(x=>x!=null&&x!==!1&&x!==``):v,keys:v=>v instanceof Map?[...v.keys()]:v&&typeof v==`object`?Object.keys(v):[],entries:v=>v instanceof Map?[...v.entries()]:v&&typeof v==`object`?Object.entries(v):[],url:v=>encodeURIComponent(str(v)),raw:v=>v instanceof SafeHtml?v:new SafeHtml(str(v)),date:(v,format=`medium`,timeZone)=>{if(v==null||v===``)return``;let d=v instanceof Date?v:new Date(v);if(Number.isNaN(d.getTime()))return``;let preset=DATE_FORMATS[String(format)];if(!preset)throw Error(`unknown date format '${String(format)}'`);let tz=timeZone??env.timeZone;return cached(`d|${env.locale}|${String(format)}|${tz}`,()=>new Intl.DateTimeFormat(env.locale,{...preset,timeZone:tz})).format(d)},number:(v,info)=>{let n=toNumber(v);return n===void 0?``:cached(`n|${env.locale}|${String(info)}`,()=>new Intl.NumberFormat(env.locale,digits(info))).format(n)},currency:(v,code,info)=>{let n=toNumber(v);return n===void 0?``:cached(`c|${env.locale}|${String(code)}|${String(info)}`,()=>new Intl.NumberFormat(env.locale,{style:`currency`,currency:String(code??`USD`),...digits(info)})).format(n)},percent:(v,info)=>{let n=toNumber(v);return n===void 0?``:cached(`p|${env.locale}|${String(info)}`,()=>new Intl.NumberFormat(env.locale,{style:`percent`,...digits(info)})).format(n)}}}function topLevelTokens(src){let out=[],depth=0,i=0;for(;i<src.length;){let c=src[i];if(c===`/`&&src[i+1]===`/`){let nl=src.indexOf(`
13
+ `,i);i=nl<0?src.length:nl}else if(c===`/`&&src[i+1]===`*`){let end=src.indexOf(`*/`,i+2);i=end<0?src.length:end+2}else if(c===`'`||c===`"`||c==="`"){for(i++;i<src.length&&src[i]!==c;)i+=src[i]===`\\`?2:1;i++}else if(c===`{`||c===`(`||c===`[`)depth===0&&out.push({v:c,start:i}),depth++,i++;else if(c===`}`||c===`)`||c===`]`)depth--,depth===0&&out.push({v:c,start:i}),i++;else if(depth===0&&/[A-Za-z_$*]/.test(c)){let m=/^[A-Za-z_$][\w$]*|^\*/.exec(src.slice(i));out.push({v:m[0],start:i}),i+=m[0].length}else depth===0&&(c===`,`||c===`;`||c===`=`)&&out.push({v:c,start:i}),i++}return out}function braceNames(src,open){let close=src.indexOf(`}`,open),body=src.slice(open+1,close<0?src.length:close),names=[],offset=open+1;for(let part of body.split(`,`)){let m=/^(\s*)([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?\s*$/.exec(part);m&&names.push({local:m[2],exported:m[3]??m[2],at:offset+m[1].length}),offset+=part.length+1}return{names,end:close<0?src.length:close+1}}function readPipeExports(source,file){return readExportNames(source,file,BUILTIN_PIPES,`pipe`)}function readExportNames(source,file,builtins,kind){let names=[],diagnostics=[],fail=(at,len,message)=>diagnostics.push(error(file,{start:positionAt(source,at),end:positionAt(source,at+len)},message)),add=(name,at)=>{builtins.includes(name)?fail(at,name.length,`'${name}' is a built-in ${kind} — choose another name`):names.push(name)},tokens=topLevelTokens(source);for(let t=0;t<tokens.length;t++){if(tokens[t].v!==`export`)continue;let at=tokens[t].start,next=tokens[t+1],after=tokens[t+2];switch(next?.v){case`const`:case`let`:case`var`:after&&/^[A-Za-z_$]/.test(after.v)?add(after.v,after.start):fail(at,6,`export one ${kind} per name: export const name = …`);break;case`function`:after&&/^[A-Za-z_$]/.test(after.v)&&add(after.v,after.start);break;case`async`:fail(at,6,`${kind}s must be synchronous — an async function returns a Promise`);break;case`{`:{let{names:list,end}=braceNames(source,next.start);if(tokens.find(x=>x.start>=end)?.v===`from`){fail(at,6,`re-exports aren't read — import the ${kind} and export it from this file`);break}for(let n of list)add(n.exported,n.at);break}case`type`:case`interface`:break;case`*`:fail(at,6,`export * isn't read — export each ${kind} by name`);break;case`default`:fail(at,6,`a default export is not a ${kind} — export each ${kind} by name`);break;default:fail(at,6,`export ${next?.v??``} is not a ${kind} — export const or function`)}}return{names,diagnostics}}const VALIDATORS_TAG=`kick-validators`,VALIDATORS={required:{args:[],message:`This field is required`},email:{args:[],message:`Enter a valid email address`},url:{args:[],message:`Enter a valid URL`},minLength:{args:[`number`],message:`Use at least {0} characters`},maxLength:{args:[`number`],message:`Use at most {0} characters`},min:{args:[`number`],message:`Enter {0} or more`},max:{args:[`number`],message:`Enter {0} or less`},pattern:{args:[`string`],message:`Enter a value in the expected format`},in:{args:[`string`],message:`Choose one of: {0}`}},BUILTIN_VALIDATORS=Object.keys(VALIDATORS);function readValidatorExports(source,file){return readExportNames(source,file,Object.keys(VALIDATORS),`validator`)}function argValue(a){if(/^-?\d+(\.\d+)?$/.test(a))return Number(a);let m=/^(['"])([\s\S]*)\1$/.exec(a);return m?m[2].split(`\\${m[1]}`).join(m[1]):void 0}function split(s,sep){let out=[],quote=``,at=0;for(let i=0;i<s.length;i++){let c=s[i];quote?c===`\\`?i++:c===quote&&(quote=``):c===`'`||c===`"`?quote=c:c===sep&&(out.push(s.slice(at,i)),at=i+1)}return out.push(s.slice(at)),out.map(p=>p.trim())}function parseValidate(src,custom){let rules=[];for(let part of split(src,`|`)){if(!part)return{error:`empty validator in validate`};let[name,...raw]=split(part,`:`);if(!Object.hasOwn(VALIDATORS,name)&&custom?.has(name)){let args=raw.map(argValue);if(args.some(a=>a===void 0))return{error:`${name} takes numbers or quoted strings`};rules.push([name,...args]);continue}let spec=VALIDATORS[name];if(!spec)return{error:`unknown validator '${name}'`};if(raw.length!==spec.args.length)return{error:`${name} takes ${spec.args.length} argument${spec.args.length===1?``:`s`}`};let args=[];for(let i=0;i<raw.length;i++){let a=raw[i];if(spec.args[i]===`number`){if(!/^-?\d+(\.\d+)?$/.test(a))return{error:`${name} takes a number`};args.push(Number(a))}else{let m=/^(['"])([\s\S]*)\1$/.exec(a);if(!m)return{error:`${name} takes a quoted string`};args.push(m[2].split(`\\${m[1]}`).join(m[1]))}}if(name===`pattern`)try{RegExp(args[0])}catch{return{error:`pattern '${args[0]}' isn't a valid regular expression`}}rules.push([name,...args])}return{rules}}const NAMED={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`,nbsp:`\xA0`,colon:`:`,Tab:` `,NewLine:`
14
+ `,sol:`/`,bsol:`\\`,period:`.`,comma:`,`,semi:`;`,equals:`=`,quest:`?`,num:`#`,excl:`!`,lpar:`(`,rpar:`)`,plus:`+`,hyphen:`-`,dash:`-`,copy:`©`,reg:`®`,trade:`™`,hellip:`…`,mdash:`—`,ndash:`–`,laquo:`«`,raquo:`»`};function decodeEntities(s){return s.includes(`&`)?s.replace(/&(?:#[xX]([0-9a-fA-F]+)|#(\d+)|([A-Za-z][A-Za-z0-9]*));?/g,(m,hex,dec,name)=>{if(hex!==void 0||dec!==void 0){let code=parseInt(hex??dec,hex===void 0?10:16);return code>0&&code<=1114111&&!(code>=55296&&code<=57343)?String.fromCodePoint(code):`�`}return Object.hasOwn(NAMED,name)&&m.endsWith(`;`)?NAMED[name]:m}):s}function optimize(nodes){let out=[];for(let n of nodes){let node=deep(n),last=out[out.length-1];if(node.k===`s`){if(!node.t)continue;if(last?.k===`s`){last.t+=node.t;continue}}out.push(node)}return out}function deep(n){switch(n.k){case`if`:return{...n,br:n.br.map(b=>({...b,b:optimize(b.b)}))};case`for`:return n.em?{...n,b:optimize(n.b),em:optimize(n.em)}:{...n,b:optimize(n.b)};case`sw`:return{...n,cs:n.cs.map(c=>({...c,b:optimize(c.b)})),...n.d?{d:optimize(n.d)}:{}};case`cmp`:return{...n,f:Object.fromEntries(Object.entries(n.f).map(([k,v])=>[k,{...v,nodes:optimize(v.nodes)}]))};case`o`:return{...n,fb:optimize(n.fb)};case`dyn`:return{...n,c:Object.fromEntries(Object.entries(n.c).map(([k,v])=>[k,deep(v)])),f:Object.fromEntries(Object.entries(n.f).map(([k,v])=>[k,{...v,nodes:optimize(v.nodes)}]))};case`s`:return{...n};default:return n}}const ANIMATION=/* @__PURE__ */ new Set([`animate`,`set`,`animatemotion`,`animatetransform`]),ANIMATION_VALUES=/* @__PURE__ */ new Set([`values`,`to`,`from`,`by`,`attributename`]),JSON_SCRIPT_TYPES=/* @__PURE__ */ new Set([`application/json`,`application/ld+json`]),NO_REFILL=/* @__PURE__ */ new Set([`password`,`file`,`hidden`,`submit`,`button`,`reset`,`image`]);function oldOf(name){return{k:`d`,n:`$old`,p:[{e:{k:`l`,v:name},o:1}]}}function equals(e,value){return{k:`b`,o:`==`,l:e,r:value}}const LOOP_VARS$2=/* @__PURE__ */ new Set([`$index`,`$first`,`$last`,`$even`,`$odd`,`$count`]),isFallthrough=a=>{if(a.kind===`class`||a.kind===`style`)return!0;let n=a.name.toLowerCase();return[`class`,`id`,`style`,`role`].includes(n)||n.startsWith(`aria-`)||n.startsWith(`data-`)},camel=name=>name.replace(/-([a-z])/g,(_,c)=>c.toUpperCase()),FIELD_GUARDED=/* @__PURE__ */ new Set([`type`,`name`,`value`,`checked`,`validate`]),GUARDED={input:FIELD_GUARDED,select:FIELD_GUARDED,textarea:FIELD_GUARDED,option:FIELD_GUARDED,meta:/* @__PURE__ */ new Set([`http-equiv`,`content`]),script:/* @__PURE__ */ new Set([`type`])};function distance(a,b){let row=Array.from({length:b.length+1},(_,j)=>j);for(let i=1;i<=a.length;i++){let prev=row[0];row[0]=i;for(let j=1;j<=b.length;j++){let cur=row[j];row[j]=Math.min(row[j]+1,row[j-1]+1,prev+(a[i-1]===b[j-1]?0:1)),prev=cur}}return row[b.length]}function nearInput(name,inputs){if(/^(hx-|x-|aria-|data-|@|:)/i.test(name))return;let want=camel(name).toLowerCase();for(let input of inputs)if(distance(want,input.toLowerCase())<=2)return input}var Checker=class{project;ast;component;diagnostics=[];slots=0;scopes=[/* @__PURE__ */ new Map];loops=[];warned=/* @__PURE__ */ new Set;stackNames=/* @__PURE__ */ new Set;offered=/* @__PURE__ */ new Map;inPush=0;snippetDefs=/* @__PURE__ */ new Map;snippets=Object.create(null);topLets=/* @__PURE__ */ new Set;inSnippet=!1;fragments=Object.create(null);unit;tags=/* @__PURE__ */ new Map;signatures=/* @__PURE__ */ new Map;constructor(project,ast,component){this.project=project,this.ast=ast,this.component=component;for(let name of project.templates.keys()){if(!isComponent(name,project.componentsDir))continue;let tag=componentTag(name,project.componentsDir);this.tags.set(tag,[...this.tags.get(tag)??[],name])}}err(span,message){this.diagnostics.push(error(this.ast.file,span,message))}warn(span,message){this.diagnostics.push(warning(this.ast.file,span,message))}slot(){return this.slots++}bind(name,b){this.scopes[this.scopes.length-1].set(name,b)}lookup(name){for(let i=this.scopes.length-1;i>=0;i--){let b=this.scopes[i].get(name);if(b)return b}}scoped(fn){this.scopes.push(/* @__PURE__ */ new Map);try{return fn()}finally{this.scopes.pop()}}expr(e,where=`text`,whole=!1){switch(e.kind){case`literal`:return{k:`l`,v:e.value};case`unary`:return{k:`u`,o:e.op,a:this.expr(e.arg)};case`binary`:case`logical`:return{k:`b`,o:e.op,l:this.expr(e.left),r:this.expr(e.right)};case`conditional`:return{k:`c`,t:this.expr(e.test),y:this.expr(e.whenTrue),n:this.expr(e.whenFalse)};case`pipe`:return this.project.pipes.has(e.name)||this.err(e.span,`unknown pipe '${e.name}'`),e.name===`raw`&&(!whole||where!==`text`&&where!==`css`)&&this.err(e.span,where===`attr`?`raw isn't allowed in an attribute: it could break out of the quotes`:where===`text`||where===`css`?`raw must be the last pipe of the whole {{ }}: {{ value | raw }}`:`raw isn't allowed inside <${where===`rcdata`?`title> or <textarea`:`script`}>`),{k:`p`,n:e.name,i:this.expr(e.input),a:e.args.map(a=>this.expr(a))};case`path`:{let p=e.segments.map(s=>{let seg=s.computed?{e:this.expr(s.computed)}:{n:s.name};return s.optional&&(seg.o=1),seg});if(LOOP_VARS$2.has(e.root)&&this.unit?.inLoop&&!this.loops.length)return this.unit.errors.push(error(this.ast.file,e.span,`'${e.root}' comes from the @for around this fragment — alias it (let i = ${e.root}) and pass i`)),{k:`x`};if(LOOP_VARS$2.has(e.root)){let loop=this.loops[this.loops.length-1];return loop===void 0?(this.err(e.span,`${e.root} is only available inside @for`),{k:`x`}):{k:`m`,s:loop,w:e.root}}let b=this.lookup(e.root);return b?.kind===`meta`?{k:`m`,s:b.s,w:b.w}:b?{k:`v`,s:b.s,p}:this.inSnippet&&this.topLets.has(e.root)?(this.err(e.span,`'${e.root}' is a top-level @let, which a snippet can't read — pass it as a parameter`),{k:`x`}):this.unit?.outer.has(e.root)?(this.unit.needs.includes(e.root)||this.unit.needs.push(e.root),{k:`d`,n:e.root,p}):FORM_GLOBALS.has(e.root)?{k:`d`,n:e.root,p}:this.component?(this.warned.has(e.root)||(this.warned.add(e.root),this.warn(e.span,`'${e.root}' isn't an input of this component — declare it with @input ${e.root}`)),{k:`x`}):{k:`d`,n:e.root,p}}}}nodes(list,parent){let out=[],stack=[{list,i:0,parent}];for(;stack.length;){let f=stack[stack.length-1];if(f.i>=f.list.length){stack.pop(),f.close&&f.parent?.tag.toLowerCase()===`select`&&(this.select=void 0),f.close&&out.push({k:`s`,t:f.close});continue}let n=f.list[f.i++];if(n.k!==`element`){this.node(n,out,f.parent);continue}let open=this.element(n,out);open&&stack.push({list:open.children,i:0,parent:open,close:`</${open.tag}>`})}return out}node(n,out,parent){switch(n.k){case`text`:out.push({k:`s`,t:n.value});return;case`interp`:if(n.ctx===`comment`){this.err(n.span,`{{ }} isn't allowed inside an HTML comment — use {{-- --}} for a template comment`);return}if(n.ctx===`raw-text`){out.push(...this.rawText(n,parent));return}out.push({k:`i`,c:n.ctx===`rcdata`?`rcdata`:`text`,e:this.expr(n.expr,n.ctx===`rcdata`?`rcdata`:`text`,!0),at:at(n.span)});return;case`comment`:for(let c of n.children)c.k===`interp`&&this.node(c,out);out.push({k:`s`,t:`<!--${n.children.map(c=>c.k===`text`?c.value:``).join(``)}-->`});return;case`element`:{let open=this.element(n,out);open&&out.push(...this.nodes(open.children,open),{k:`s`,t:`</${open.tag}>`});return}case`if`:out.push({k:`if`,br:n.branches.map(b=>this.scoped(()=>{let cond=b.cond&&this.expr(b.cond),alias;b.alias&&(alias=this.slot(),this.bind(b.alias,{kind:`slot`,s:alias}));let br={b:this.nodes(b.body,parent)};return cond&&(br.c=cond),alias!==void 0&&(br.a=alias),br}))});return;case`for`:{let e=this.expr(n.of),m=this.slot(),it,body=this.scoped(()=>{typeof n.item==`string`?(it=this.slot(),this.bind(n.item,{kind:`slot`,s:it})):(it=[this.slot(),this.slot()],this.bind(n.item[0],{kind:`slot`,s:it[0]}),this.bind(n.item[1],{kind:`slot`,s:it[1]}));for(let[name,w]of Object.entries(n.lets))this.bind(name,{kind:`meta`,s:m,w});this.loops.push(m);try{return this.nodes(n.body,parent)}finally{this.loops.pop()}}),node={k:`for`,e,it,m,b:body,at:at(n.span)};n.empty&&(node.em=this.scoped(()=>this.nodes(n.empty,parent))),out.push(node);return}case`switch`:{let node={k:`sw`,e:this.expr(n.on),cs:n.cases.map(c=>({e:this.expr(c.value),b:this.scoped(()=>this.nodes(c.body,parent))}))};n.default&&(node.d=this.scoped(()=>this.nodes(n.default,parent))),out.push(node);return}case`let`:{let e=this.expr(n.expr),s=this.slot();this.scopes[this.scopes.length-1].has(n.name)&&this.err(n.span,`@let ${n.name} is declared twice here`),this.bind(n.name,{kind:`slot`,s}),out.push({k:`let`,s,e});return}case`verbatim`:out.push({k:`s`,t:n.text});return;case`slot-outlet`:{let name=n.name??``,key=n.offers.map(o=>o.name).toSorted().join(`, `),prev=this.offered.get(name);prev!==void 0&&prev!==key&&this.err(n.span,`slot '${name||`default`}' offers ${key||`nothing`} here but ${prev||`nothing`} elsewhere — offer the same names everywhere`),this.offered.set(name,key);let v=n.offers.map(o=>({n:o.name,e:this.expr(o.expr)})),fs=[],fb=this.scoped(()=>{for(let o of n.offers){let s=this.slot();fs.push(s),this.bind(o.name,{kind:`slot`,s})}return this.nodes(n.fallback,parent)});out.push({k:`o`,n:name,fb,...v.length?{v,fs}:{}});return}case`slot-fill`:this.err(n.span,`@slot('…') { } goes at the top of a page with a layout, or inside a component tag`);return;case`assets`:out.push({k:`as`,en:n.entry});return;case`fragment`:this.fragment(n,out,parent);return;case`snippet`:return;case`render`:{if(parent?.foreign){this.err(n.span,`@render can't go inside <svg> or <math>: render the snippet outside it`);return}let params=this.snippetDefs.get(n.name);if(!params){this.err(n.span,`no snippet '${n.name}' in this template — it has ${[...this.snippetDefs.keys()].join(`, `)||`none`}`);return}let required=params.filter(p=>p.default===void 0).length;if(n.args.length<required||n.args.length>params.length){let range=required===params.length?`${required}`:`${required}–${params.length}`;this.err(n.span,`@render ${n.name} takes ${range} argument(s), got ${n.args.length}`);return}out.push({k:`rnd`,n:n.name,a:n.args.map(a=>this.expr(a)),at:at(n.span)});return}case`push`:this.inPush++;try{out.push({k:`push`,n:n.name,b:this.scoped(()=>this.nodes(n.body,parent))})}finally{this.inPush--}return;case`stack`:if(n.children.some(c=>c.k!==`text`||c.value.trim())){this.err(n.span,`<stack> can't have content: @push adds it`);return}if(this.component){this.err(n.span,`<stack> goes in a page or layout, not in components`);return}if(this.inPush){this.err(n.span,`<stack> can't go inside @push: put it in the layout itself`);return}this.stackNames.has(n.name)&&this.warn(n.span,`stack '${n.name}' is already placed above: only the first one is filled`),this.stackNames.add(n.name),out.push({k:`stk`,n:n.name})}}fragment(n,out,parent){if(this.component){this.err(n.span,`fragments aren't allowed in components`);return}if(this.inSnippet){this.err(n.span,`a @fragment can't go inside a @snippet: put the @render inside the fragment`);return}if(out.push(...this.scoped(()=>this.nodes(n.body,parent))),this.unit)return;if(n.name in this.fragments){this.err(n.span,`fragment '${n.name}' is defined twice`);return}let saved={scopes:this.scopes.splice(0),slots:this.slots,loops:this.loops.splice(0),validates:this.validates,reported:this.diagnostics.length},unit={outer:new Set(saved.scopes.flatMap(scope=>[...scope.keys()])),inLoop:saved.loops.length>0,needs:[],errors:[]};this.unit=unit,this.scopes.push(/* @__PURE__ */ new Map),this.slots=0,this.validates=!1;let body;try{body=this.nodes(n.body,parent)}finally{this.unit=void 0,this.scopes.splice(0,this.scopes.length,...saved.scopes),this.loops.splice(0,this.loops.length,...saved.loops)}let compiled={needs:unit.needs,slots:this.slots,body:optimize(body)};this.validates&&(compiled.validates=!0),this.fragments[n.name]=compiled,this.slots=saved.slots,this.validates=saved.validates,this.diagnostics.length=saved.reported,this.diagnostics.push(...unit.errors)}snippet(n,inputs){let saved={scopes:this.scopes.splice(0),loops:this.loops.splice(0),slots:this.slots,validates:this.validates};this.scopes.push(/* @__PURE__ */ new Map),this.slots=0,this.validates=!1,this.inSnippet=!0;let body,params=[];try{for(let i of inputs)this.bind(i.n,{kind:`slot`,s:this.slot()});for(let p of n.params){let s=this.slot();params.push(s),this.bind(p.name,{kind:`slot`,s})}body=this.nodes(n.body)}finally{this.inSnippet=!1,this.scopes.splice(0,this.scopes.length,...saved.scopes),this.loops.splice(0,this.loops.length,...saved.loops)}let compiled={params,defaults:n.params.map(p=>p.default),slots:this.slots,body:optimize(body)};this.validates&&(compiled.validates=!0),this.snippets[n.name]=compiled,this.slots=saved.slots,this.validates=saved.validates}rawText(n,parent){let tag=parent?.tag.toLowerCase(),type=parent?.attrs.find(a=>a.name.toLowerCase()===`type`),typeValue=type?.kind===`static`?String(type.parts?.[0]??``).trim().toLowerCase():``,isJson=tag===`script`&&JSON_SCRIPT_TYPES.has(typeValue),only=parent?.children.filter(c=>!(c.k===`text`&&!c.value.trim())).length===1;return isJson&&only&&n.expr.kind===`pipe`&&n.expr.name===`json`?[{k:`i`,c:`json`,e:this.expr(n.expr,`json`),at:at(n.span)}]:tag===`style`&&!parent.foreign&&only&&n.expr.kind===`pipe`&&n.expr.name===`raw`?[{k:`i`,c:`css`,e:this.expr(n.expr,`css`,!0),at:at(n.span)}]:(this.err(n.span,tag===`script`?`{{ }} isn't allowed inside <script>: pass data as <script type="application/json">{{ value | json }}<\/script>`:tag===`style`&&!parent.foreign?`{{ }} isn't allowed inside <style>, except trusted CSS as its whole content: <style>{{ css | raw }}</style>`:`{{ }} isn't allowed inside <${tag}>`),[])}element(el,out){let lower=el.tag.toLowerCase();if(isClientScript(el)){this.err(el.span,`<script client> must be at the top level of the component`);return}if(!el.foreign&&lower===`component`){this.dynamic(el,out);return}if(!el.foreign&&lower.includes(`-`)){let names=this.tags.get(lower);if(names&&names.length>1){this.err(el.span,`<${lower}> matches more than one component: ${names.join(`, `)}`);return}if(names){this.call(el,names[0],out,el===this.rootElement);return}this.hasClientScript||this.warn(el.span,`<${lower}> isn't a component (no ${this.project.componentsDir}/…/${lower}.kick) — it's output as a custom element`)}let attrs=this.attrs(el),refill=this.refill(el,attrs);if(attrs.some(a=>a.t!==`s`)||el===this.rootElement){out.push({k:`s`,t:`<${el.tag}`});let node={k:`A`,tag:el.tag,a:attrs,at:at(el.span)};el===this.rootElement&&(node.f=1),out.push(node)}else out.push({k:`s`,t:`<${el.tag}${attrs.map(a=>staticAttr(a)).join(``)}`});if(el.void||el.selfClosing&&el.foreign)out.push({k:`s`,t:el.selfClosing?` />`:`>`});else return out.push({k:`s`,t:`>`}),refill&&lower===`textarea`&&el.children.length===0&&out.push({k:`s`,t:`
15
+ `},{k:`i`,c:`rcdata`,e:oldOf(refill),at:at(el.span)}),el}validates=!1;validateAttr(el,a,out){if(a.kind!==`static`){this.err(a.span,`validate must be written, not bound`);return}if(!el.attrs.some(x=>x.name.toLowerCase()===`name`)){this.err(a.span,`validate needs a name on the same field`);return}let r=parseValidate(decodeEntities(String(a.parts?.[0]??``)),this.project.validators);`error`in r?this.err(a.span,r.error):(this.validates=!0,out.push({t:`s`,n:`data-kick-validate`,v:JSON.stringify(r.rules).replace(/&/g,`&amp;`)}))}select;refill(el,attrs){if(el.foreign)return;let tag=el.tag.toLowerCase(),has=n=>el.attrs.some(a=>a.name.toLowerCase()===n),stat=n=>{let a=el.attrs.find(x=>x.name.toLowerCase()===n&&x.kind===`static`);return a?String(a.parts?.[0]??``):void 0},valueExpr=()=>{let a=el.attrs.find(x=>x.name.toLowerCase()===`value`);if(a?.kind===`static`)return{k:`l`,v:decodeEntities(String(a.parts?.[0]??``))};if(a?.kind===`interp`&&a.parts?.length===1&&typeof a.parts[0]!=`string`)return{k:`b`,o:`+`,l:{k:`l`,v:``},r:this.expr(a.parts[0],`attr`)}};if(tag===`option`){let value=valueExpr();if(this.select===void 0||value===void 0||has(`selected`))return;attrs.push({t:`b`,n:`selected`,e:equals(oldOf(this.select),value)});return}if(tag!==`input`&&tag!==`textarea`&&tag!==`select`)return;let name=stat(`name`);if(!name||SECRET_FIELD.test(name))return;if(tag===`select`)return this.select=name,name;if(tag===`textarea`)return name;if(has(`type`)&&stat(`type`)===void 0)return;let type=(stat(`type`)??`text`).toLowerCase();if(!NO_REFILL.has(type)){if(type===`checkbox`||type===`radio`){if(has(`checked`))return;let value=has(`value`)?valueExpr():{k:`l`,v:`on`};return value?(attrs.push({t:`b`,n:`checked`,e:equals(oldOf(name),value)}),name):void 0}if(!has(`value`))return attrs.push({t:`b`,n:`value`,e:oldOf(name)}),name}}rootElement;hasClientScript=!1;attrs(el){let tag=el.tag,out=[],httpEquiv=el.attrs.find(a=>a.name.toLowerCase()===`http-equiv`),refresh=tag.toLowerCase()===`meta`&&httpEquiv?.kind===`static`&&String(httpEquiv.parts?.[0]).trim().toLowerCase()===`refresh`;for(let a of el.attrs){let lower=a.name.toLowerCase();if(lower===`validate`&&!el.foreign){this.validateAttr(el,a,out);continue}if(a.kind!==`static`&&a.kind!==`bare`&&a.kind!==`class`&&a.kind!==`style`){if(lower.startsWith(`on`)){this.err(a.span,`${a.name} can't be interpolated: event handler attributes run their value as script`);continue}if(lower===`srcdoc`){this.err(a.span,`srcdoc can't be interpolated: its value is a whole HTML document`);continue}if(lower===`style`){this.err(a.span,`style can't be interpolated — bind one property with [style.prop]="value"`);continue}if(lower===`class`&&a.kind===`interp`){this.err(a.span,`class can't be interpolated — add classes with [class.name]="condition"`);continue}if(ANIMATION.has(tag.toLowerCase())&&ANIMATION_VALUES.has(lower)){this.err(a.span,`${a.name} can't be interpolated on <${tag}>: an animation can set href to a javascript: URL`);continue}if(refresh&&lower===`content`){this.err(a.span,`a refresh <meta>'s content can't be interpolated: it holds a URL to navigate to`);continue}}let url=isUrlAttr(tag,a.name)?lower===`srcset`?`srcset`:`url`:void 0;if(a.kind!==`bind`&&a.kind!==`class`&&a.kind!==`style`||a.expr)switch(a.kind){case`bare`:out.push({t:`s`,n:a.name,v:!0});break;case`static`:out.push({t:`s`,n:a.name,v:String(a.parts?.[0]??``)});break;case`interp`:{let node={t:`i`,n:a.name,p:a.parts.map(p=>typeof p==`string`?p:this.expr(p,`attr`))};url&&(node.u=url),out.push(node);break}case`bind`:{let node={t:`b`,n:a.name,e:this.expr(a.expr,`attr`)};url&&(node.u=url),out.push(node);break}case`class`:out.push({t:`c`,n:a.name,e:this.expr(a.expr,`attr`)});break;case`style`:{let node={t:`y`,n:a.name,e:this.expr(a.expr,`attr`)};a.unit&&(node.x=a.unit),out.push(node);break}}}return out}signature(name){let cached=this.signatures.get(name);if(cached)return cached;let ast=this.project.templates.get(name),outlets=/* @__PURE__ */ new Map,stack=[ast.body];for(;stack.length;)for(let n of stack.pop())if(n.k===`slot-outlet`)outlets.has(n.name??``)||outlets.set(n.name??``,n.offers.map(o=>o.name)),stack.push(n.fallback);else if(n.k===`element`||n.k===`comment`)stack.push(n.children);else if(n.k===`if`)for(let b of n.branches)stack.push(b.body);else n.k===`for`?stack.push(n.body,n.empty??[]):n.k===`switch`?stack.push(...n.cases.map(c=>c.body),n.default??[]):(n.k===`slot-fill`||n.k===`fragment`||n.k===`push`||n.k===`snippet`)&&stack.push(n.body);let top=ast.body.filter(n=>!(n.k===`element`&&isClientScript(n))),roots=rootElements(top),root;if(roots.length===1){let el=roots[0],tag=el?.tag.toLowerCase();if(el&&!el.foreign&&tag.includes(`-`)&&this.tags.get(tag)?.length===1)root={k:`cmp`,name:this.tags.get(tag)[0]};else if(el){if(root={k:`el`,tag},tag===`component`&&!el.foreign){let of=el.attrs.find(a=>a.name.toLowerCase()===`of`&&a.kind===`static`);root.of=String(of?.parts?.[0]??``).split(/\s+/).filter(Boolean)}}else top.some(n=>n.k===`slot-outlet`)&&(root={k:`slot`})}let sig={name,inputs:new Map(ast.inputs.map(i=>[i.name,{required:!i.default,def:i.default?.value}])),outlets,roots:roots.length,...root?{root}:{}};return this.signatures.set(name,sig),sig}inputExpr(a,def){if(a.kind===`bind`)return this.expr(a.expr);if(a.kind===`bare`)return{k:`l`,v:!0};if(a.kind===`static`){let v=String(a.parts?.[0]??``);return typeof def==`boolean`&&(v===`true`||v===`false`)&&this.warn(a.span,`${a.name}="${v}" passes the string "${v}", which is truthy — write [${a.name}]="${v}"`),{k:`l`,v:decodeEntities(v)}}if(a.kind===`interp`)return a.parts.reduce((acc,p)=>({k:`b`,o:`+`,l:acc,r:typeof p==`string`?{k:`l`,v:decodeEntities(p)}:this.expr(p)}),{k:`l`,v:``});this.err(a.span,`[${a.kind}.${a.name}] goes on the component's root element, not an input`)}call(el,name,out,root=!1,candidate=!1){let sig=this.signature(name),target=this.project.templates.get(name),slotOf=/* @__PURE__ */ new Map;target.inputs.forEach((i,idx)=>slotOf.set(i.name,idx));let inputs=[],given=/* @__PURE__ */ new Set,fallthrough=[];for(let a of el.attrs){if(isFallthrough(a)){fallthrough.push(a);continue}let input=sig.inputs.has(a.name)?a.name:camel(a.name);if(!sig.inputs.has(input)){let near=nearInput(a.name,sig.inputs.keys());near&&this.warn(a.span,`'${a.name}' isn't an input of ${el.tag} — did you mean '${near}'? It's passed to the root element.`),fallthrough.push(a);continue}if(a.kind===`bind`&&!a.expr)continue;given.add(input);let e=this.inputExpr(a,sig.inputs.get(input).def);e&&inputs.push({s:slotOf.get(input),e})}for(let[input,info]of sig.inputs)info.required&&!given.has(input)&&this.err(el.span,`missing input '${input}' on <${el.tag}>`);let chained=[],leaf=sig,seen=/* @__PURE__ */ new Set([name]);for(;leaf.root?.k===`cmp`&&fallthrough.length&&leaf.roots===1&&!seen.has(leaf.root.name);){seen.add(leaf.root.name);let inner=this.signature(leaf.root.name),rest=[];for(let a of fallthrough){let input=inner.inputs.has(a.name)?a.name:camel(a.name);if(isFallthrough(a)||!inner.inputs.has(input)){rest.push(a);continue}let e=this.inputExpr(a,inner.inputs.get(input).def);e&&chained.push({n:input,e})}fallthrough.splice(0,fallthrough.length,...rest),leaf=inner}let passed=fallthrough.map(a=>a.name).join(`, `),tagDependent=fallthrough.filter(a=>!isFallthrough(a));if(fallthrough.length&&(leaf.roots!==1||!leaf.root))this.err(fallthrough[0].span,`<${el.tag}> passes ${passed} to its root element, but ${leaf.name}.kick needs exactly one root element for that`);else if(tagDependent.length&&leaf.root?.k===`el`&&leaf.root.tag===`component`)this.err(tagDependent[0].span,`<${el.tag}> passes ${tagDependent.map(a=>a.name).join(`, `)} to its root, but ${leaf.name}.kick's root is a <component>, whose element is only chosen at render time — declare them as inputs and pass them on`);else if(fallthrough.length&&leaf.root?.k===`el`&&leaf.root.of){let without=leaf.root.of.filter(tag=>{let names=this.tags.get(tag.toLowerCase());if(names?.length!==1)return!1;let cand=this.signature(names[0]);return cand.roots!==1||!cand.root||cand.root.k===`slot`});without.length&&this.err(fallthrough[0].span,`<${el.tag}> passes ${passed} on to its <component>'s candidates, but ${without.join(`, `)} has no single root element to take them`)}else if(fallthrough.length&&leaf.root?.k===`slot`)this.err(fallthrough[0].span,`<${el.tag}> passes ${passed} to its root, but ${leaf.name}.kick's root is a <slot>, which takes no attributes`);else if(leaf.root?.k===`el`&&Object.hasOwn(GUARDED,leaf.root.tag)){let names=GUARDED[leaf.root.tag],guarded=fallthrough.filter(a=>a.kind!==`class`&&a.kind!==`style`&&names.has(a.name.toLowerCase()));for(let a of guarded)this.err(a.span,`'${a.name}' would reach the <${leaf.root.tag}> in ${leaf.name}.kick, whose safety checks depend on its other attributes — declare it as an @input of ${el.tag}`);fallthrough.splice(0,fallthrough.length,...fallthrough.filter(a=>!guarded.includes(a)))}let fills={},rest=[];for(let c of el.children)c.k===`slot-fill`?(c.name in fills?this.err(c.span,`slot '${c.name}' is filled twice`):!sig.outlets.has(c.name)&&!candidate&&this.err(c.span,`<${el.tag}> has no slot '${c.name}'`),fills[c.name]=this.fill(c,candidate?void 0:sig.outlets.get(c.name))):rest.push(c);rest.some(c=>!(c.k===`text`&&!c.value.trim()))&&(sig.outlets.has(``)?``in fills?this.err(el.span,`<${el.tag}>'s default slot is filled twice: by the content between its tags and by @slot(default …)`):fills[``]={nodes:this.scoped(()=>this.nodes(rest))}:candidate||this.err(el.span,`<${el.tag}> has no default <slot /> for the content inside it`));let rootTag=leaf.root?.k===`el`?leaf.root.tag:el.tag,fa=this.attrs({...el,tag:rootTag,attrs:fallthrough});out.push({k:`cmp`,n:name,in:inputs,...chained.length?{ci:chained}:{},fa,f:fills,...root?{r:1}:{},at:at(el.span)})}dynamic(el,out){let plain=a=>a.kind!==`class`&&a.kind!==`style`,isA=el.attrs.find(a=>plain(a)&&a.name.toLowerCase()===`is`),ofA=el.attrs.find(a=>plain(a)&&a.name.toLowerCase()===`of`);if(!ofA||ofA.kind!==`static`){this.err(ofA?.span??el.span,`<component> needs of="tag-a tag-b": the components it may render`);return}if(!isA||isA.kind!==`bind`||!isA.expr){this.err(isA?.span??el.span,`<component> needs [is]="expr" — a bound value; for a fixed component, write its tag`);return}let rest=el.attrs.filter(a=>a!==isA&&a!==ofA);if(!String(ofA.parts?.[0]??``).trim()){this.err(ofA.span,`<component> needs at least one tag in of="…"`);return}let c=Object.create(null),sigs=[],reported=this.diagnostics.length;for(let tag of String(ofA.parts?.[0]??``).split(/\s+/).filter(Boolean)){let lower=tag.toLowerCase();if(lower in c){this.warn(ofA.span,`${lower} is listed twice in of`);continue}let names=this.tags.get(lower);if(!names||names.length!==1){this.err(ofA.span,`<component> lists ${lower}, which isn't a component (no ${this.project.componentsDir}/…/${lower}.kick)`);continue}let one=[];this.call({...el,tag:lower,attrs:rest,children:[]},names[0],one,el===this.rootElement,!0);let cmp=one.find(n=>n.k===`cmp`);cmp&&(c[lower]=cmp),sigs.push(this.signature(names[0]))}let seen=/* @__PURE__ */ new Set,mine=this.diagnostics.splice(reported).filter(d=>{let key=`${d.severity}|${d.span.start.offset}|${d.message}`;return!seen.has(key)&&seen.add(key)});this.diagnostics.push(...mine);let fills={},loose=[];for(let ch of el.children)ch.k===`slot-fill`?ch.name in fills?this.err(ch.span,`slot '${ch.name||`default`}' is filled twice`):fills[ch.name]=this.fill(ch,void 0):loose.push(ch);loose.some(ch=>!(ch.k===`text`&&!ch.value.trim()))&&(sigs.length&&!sigs.some(s=>s.outlets.has(``))?this.err(el.span,`no candidate of <component> has a default <slot /> for the content inside it`):``in fills?this.err(el.span,`<component>'s default slot is filled twice: by the content between its tags and by @slot(default …)`):fills[``]={nodes:this.scoped(()=>this.nodes(loose))});for(let f of el.children){if(f.k!==`slot-fill`)continue;let having=sigs.filter(s=>s.outlets.has(f.name));if(!having.length)this.err(f.span,`no candidate of <component> has a slot '${f.name||`default`}'`);else for(let l of f.lets)having.some(s=>s.outlets.get(f.name).includes(l.from))||this.err(f.span,`no candidate's slot '${f.name||`default`}' offers '${l.from}'`)}out.push({k:`dyn`,e:this.expr(isA.expr),c,f:fills,at:at(el.span)})}fill(f,offered){return this.scoped(()=>{let params=[];for(let l of f.lets){offered&&!offered.includes(l.from)&&this.err(f.span,`slot '${f.name||`default`}' doesn't offer '${l.from}' — it offers ${offered.join(`, `)||`nothing`}`);let s=this.slot();params.push({from:l.from,s}),this.bind(l.name,{kind:`slot`,s})}let nodes=this.nodes(f.body);return params.length?{nodes,params}:{nodes}})}ref(from,ref){return resolveRef(from,ref,n=>this.project.templates.has(n))}layoutChain(start,span,page){let outlets=/* @__PURE__ */ new Map,seen=[page],name=start;for(;name;){if(!templateName(name)){this.err(span,`'${name}' isn't a valid template name`);return}if(seen.includes(name)){this.err(span,`layout cycle: ${[...seen,name].join(` → `)}`);return}let ast=this.project.templates.get(name);if(!ast){this.err(span,`layout '${name}' not found`);return}seen.push(name),mergeOutlets(outlets,this.signature(name).outlets),name=ast.layout?this.ref(name,ast.layout):void 0}return outlets}};function isClientScript(n){return n.k===`element`&&n.tag.toLowerCase()===`script`&&n.attrs.some(a=>a.name.toLowerCase()===`client`&&a.kind===`bare`)}function rootElements(body){let roots=[];for(let n of body)(n.k!==`text`||n.value.trim())&&n.k!==`comment`&&n.k!==`let`&&n.k!==`push`&&n.k!==`snippet`&&roots.push(n.k===`element`?n:null);return roots}function mergeOutlets(into,more){for(let[name,offers]of more){let had=into.get(name);into.set(name,had?had.filter(o=>offers.includes(o)):[...offers])}return into}function staticAttr(a){return a.v===!0?` ${a.n}`:` ${a.n}="${a.v.replace(/"/g,`&quot;`)}"`}const at=span=>[span.start.line,span.start.column],zero={start:{offset:0,line:1,column:1},end:{offset:0,line:1,column:1}};function check(name,project){let ast=project.templates.get(name);if(!ast||!templateName(name))return{diagnostics:[error(`${name}.kick`,zero,`template '${name}' not found`)]};let component=isComponent(name,project.componentsDir),c=new Checker(project,ast,component);if(component){let tag=componentTag(name,project.componentsDir),same=c.tags.get(tag)??[];same.length>1&&c.diagnostics.push(error(ast.file,zero,`<${tag}> is the tag of more than one component: ${same.join(`, `)}`))}let pageDefaults={};if(!component)for(let i of ast.inputs)i.default&&(pageDefaults[i.name]=i.default.value);let inputs=(component?ast.inputs:[]).map((i,idx)=>{let s=idx,entry={n:i.name,s,r:!i.default};return i.default&&(entry.d=i.default.value),entry});c.slots=inputs.length;for(let i of inputs)c.bind(i.n,{kind:`slot`,s:i.s});let snippetNodes=[];for(let n of ast.body)n.k===`let`&&c.topLets.add(n.name),n.k===`snippet`&&(c.snippetDefs.has(n.name)?c.diagnostics.push(error(ast.file,n.span,`snippet '${n.name}' is defined twice`)):(c.snippetDefs.set(n.name,n.params),snippetNodes.push(n)));let top=[],client;for(let n of ast.body){if(n.k===`element`&&n.tag.toLowerCase()===`script`&&n.attrs.some(a=>a.name.toLowerCase()===`client`&&a.kind!==`bare`)){c.diagnostics.push(error(ast.file,n.span,`write <script client> with no value`));continue}if(n.k!==`element`||!isClientScript(n)){top.push(n);continue}if(!component){c.diagnostics.push(error(ast.file,n.span,`<script client> is only for components (src/views/${project.componentsDir}/…)`));continue}if(client){c.diagnostics.push(error(ast.file,n.span,`a component has one <script client>`));continue}if(n.children.some(ch=>ch.k!==`text`)){c.diagnostics.push(error(ast.file,n.span,`<script client> can't use {{ }} — pass data through attributes`));continue}let code=n.children.map(ch=>ch.k===`text`?ch.value:``).join(``),tag=componentTag(name,project.componentsDir);tag===`kick-validate`?c.diagnostics.push(error(ast.file,n.span,`kick-validate is reserved for the validator script`)):tag===`kick-validators`?c.diagnostics.push(error(ast.file,n.span,`kick-validators is reserved for the app's validators`)):/^[a-z][a-z0-9-]*$/.test(tag)?client={code,js:!1}:c.diagnostics.push(error(ast.file,n.span,`<script client> needs a component name of lowercase letters, digits and dashes: '${tag}'`))}c.hasClientScript=client!==void 0;for(let n of snippetNodes)c.snippet(n,inputs);if(component){let roots=rootElements(top);roots.length===1&&roots[0]&&(c.rootElement=roots[0])}let fills={},body=[],fillNodes=[];for(let[i,n]of top.entries())if(n.k===`snippet`){let next=top[i+1],prev=body.at(-1);next?.k===`text`&&/^\r?\n/.test(next.value)?top[i+1]={...next,value:next.value.replace(/^\r?\n/,``)}:!next&&prev?.k===`text`&&(body[body.length-1]={...prev,value:prev.value.replace(/\r?\n$/,``)})}else n.k===`slot-fill`&&!component?fillNodes.push(n):body.push(n);let base=project.baseLayout;base!==void 0&&!project.templates.has(base)&&c.diagnostics.push(error(ast.file,zero,`base layout '${base}' not found`));let mapped=component||configuredLayouts(project).has(name)?void 0:layoutResolver(project.layouts)(name),declared=ast.layout?c.ref(name,ast.layout):ast.layout,layoutName=declared===void 0?mapped:declared??void 0,outlets=layoutName===void 0?void 0:c.layoutChain(layoutName,ast.layoutSpan??zero,name);base!==void 0&&ast.layout!==null&&!component&&name!==base&&project.templates.has(base)&&(outlets=mergeOutlets(outlets??/* @__PURE__ */ new Map,c.signature(base).outlets));let bodyContent=body.some(n=>n.k!==`let`&&n.k!==`comment`&&!(n.k===`text`&&!n.value.trim()));for(let f of fillNodes){if(f.name===``&&bodyContent){c.diagnostics.push(error(ast.file,f.span,`the layout's default slot is filled twice: by the page's own content and by @slot(default …)`));continue}if(f.name in fills){c.diagnostics.push(error(ast.file,f.span,`slot '${f.name}' is filled twice`));continue}if(!outlets){c.diagnostics.push(warning(ast.file,f.span,`@slot('${f.name}') has no layout to fill here`));let fill=c.fill(f,void 0);fills[f.name]={...fill,nodes:optimize(fill.nodes)};continue}if(!outlets.has(f.name)){c.diagnostics.push(error(ast.file,f.span,`the layout has no slot '${f.name}'`));continue}let first=layoutName??(base!==void 0&&ast.layout!==null&&!component&&name!==base?base:void 0);if(f.name===``&&first&&project.templates.has(first)&&!c.signature(first).outlets.has(``)){c.diagnostics.push(error(ast.file,f.span,`layout '${first}' has no default <slot /> for @slot(default …)`));continue}let fill=c.fill(f,outlets.get(f.name));fills[f.name]={...fill,nodes:optimize(fill.nodes)}}let template={v:3,name,file:ast.file,slots:0,inputs,fills,body:optimize(c.nodes(body))};return template.slots=c.slots,declared!==void 0&&(template.layout=declared),client&&(template.client=client),c.validates&&(template.validates=!0),Object.keys(pageDefaults).length&&(template.defaults=pageDefaults),Object.keys(c.fragments).length&&(template.fragments=c.fragments),Object.keys(c.snippets).length&&(template.snippets=c.snippets),c.diagnostics.some(d=>d.severity===`error`)?{diagnostics:c.diagnostics}:{template,diagnostics:c.diagnostics}}const VOID=new Set(`area base br col embed hr img input link meta param source track wbr`.split(` `)),RAW_TEXT=/* @__PURE__ */ new Set([`script`,`style`]),RCDATA=/* @__PURE__ */ new Set([`title`,`textarea`]),INTEGRATION_POINTS=/* @__PURE__ */ new Set([`foreignobject`,`desc`,`title`,`annotation-xml`]),KEYWORDS=/^@(if|else|for|empty|switch|case|default|let|layout|input|slot|error|verbatim|assets|fragment|push|snippet|render|import)(?![\w$-])/,PLAIN_NAME=/^[\w-]+$/,LOOP_VARS$1=/* @__PURE__ */ new Set([`$index`,`$first`,`$last`,`$even`,`$odd`,`$count`]);var Fatal=class extends Error{},TemplateParser=class{s;file;i=0;text=``;textStart=0;seenOutput=!1;lineStarts=[0];diagnostics=[];ast;frames;constructor(s,file){this.s=s,this.file=file;for(let j=0;j<s.length;j++){let c=s.charCodeAt(j);(c===10||c===13&&s.charCodeAt(j+1)!==10)&&this.lineStarts.push(j+1)}this.ast={file,inputs:[],body:[]},this.frames=[{type:`root`,children:this.ast.body}]}pos(offset){let lo=0,hi=this.lineStarts.length-1;for(;lo<hi;){let mid=lo+hi+1>>1;this.lineStarts[mid]<=offset?lo=mid:hi=mid-1}return{offset,line:lo+1,column:offset-this.lineStarts[lo]+1}}span(start,end){return{start:this.pos(start),end:this.pos(end)}}err(start,end,message){this.diagnostics.push(error(this.file,this.span(start,end),message))}warn(start,end,message){this.diagnostics.push(warning(this.file,this.span(start,end),message))}fatal(start,end,message){throw this.err(start,end,message),new Fatal}expr(src,start){let r=parseExpression(src,this.file,this.pos(start));return this.diagnostics.push(...r.diagnostics),r.expr}get top(){return this.frames[this.frames.length-1]}children(){let f=this.top;return f.type===`switch`?[]:f.children}get inSnippetBody(){return this.frames.some(f=>f.type===`block`&&f.keyword===`snippet`)}flush(){this.text&&=(/\S/.test(this.text)&&!this.inSnippetBody&&(this.seenOutput=!0),this.children().push({k:`text`,value:this.text,span:this.span(this.textStart,this.i)}),``)}emit(node){this.flush(),node.k!==`let`&&node.k!==`slot-fill`&&node.k!==`snippet`&&!this.inSnippetBody&&(this.seenOutput=!0),this.children().push(node)}addText(chunk,at){this.text||(this.textStart=at),this.text+=chunk}inPre(){return this.frames.some(f=>f.type===`element`&&f.name===`pre`)}standalone(tokenStart,tokenEnd){if(this.inPre())return tokenEnd;let a=tokenStart;for(;a>0&&(this.s[a-1]===` `||this.s[a-1]===` `);)a--;if(a>0&&this.s[a-1]!==`
16
+ `&&this.s[a-1]!==`\r`)return tokenEnd;let b=tokenEnd;for(;b<this.s.length&&(this.s[b]===` `||this.s[b]===` `);)b++;if(b<this.s.length&&this.s[b]!==`
17
+ `&&this.s[b]!==`\r`)return tokenEnd;let lead=tokenStart-a;return lead&&this.text.endsWith(this.s.slice(a,tokenStart))&&(this.text=this.text.slice(0,-lead)),this.s[b]===`\r`&&b++,this.s[b]===`
18
+ `&&b++,b}run(){try{for(;this.i<this.s.length;)this.top.type===`switch`?this.switchBody():this.step();this.flush();for(let f of this.frames)(f.type===`block`||f.type===`switch`)&&this.err(f.start,f.start+1,`@${f.type===`block`?f.keyword:`switch`} is never closed — expected }`)}catch(e){if(!(e instanceof Fatal))throw e}}step(){let s=this.s,i=this.i,c=s[i];if(c===`{`&&s.startsWith(`{{--`,i)){let end=s.indexOf(`--}}`,i+4);end<0&&this.fatal(i,i+4,`template comment is never closed — expected --}}`),this.i=end+4}else if(c===`{`&&s[i+1]===`{`)this.interp(i,`text`);else{if(c===`<`){if(s.startsWith(`<!--`,i))return this.htmlComment(i);if(s[i+1]===`/`&&/[A-Za-z]/.test(s[i+2]??``))return this.closeTag(i);if(/[A-Za-z]/.test(s[i+1]??``))return this.openTag(i);s[i+1]===`{`&&this.fatal(i,i+2,`tag names can't be interpolated`)}if(c===`@`){let m=KEYWORDS.exec(s.slice(i,i+12));if(m&&this.block(m[1],i))return}c===`}`&&this.frames.some(f=>f.type===`block`)?this.closeBlock(i):(this.addText(c,i),this.i++)}}interpSource(i){let at=i+2,j=at,quote=``;for(;j<this.s.length;){let ch=this.s[j];if(quote)ch===`\\`?j++:ch===quote&&(quote=``);else if(ch===`'`||ch===`"`)quote=ch;else if(ch===`}`&&this.s[j+1]===`}`)return{src:this.s.slice(at,j),at,end:j+2};j++}this.fatal(i,i+2,`interpolation is never closed — expected }}`)}interp(i,ctx){let{src,at,end}=this.interpSource(i),expr=this.expr(src,at);expr&&this.emit({k:`interp`,expr,ctx,span:this.span(i,end)}),this.i=end}textWithInterps(from,stop,ctx){let out=[],j=from,start=from;for(;j<stop;)if(this.s.startsWith(`{{--`,j)){j>start&&out.push({k:`text`,value:this.s.slice(start,j),span:this.span(start,j)});let end=this.s.indexOf(`--}}`,j+4);j=start=end<0||end>stop?stop:end+4}else if(this.s.startsWith(`{{`,j)){j>start&&out.push({k:`text`,value:this.s.slice(start,j),span:this.span(start,j)});let{src,at,end}=this.interpSource(j),expr=this.expr(src,at);expr&&out.push({k:`interp`,expr,ctx,span:this.span(j,end)}),j=start=end}else j++;return stop>start&&out.push({k:`text`,value:this.s.slice(start,stop),span:this.span(start,stop)}),out}htmlComment(i){let end=this.s.indexOf(`-->`,i+4);end<0&&this.fatal(i,i+4,`HTML comment is never closed — expected -->`),this.emit({k:`comment`,children:this.textWithInterps(i+4,end,`comment`),span:this.span(i,end+3)}),this.i=end+3}openTag(i){let s=this.s,m=/^<([A-Za-z][\w:.-]*)/.exec(s.slice(i,i+200)),tag=m[1],j=i+m[0].length,parent=this.frames.findLast(f=>f.type===`element`),lower=tag.toLowerCase(),foreign=!!parent?.el.foreign&&!INTEGRATION_POINTS.has(parent.el.tag.toLowerCase())||lower===`svg`||lower===`math`,attrs=[],selfClosing=!1;for(;;){for(;j<s.length&&/\s/.test(s[j]);)j++;if(j>=s.length&&this.fatal(i,i+m[0].length,`<${tag}> is never closed — expected >`),s[j]===`>`){j++;break}if(s[j]===`/`&&s[j+1]===`>`){selfClosing=!0,j+=2;break}j=this.attr(j,attrs)}this.i=j;let name=foreign?tag:lower,el={k:`element`,tag,attrs,children:[],foreign,void:!foreign&&VOID.has(lower),selfClosing,span:this.span(i,j)};if(!foreign&&lower===`slot`){let nameAttr=attrs.find(a=>a.name===`name`&&a.kind!==`bind`),slotName=nameAttr?.kind===`static`?String(nameAttr.parts?.[0]??``):void 0;nameAttr&&nameAttr.kind!==`static`&&this.err(nameAttr.span.start.offset,nameAttr.span.end.offset,`a slot name must be plain text`);let offers=[];for(let a of attrs)a!==nameAttr&&(a.kind===`bind`&&a.expr?offers.push({name:a.name,expr:a.expr,span:a.span}):a.kind!==`bind`&&this.err(a.span.start.offset,a.span.end.offset,`<slot> takes name="…" and [value]="…" bindings only, not ${a.name}`));let node={k:`slot-outlet`,name:slotName,offers,fallback:[],span:el.span};this.emit(node),selfClosing||this.frames.push({type:`slot`,children:node.fallback,tag:`slot`,start:i})}else if(!foreign&&lower===`stack`){let nameAttr=attrs.find(a=>a.name===`name`),name=nameAttr?.kind===`static`?String(nameAttr.parts?.[0]??``):``;PLAIN_NAME.test(name)||this.err(i,j,`<stack> needs name="…" in letters, digits, - and _`);let node={k:`stack`,name,children:[],span:el.span};this.emit(node),selfClosing||this.frames.push({type:`slot`,children:node.children,tag:`stack`,start:i})}else if(this.emit(el),!(el.void||selfClosing)){if(RAW_TEXT.has(lower)||!foreign&&RCDATA.has(lower)){let end=RegExp(`</${lower}(?=[\\t\\n\\f\\r />])`,`i`);end.lastIndex=0;let found=end.exec(s.slice(j)),close=found?j+found.index:-1,stop=close<0?s.length:close;if(RAW_TEXT.has(lower)){let content=s.slice(j,stop);foreign&&content.includes(`<`)?this.err(j,stop,`markup isn't allowed inside <${lower}> in SVG or MathML — move the code to a separate file`):(/<!\[CDATA\[/i.test(content)||lower===`script`&&/<!--/.test(content)&&/<script/i.test(content))&&this.err(j,stop,`this <${lower}> content (<!-- with <script, or CDATA) is read differently by browsers — move it to a separate file`)}if(el.children=this.textWithInterps(j,stop,RAW_TEXT.has(lower)?`raw-text`:`rcdata`),close<0){this.i=s.length;return}let gt=s.indexOf(`>`,close);this.i=gt<0?s.length:gt+1}else this.frames.push({type:`element`,el,children:el.children,name})}}attr(j,attrs){let s=this.s,start=j;for(s.startsWith(`{{`,j)&&this.fatal(j,j+2,`attribute names can't be interpolated`);j<s.length&&!/[\s"'>/=]/.test(s[j]);)s.startsWith(`{{`,j)&&this.fatal(j,j+2,`attribute names can't be interpolated`),j++;j===start&&this.fatal(j,j+1,`unexpected '${s[j]}' in a tag`);let raw=s.slice(start,j),k=j;for(;k<s.length&&/[ \t]/.test(s[k]);)k++;if(s[k]!==`=`)return attrs.push(this.classify(raw,void 0,start,j,!1)),j;for(k++;k<s.length&&/\s/.test(s[k]);)k++;let q=s[k];if(q===`"`||q===`'`){let close=s.indexOf(q,k+1);return close<0&&this.fatal(start,k+1,`the value of ${raw} is never closed — expected ${q}`),attrs.push(this.classify(raw,{from:k+1,to:close},start,close+1,!0)),close+1}let e=k;for(;e<s.length&&!/[\s>]/.test(s[e]);)e++;return s.slice(k,e).includes(`{{`)&&this.fatal(k,e,`quote the value of ${raw}: an interpolated attribute must be in quotes`),attrs.push(this.classify(raw,{from:k,to:e},start,e,!1)),e}classify(raw,value,start,end,quoted){let span=this.span(start,end),binding=/^\[(?:(class)\.([\w-]+)|(style)\.([\w-]+)(?:\.(\w+))?|([^\]]+))\]$/.exec(raw);if(binding){value||this.fatal(start,end,`${raw} needs a value: ${raw}="expression"`);let src=this.s.slice(value.from,value.to);src.includes(`{{`)&&this.fatal(value.from,value.to,`${raw} takes an expression, without {{ }}`);let expr=this.expr(src,value.from),[,cls,clsName,sty,styName,unit,bind]=binding;return cls?{name:clsName,kind:`class`,expr,quoted,span}:sty?{name:styName,kind:`style`,expr,unit,quoted,span}:{name:bind,kind:`bind`,expr,quoted,span}}if(!value)return{name:raw,kind:`bare`,quoted:!1,span};let parts=[];for(let n of this.textWithInterps(value.from,value.to,`text`))n.k===`text`?parts.push(n.value):n.k===`interp`&&parts.push(n.expr);return{name:raw,kind:parts.some(p=>typeof p!=`string`)?`interp`:`static`,parts:parts.length?parts:[``],quoted,span}}closeTag(i){let m=/^<\/([A-Za-z][\w:.-]*)\s*>/.exec(this.s.slice(i,i+200));m||this.fatal(i,i+2,`malformed closing tag`),this.i=i+m[0].length;let tag=m[1];for(let f=this.frames.length-1;f>0;f--){let frame=this.frames[f];if(frame.type===`block`||frame.type===`switch`||frame.type===`root`)break;if(frame.type===`slot`?tag.toLowerCase()===frame.tag:frame.el.foreign?frame.name===tag:frame.name===tag.toLowerCase()){this.flush(),this.frames.length=f;return}}this.warn(i,this.i,`</${tag}> closes nothing`)}snippetOrRender(kw,i,after){let m=/^\s+([A-Za-z_$][\w$]*)\s*\(/.exec(this.s.slice(after,after+200));if(!m)return!1;let name=m[1],p=this.parens(after+m[0].length-1,`@${kw} ${name}`),parts=splitArgs(p.src,p.at);if(kw===`render`){let args=parts.flatMap(a=>{let e=this.expr(a.src,a.at);return e?[e]:[]});return this.i=this.standalone(i,p.end),this.emit({k:`render`,name,args,span:this.span(i,p.end)}),!0}let params=[];for(let a of parts){let pm=/^\s*([A-Za-z_$][\w$]*)\s*(?:=\s*([\s\S]+?))?\s*$/.exec(a.src);if(!pm){this.err(a.at,a.at+a.src.length,`expected a parameter name, or name = literal`);continue}let param={name:pm[1]};if(pm[2]!==void 0){let at=a.at+a.src.indexOf(pm[2],pm[1].length),e=this.expr(pm[2],at),literal=literalOf(e);literal===void 0?e&&this.err(at,at+pm[2].length,`a parameter default must be a literal`):param.default=literal}param.default===void 0&&params.some(q=>q.default!==void 0)&&this.err(a.at,a.at+a.src.length,`a parameter without a default must come before those with one`),params.push(param)}this.frames.length>1&&this.err(i,p.end,`@snippet goes at the top level of a template, not inside an element or block`);let brace=this.openBrace(p.end,`@snippet ${name}(…)`),resume=this.standalone(i,brace),node={k:`snippet`,name,params,body:[],span:this.span(i,brace)};return this.emit(node),this.frames.push({type:`block`,children:node.body,node,keyword:`snippet`,start:i}),this.i=resume,!0}typeImport(i,after){let br=/[\r\n]/.exec(this.s.slice(after)),eol=br?after+br.index:this.s.length,line=this.s.slice(after,eol),isType=/^\s+type\b/.test(line),importShaped=/^\s+(?:\{[^}]*\}|\*\s+as\s+[A-Za-z_$][\w$]*|[A-Za-z_$][\w$]*(?:\s*,\s*(?:\{[^}]*\}|\*\s+as\s+[A-Za-z_$][\w$]*))?)\s+from\s*['"]/.test(line);return!isType&&!importShaped?!1:(!isType||!/^\s+type\s+[\s\S]+\bfrom\s*(['"])[^'"]+\1\s*;?\s*$/.test(line)?this.err(i,eol,`only @import type … from '…' is allowed: templates take types, not values`):this.frames.length>1?this.err(i,eol,`@import type goes at the top level of a template`):(this.ast.typeImports??=[]).push(`import${line.replace(/;\s*$/,``).trimEnd()}`),this.i=this.standalone(i,eol),!0)}parens(j,what){this.s[j]!==`(`&&this.fatal(j,j+1,`expected ( after ${what}`);let depth=0,quote=``;for(let k=j;k<this.s.length;k++){let ch=this.s[k];if(quote)ch===`\\`?k++:ch===quote&&(quote=``);else if(ch===`'`||ch===`"`)quote=ch;else if(ch===`(`)depth++;else if(ch===`)`&&--depth===0)return{src:this.s.slice(j+1,k),at:j+1,end:k+1}}this.fatal(j,j+1,`${what} ( is never closed — expected )`)}skipWs(j){for(;j<this.s.length&&/\s/.test(this.s[j]);)j++;return j}openBrace(j,what){return j=this.skipWs(j),this.s[j]!==`{`&&this.fatal(j,j+1,`expected { after ${what}`),j+1}splitHeader(src,at){let out=[],quote=``,start=0;for(let k=0;k<src.length;k++){let ch=src[k];quote?ch===`\\`?k++:ch===quote&&(quote=``):ch===`'`||ch===`"`?quote=ch:ch===`;`&&(out.push({src:src.slice(start,k),at:at+start}),start=k+1)}return out.push({src:src.slice(start),at:at+start}),out}stringArg(src,at,what){let m=/^\s*(['"])([^'"]*)\1\s*$/.exec(src);return m||this.fatal(at,at+src.length,`${what} takes a quoted name`),m[2]}block(kw,i){let s=this.s,after=i+1+kw.length,next=this.skipWs(after),ch=s[next];switch(kw){case`if`:case`for`:case`switch`:case`slot`:case`error`:case`layout`:case`assets`:case`fragment`:case`push`:if(ch!==`(`)return!1;break;case`verbatim`:if(ch!==`{`)return!1;break;case`let`:case`input`:if(!/[ \t]/.test(s[after]??``))return!1;break;case`else`:case`empty`:case`case`:case`default`:if(ch!==`{`&&ch!==`(`&&!(kw===`else`&&s.startsWith(`if`,next)))return!1;this.fatal(i,after,`@${kw} has no matching ${kw===`else`?`@if`:kw===`empty`?`@for`:`@switch`}`)}if(kw===`layout`)return this.layout(i,next);if(kw===`input`)return this.input(i,after);if(kw===`let`)return this.let(i,after);if(kw===`verbatim`)return this.verbatim(i,next);if(kw===`snippet`||kw===`render`)return this.snippetOrRender(kw,i,after);if(kw===`import`)return this.typeImport(i,after);if(kw===`assets`){let p=this.parens(next,`@assets`),entry=this.stringArg(p.src,p.at,`@assets`);return this.i=this.standalone(i,p.end),this.emit({k:`assets`,entry,span:this.span(i,p.end)}),!0}let p=this.parens(next,`@${kw}`),brace=this.openBrace(p.end,`@${kw} (…)`),resume=this.standalone(i,brace);if(kw===`if`){let branch=this.ifBranch(p.src,p.at),node={k:`if`,branches:[branch],span:this.span(i,brace)};this.emit(node),this.frames.push({type:`block`,children:branch.body,next:`else`,node,keyword:`if`,start:i})}else if(kw===`for`){let node=this.forHeader(p.src,p.at,i,brace);this.emit(node),this.frames.push({type:`block`,children:node.body,next:`empty`,node,keyword:`for`,start:i})}else if(kw===`error`){let field=this.stringArg(p.src,p.at,`@error`),at=this.span(p.at,p.at+p.src.length),cond={kind:`path`,root:`$errors`,segments:[{computed:{kind:`literal`,value:field,span:at},optional:!0}],span:at},spot=hidden=>({k:`element`,tag:`span`,attrs:[{name:`data-kick-error`,kind:`static`,parts:[field],quoted:!0,span:at},{name:`aria-live`,kind:`static`,parts:[`polite`],quoted:!0,span:at},...hidden?[{name:`hidden`,kind:`bare`,quoted:!1,span:at}]:[]],children:[],foreign:!1,void:!1,selfClosing:!1,span:at}),shown=spot(!1),node={k:`if`,branches:[{cond,alias:`$message`,body:[shown]},{body:[spot(!0)]}],span:this.span(i,brace)};this.emit(node),this.frames.push({type:`block`,children:shown.children,node,keyword:`error`,start:i})}else if(kw===`switch`){let node={k:`switch`,on:this.expr(p.src,p.at)??{kind:`literal`,value:null,span:this.span(p.at,p.at)},cases:[],span:this.span(i,brace)};this.emit(node),this.frames.push({type:`switch`,node,start:i})}else if(kw===`fragment`||kw===`push`){let name=this.stringArg(p.src,p.at,`@${kw}`);PLAIN_NAME.test(name)||this.err(p.at,p.end,`@${kw} names use letters, digits, - and _`);let node={k:kw,name,body:[],span:this.span(i,brace)};this.emit(node),this.frames.push({type:`block`,children:node.body,node,keyword:kw,start:i})}else{let[head,letPart,extra]=this.splitHeader(p.src,p.at),name=/^\s*default\s*$/.test(head.src)?``:this.stringArg(head.src,head.at,`@slot`),lets=[];if(letPart){let m=/^\s*let\s+(.*)$/s.exec(letPart.src),items=m?m[1].split(`,`).map(x=>/^\s*([A-Za-z_$][\w$]*)\s*(?:=\s*([A-Za-z_$][\w$]*)\s*)?$/.exec(x)):[];if(!m||items.some(x=>!x))this.err(letPart.at,letPart.at+letPart.src.length,"expected `let name` or `let name = offered` after ;");else for(let x of items)lets.push({name:x[1],from:x[2]??x[1]})}extra&&this.err(extra.at,extra.at+1,`unexpected ; in @slot`);let node={k:`slot-fill`,name,lets,body:[],span:this.span(i,brace)};this.emit(node),this.frames.push({type:`block`,children:node.body,node,keyword:`slot`,start:i})}return this.i=resume,!0}ifBranch(src,at){let parts=this.splitHeader(src,at),branch={cond:this.expr(parts[0].src,parts[0].at),body:[]};if(parts[1]){let m=/^\s*as\s+([A-Za-z_$][\w$]*)\s*$/.exec(parts[1].src);m?branch.alias=m[1]:this.err(parts[1].at,parts[1].at+parts[1].src.length,"expected `as name` after ;")}return parts.length>2&&this.err(parts[2].at,parts[2].at+1,`unexpected ; in @if`),branch}forHeader(src,at,start,end){let parts=this.splitHeader(src,at),head=parts[0],m=/^(\s*)(?:\[\s*([A-Za-z_$][\w$]*)\s*,\s*([A-Za-z_$][\w$]*)\s*\]|([A-Za-z_$][\w$]*))\s+of\s+/.exec(head.src);m||this.fatal(head.at,head.at+head.src.length,"@for needs `item of items`");let item=m[4]??[m[2],m[3]],ofSrc=head.src.slice(m[0].length),of=this.expr(ofSrc,head.at+m[0].length)??{kind:`literal`,value:null,span:this.span(at,at)},lets={};for(let part of parts.slice(1)){let t=part.src.trim();if(t.startsWith(`track`))this.expr(part.src.replace(/^\s*track\b/,w=>` `.repeat(w.length)),part.at);else if(t.startsWith(`let`)){let body=part.src.replace(/^\s*let\b/,``);for(let decl of body.split(`,`)){let d=/^\s*([A-Za-z_$][\w$]*)\s*=\s*(\$\w+)\s*$/.exec(decl);!d||!LOOP_VARS$1.has(d[2])?this.err(part.at,part.at+part.src.length,`unknown loop variable in \`${decl.trim()}\` — use ${[...LOOP_VARS$1].join(`, `)}`):lets[d[1]]=d[2]}}else this.err(part.at,part.at+part.src.length,`expected track or let in @for, found \`${t}\``)}return{k:`for`,item,of,lets,body:[],span:this.span(start,end)}}closeBlock(i){let f=this.frames.length-1;for(;this.frames[f].type!==`block`;)f--;let frame=this.frames[f],s=this.s,j=this.skipWs(i+1),branch,empty=!1,end=i+1;if(frame.next===`else`&&/^@else(?![\w$-])/.test(s.slice(j,j+6))){let k=this.skipWs(j+5);if(s.startsWith(`if`,k)&&/[\s(]/.test(s[k+2]??``)){let p=this.parens(this.skipWs(k+2),`@else if`);branch=this.ifBranch(p.src,p.at),k=p.end}else branch={body:[]};end=this.openBrace(k,`@else`)}else frame.next===`empty`&&/^@empty(?![\w$-])/.test(s.slice(j,j+7))&&(empty=!0,end=this.openBrace(j+6,`@empty`));let resume=this.standalone(i,end);if(this.flush(),this.frames.length=f,this.i=resume,branch){let node=frame.node;node.branches.push(branch),this.frames.push({type:`block`,children:branch.body,next:branch.cond?`else`:void 0,node,keyword:`else`,start:j})}else if(empty){let node=frame.node;node.empty=[],this.frames.push({type:`block`,children:node.empty,node,keyword:`empty`,start:j})}}switchBody(){let s=this.s,j=this.skipWs(this.i),frame=this.top;if(j>=s.length){this.i=j;return}if(s[j]===`}`){this.frames.pop(),this.i=this.standalone(j,j+1);return}let m=/^@(case|default)(?![\w$-])/.exec(s.slice(j,j+9));m||this.fatal(j,j+1,`only @case and @default go inside @switch`);let k=j+m[0].length,value;if(m[1]===`case`){let p=this.parens(this.skipWs(k),`@case`);value=this.expr(p.src,p.at),k=p.end}else frame.node.default&&this.err(j,k,`@switch has two @default blocks`);let brace=this.openBrace(k,`@${m[1]}`),body=[];m[1]===`case`?frame.node.cases.push({value:value??frame.node.on,body}):frame.node.default=body,this.i=this.standalone(j,brace),this.frames.push({type:`block`,children:body,node:frame.node,keyword:m[1],start:j})}verbatim(i,brace){let depth=0,quote=``;for(let k=brace;k<this.s.length;k++){let ch=this.s[k];if(quote)ch===`\\`?k++:ch===quote&&(quote=``);else if(ch===`'`||ch===`"`||ch==="`")quote=ch;else if(ch===`{`)depth++;else if(ch===`}`&&--depth===0){let resume=this.standalone(i,k+1);return this.emit({k:`verbatim`,text:this.s.slice(brace+1,k),span:this.span(i,k+1)}),this.i=resume,!0}}this.fatal(i,brace+1,`@verbatim is never closed — expected }`)}layout(i,at){let p=this.parens(at,`@layout`);return this.seenOutput||this.frames.length>1?this.err(i,p.end,`@layout must come before any output`):this.ast.layout===void 0?(this.ast.layout=/^\s*none\s*$/.test(p.src)?null:this.stringArg(p.src,p.at,`@layout`),this.ast.layoutSpan=this.span(i,p.end)):this.err(i,p.end,`a template has one @layout`),this.i=this.standalone(i,p.end),!0}input(i,after){let eol=this.s.indexOf(`
19
+ `,after);eol<0&&(eol=this.s.length);let line=this.s.slice(after,eol).replace(/\r$/,``),head=/^\s*([A-Za-z_$][\w$]*)\s*/.exec(line);head||this.fatal(i,eol,`@input needs a name: @input name, @input name: Type or @input name = value`);let rest=line.slice(head[0].length),type;if(rest.startsWith(`:`)){let end=typeEnd(rest,1);type=rest.slice(1,end).trim(),rest=rest.slice(end).replace(/^\/\/.*$/,``),type||this.err(i,eol,`@input name: expects a type after the colon`)}let dm=/^\s*(?:=\s*(.*?))?\s*$/.exec(rest);dm||this.fatal(i,eol,`unexpected '${rest.trim()}' after @input ${head[1]}`);let m=[line,head[1],dm[1]];this.frames.length>1&&this.err(i,eol,`@input goes at the top of a component, outside any block`);let decl={name:m[1],span:this.span(i,after+line.length)};if(type&&(decl.type=type),m[2]!==void 0){let at=after+line.lastIndexOf(m[2]),e=this.expr(m[2],at),literal=literalOf(e);e&&literal===void 0?this.err(at,at+m[2].length,`an @input default must be a literal: a string, number, true, false or null`):e&&(decl.default={value:literal,span:e.span})}return this.ast.inputs.some(d=>d.name===decl.name)&&this.err(i,eol,`@input ${decl.name} is declared twice`),this.ast.inputs.push(decl),this.i=this.standalone(i,after+line.length),!0}let(i,after){let quote=``;for(let k=after;k<this.s.length;k++){let ch=this.s[k];if(quote)ch===`\\`?k++:ch===quote&&(quote=``);else if(ch===`'`||ch===`"`)quote=ch;else if(ch===`;`){let src=this.s.slice(after,k),m=/^\s*([A-Za-z_$][\w$]*)\s*=/.exec(src);m||this.fatal(i,k,`@let needs a name: @let name = expression;`);let expr=this.expr(src.slice(m[0].length),after+m[0].length),resume=this.standalone(i,k+1);return expr&&this.emit({k:`let`,name:m[1],expr,span:this.span(i,k+1)}),this.i=resume,!0}}this.fatal(i,after,`@let is never ended — expected ;`)}};function parse(source,file){let p=new TemplateParser(source.charCodeAt(0)===65279?source.slice(1):source,file);return p.run(),{ast:p.ast,diagnostics:p.diagnostics}}function splitArgs(src,at){if(!src.trim())return[];let out=[],depth=0,quote=``,start=0;for(let k=0;k<src.length;k++){let c=src[k];quote?c===`\\`?k++:c===quote&&(quote=``):c===`'`||c===`"`?quote=c:c===`(`||c===`[`?depth++:c===`)`||c===`]`?depth--:c===`,`&&depth===0&&(out.push({src:src.slice(start,k),at:at+start}),start=k+1)}return out.push({src:src.slice(start),at:at+start}),out}function literalOf(e){if(e?.kind===`literal`)return e.value;if(e?.kind===`unary`&&e.op===`-`&&e.arg.kind===`literal`&&typeof e.arg.value==`number`)return-e.arg.value}function templateEnd(src,at){for(let k=at+1;k<src.length;k++){let c=src[k];if(c===`\\`)k++;else if(c==="`")return k;else if(c===`$`&&src[k+1]===`{`){let depth=1;for(k+=2;k<src.length&&depth>0;k++){let d=src[k];d==="`"?k=templateEnd(src,k):d===`{`?depth++:d===`}`&&depth--}k--}}return src.length}function typeEnd(src,at){let depth=0,quote=``;for(let k=at;k<src.length;k++){let c=src[k];if(quote)c===`\\`?k++:c===quote&&(quote=``);else if(c===`/`&&src[k+1]===`*`){let close=src.indexOf(`*/`,k+2);k=close<0?src.length:close+1}else if(c===`/`&&src[k+1]===`/`)return k;else if(c==="`")k=templateEnd(src,k);else if(c===`'`||c===`"`)quote=c;else if(`<([{`.includes(c))depth++;else if(`>)]}`.includes(c)&&(c!==`>`||src[k-1]!==`=`))depth--;else if(c===`=`&&depth===0&&src[k+1]!==`>`)return k}return src.length}const LOOP_VARS=/* @__PURE__ */ new Set([`$index`,`$first`,`$last`,`$even`,`$odd`,`$count`]),level=()=>({present:!1,nonNull:!1,loop:!1,opaque:!1,props:/* @__PURE__ */ new Map});var Summarizer=class{roots=/* @__PURE__ */ new Map;scopes=[/* @__PURE__ */ new Map];tested=[];frags=[];snippet;snippetReads=/* @__PURE__ */ new Map;snippetCalls=/* @__PURE__ */ new Map;pageCalls=/* @__PURE__ */ new Set;fragmentCalls=/* @__PURE__ */ new Map;fragments=/* @__PURE__ */ new Map;bind(name,src,steps=[]){let b={depth:this.scopes.length-1,src,steps};return this.scopes[this.scopes.length-1].set(name,b),b}lookup(name){for(let i=this.scopes.length-1;i>=0;i--){let b=this.scopes[i].get(name);if(b)return b}}scoped(fn){this.scopes.push(/* @__PURE__ */ new Map);try{fn()}finally{this.scopes.pop()}}path(e,mode,loop){if(LOOP_VARS.has(e.root))return null;let steps=[],own=[mode],opaqueEnd=!1,skippable=!1;for(let s of e.segments)s.optional&&(opaqueEnd||(own[own.length-1]=`soft`),skippable=!0),s.computed?(this.expr(s.computed,skippable?`soft`:`use`),opaqueEnd=!0):opaqueEnd||(steps.push({p:s.name}),own.push(mode));let b=this.lookup(e.root);if(!b&&FORM_GLOBALS.has(e.root))return null;let pages=b?this.resolve(b,steps,own):[{root:e.root,steps,modes:own}];for(let page of pages){let read=this.guarded({...page,opaqueEnd,loop});this.recordInto(this.snippet?this.snippetReads.get(this.snippet):this.roots,read)}for(let f of this.frags)if(b)for(let r of this.resolveFor(f.depth,e.root,b,steps,own)){let read=this.guarded({...r.read,opaqueEnd,loop},f.tested);r.need?(read.modes[0]===`soft`&&(read.modes[0]=`test`),this.recordInto(f.needs,read)):this.recordInto(f.reads,read)}else{let read={root:e.root,steps,modes:own,opaqueEnd,loop};this.recordInto(f.reads,this.guarded(read,f.tested))}return opaqueEnd?null:b?{src:{k:`var`,name:e.root,b},steps}:{src:{k:`data`,root:e.root},steps}}resolve(b,steps,modes){return this.resolveFor(-1,``,b,steps,modes).map(r=>r.read)}resolveFor(depth,name,b,steps,modes){let out=[],seen=/* @__PURE__ */ new Map,walk=(curName,cur,chain)=>{if(cur.src){let key=JSON.stringify([curName,cur.depth,cur.steps,cur.softAt,chain.map(c=>[c.steps,c.softAt])]),keys=seen.get(cur.src)??/* @__PURE__ */ new Set;if(keys.has(key))return;seen.set(cur.src,keys.add(key))}if(cur.depth<depth){out.push({need:!0,read:joined(curName,chain,steps,modes)});return}let src=cur.src;if(!src)return;if(src.k===`either`){for(let o of src.options){let via={depth:cur.depth,src:o.src,steps:[...o.steps,...cur.steps]};o.soft&&(via.softAt=o.steps.length),walk(curName,via,chain)}return}let next=[...chain,cur];src.k===`data`?out.push({need:!1,read:joined(src.root,next,steps,modes)}):walk(src.name,src.b,next)};return walk(name,b,[]),out}guarded(r,from=0){let modes=[...r.modes];for(let frame of this.tested.slice(from))for(let t of frame)if(!(t.root!==r.root||t.steps.length>r.steps.length)&&t.steps.every((s,i)=>sameStep(s,r.steps[i])))for(let i=0;i<=t.steps.length;i++)modes[i]===`use`&&(modes[i]=`test`);return{...r,modes}}recordInto(roots,r){let lv=roots.get(r.root);lv||roots.set(r.root,lv=level());let touch=(l,m)=>{(m===`use`||m===`test`)&&(l.present=!0),m===`use`&&(l.nonNull=!0)};touch(lv,r.modes[0]);for(let[i,s]of r.steps.entries()){let next;`p`in s?(next=lv.props.get(s.p),next||lv.props.set(s.p,next=level())):next=`item`in s?lv.item??=level():lv.pair??=level(),lv=next,touch(lv,r.modes[i+1])}r.opaqueEnd&&(lv.opaque=!0),r.loop&&(lv.loop=!0,r.loop===`pair`?lv.pair??=level():lv.item??=level())}expr(e,mode,loop){switch(e.kind){case`literal`:return null;case`path`:return this.path(e,mode,loop);case`unary`:{let m=mode===`soft`?`use`:mode;return this.expr(e.arg,e.op===`!`&&m===`use`?`test`:m),null}case`binary`:{let m=mode===`soft`?`use`:mode;return this.expr(e.left,m),this.expr(e.right,m),null}case`logical`:if(e.op===`??`){let left=this.expr(e.left,`soft`,loop);return either(left&&{...left,soft:!0},this.expr(e.right,mode,loop))}if(e.op===`&&`){this.expr(e.left,mode===`use`?`test`:mode,loop);let right=null;return this.guardedBy([e.left],()=>right=this.expr(e.right,mode,loop)),right}return either(this.expr(e.left,mode===`use`?`test`:mode,loop),this.expr(e.right,mode,loop));case`conditional`:this.expr(e.test,mode===`use`?`test`:mode);let yes=null;return this.guardedBy([e.test],()=>yes=this.expr(e.whenTrue,mode,loop)),either(yes,this.expr(e.whenFalse,mode,loop));case`pipe`:this.expr(e.input,mode);for(let a of e.args)this.expr(a,`use`);return null}}guardedBy(conds,fn){this.tested.push(conds.flatMap(c=>testedPaths(c,n=>this.lookup(n),this)));try{fn()}finally{this.tested.pop()}}dataPaths(root,steps){let b=this.lookup(root);return b?this.resolve(b,steps,[...steps.map(()=>`use`),`use`]).map(r=>({root:r.root,steps:r.steps})):FORM_GLOBALS.has(root)||LOOP_VARS.has(root)?[]:[{root,steps}]}nodes(list){let stack=[{list,i:0}];for(;stack.length;){let f=stack[stack.length-1];if(f.i>=f.list.length){stack.pop();continue}let n=f.list[f.i++];if(n.k===`element`){for(let a of n.attrs){a.expr&&this.expr(a.expr,`use`);for(let p of a.parts??[])typeof p!=`string`&&this.expr(p,`use`)}stack.push({list:n.children,i:0})}else this.node(n)}}bindTo(name,to,extra=[]){if(!to)this.bind(name,null);else{let b=this.bind(name,to.src,[...to.steps,...extra]);to.soft&&(b.softAt=to.steps.length)}}node(n){switch(n.k){case`interp`:this.expr(n.expr,`use`);return;case`comment`:this.nodes(n.children);return;case`if`:{let negated=[];for(let br of n.branches){let to=br.cond?this.expr(br.cond,`test`):null,guards=[...br.cond?[br.cond]:[],...negated];this.scoped(()=>{br.alias&&this.bindTo(br.alias,to),this.guardedBy(guards,()=>this.nodes(br.body))}),br.cond?.kind===`unary`&&br.cond.op===`!`&&negated.push(br.cond.arg)}return}case`for`:{let pairs=Array.isArray(n.item),to=this.expr(n.of,`test`,pairs?`pair`:`item`);this.scoped(()=>{pairs?(this.bind(n.item[0],null),this.bindTo(n.item[1],to,[{pair:!0}])):this.bindTo(n.item,to,[{item:!0}]);for(let name of Object.keys(n.lets))this.bind(name,null);this.nodes(n.body)}),n.empty&&this.scoped(()=>this.nodes(n.empty));return}case`switch`:this.expr(n.on,`use`);for(let c of n.cases)this.expr(c.value,`use`),this.scoped(()=>this.nodes(c.body));n.default&&this.scoped(()=>this.nodes(n.default));return;case`let`:this.bindTo(n.name,this.expr(n.expr,`test`));return;case`slot-outlet`:for(let o of n.offers)this.expr(o.expr,`use`);this.scoped(()=>{for(let o of n.offers)this.bind(o.name,null);this.nodes(n.fallback)});return;case`slot-fill`:this.scoped(()=>{for(let l of n.lets)this.bind(l.name,null);this.nodes(n.body)});return;case`push`:this.scoped(()=>this.nodes(n.body));return;case`fragment`:{let own=this.fragments.get(n.name)??{needs:/* @__PURE__ */ new Map,reads:/* @__PURE__ */ new Map};this.fragments.set(n.name,own),this.frags.push({name:n.name,...own,depth:this.scopes.length,tested:this.tested.length});try{this.scoped(()=>this.nodes(n.body))}finally{this.frags.pop()}return}case`snippet`:{let outer=this.scopes.splice(0);this.scopes.push(/* @__PURE__ */ new Map),this.snippet=n.name,this.snippetReads.has(n.name)||this.snippetReads.set(n.name,/* @__PURE__ */ new Map);try{for(let p of n.params)this.bind(p.name,null);this.nodes(n.body)}finally{this.snippet=void 0,this.scopes.splice(0,this.scopes.length,...outer)}return}case`render`:for(let a of n.args)this.expr(a,`use`);this.snippet?add(this.snippetCalls,this.snippet,n.name):this.pageCalls.add(n.name);for(let f of this.frags)add(this.fragmentCalls,f.name,n.name);return;default:return}}};function joined(root,chain,steps,modes){let outer=chain.toReversed(),allSteps=[...outer.flatMap(c=>c.steps),...steps],allModes=fixModes([...outer.flatMap(c=>c.steps.map(()=>`test`)),...modes],allSteps.length),at=0;for(let c of outer){if(c.softAt!==void 0)for(let i=0;i<=at+c.softAt;i++)allModes[i]=`soft`;at+=c.steps.length}return{root,steps:allSteps,modes:allModes}}function either(...targets){let options=targets.filter(t=>t!==null);return options.length<2?options[0]??null:{src:{k:`either`,options},steps:[]}}function add(map,key,value){let set=map.get(key)??/* @__PURE__ */ new Set;set.add(value),map.set(key,set)}function mergeLevels(into,from){for(let[name,l]of from){let target=into.get(name);target?mergeLevel(target,l):into.set(name,cloneLevel(l))}}function cloneLevel(l){let out=level();return mergeLevel(out,l),out}function mergeLevel(into,l){into.present||=l.present,into.nonNull||=l.nonNull,into.loop||=l.loop,into.opaque||=l.opaque,mergeLevels(into.props,l.props),l.item&&(into.item?mergeLevel(into.item,l.item):into.item=cloneLevel(l.item)),l.pair&&(into.pair?mergeLevel(into.pair,l.pair):into.pair=cloneLevel(l.pair))}function fixModes(modes,n){let out=modes.slice(modes.length-(n+1));for(;out.length<n+1;)out.unshift(`use`);return out}const sameStep=(a,b)=>`p`in a?`p`in b&&a.p===b.p:`item`in a?`item`in b:`pair`in b;function testedPaths(cond,_lookup,s){let out=[],visit=e=>{if(e.kind===`logical`&&e.op===`&&`)visit(e.left),visit(e.right);else if(e.kind===`path`&&e.segments.every(x=>!x.computed)){let p=s.dataPaths(e.root,e.segments.map(x=>({p:x.name})));p.length===1&&out.push(p[0])}};return visit(cond),out}function shapeOf(l){if(l.opaque)return{k:`unknown`};if(l.pair)return{k:`pairs`,value:shapeOf(l.pair)};if(l.item)return{k:`list`,item:shapeOf(l.item)};if(l.props.size){let props={};for(let[name,child]of[...l.props].toSorted(([a],[b])=>a.localeCompare(b)))props[name]=fieldOf(child);return{k:`object`,props}}return{k:`unknown`}}function fieldOf(l){return{shape:shapeOf(l),optional:!l.present,nullable:!l.nonNull||l.loop}}function fieldsOf(roots){let out={};for(let[name,l]of[...roots].toSorted(([a],[b])=>a.localeCompare(b)))out[name]=fieldOf(l);return out}function summarize(ast){let s=new Summarizer;s.nodes(ast.body);let declared={};for(let i of ast.inputs)declared[i.name]={...i.type?{type:i.type}:{},optional:i.default!==void 0};let reach=(called,into)=>{let seen=/* @__PURE__ */ new Set,todo=[...called];for(;todo.length;){let snippet=todo.pop();if(seen.has(snippet))continue;seen.add(snippet);let reads=s.snippetReads.get(snippet);reads&&mergeLevels(into,reads);for(let next of s.snippetCalls.get(snippet)??[])todo.push(next)}};reach(s.pageCalls,s.roots);for(let[name,called]of s.fragmentCalls){let f=s.fragments.get(name);f&&reach(called,f.reads)}let fragments={};for(let[name,f]of s.fragments)fragments[name]={needs:fieldsOf(f.needs),reads:fieldsOf(f.reads)};return{fields:fieldsOf(s.roots),declared,imports:ast.typeImports??[],fragments,...ast.layout===void 0?{}:{layout:ast.layout}}}function mergeShape(a,b){if(a.k===`unknown`)return b;if(b.k===`unknown`)return a;if(a.k===`object`&&b.k===`object`){let props={...a.props};for(let[k,v]of Object.entries(b.props))props[k]=props[k]?merge(props[k],v):v;return{k:`object`,props}}return a.k===`list`&&b.k===`list`?{k:`list`,item:mergeShape(a.item,b.item)}:a.k===`pairs`&&b.k===`pairs`?{k:`pairs`,value:mergeShape(a.value,b.value)}:{k:`unknown`}}function merge(a,b){return{shape:mergeShape(a.shape,b.shape),optional:a.optional&&b.optional,nullable:a.nullable&&b.nullable}}function mergeSummary(into,from){let fields={...into.fields};for(let[k,v]of Object.entries(from.fields))fields[k]=fields[k]?merge(fields[k],v):v;return{...into,fields,declared:mergeDeclared(into.declared,from.declared)}}function mergeDeclared(page,layout){let out={...layout};for(let[name,d]of Object.entries(page)){let l=layout[name];if(!l){out[name]=d;continue}let type=d.type??l.type,fits=!d.type||d.type===l.type;out[name]={...type?{type}:{},optional:d.optional||l.optional&&fits}}return out}export{emptyFormState as A,FORBIDDEN_NAMES as C,warning as D,positionAt as E,takeFormState as M,AST_FORMAT_VERSION as O,isUrlAttr as S,error as T,read as _,check as a,sanitizeUrl as b,VALIDATORS as c,readPipeExports as d,BUILTIN_PIPES as f,escapeJsonForScript as g,escapeHtml as h,parse as i,rememberPage as j,FORM_GLOBALS as k,VALIDATORS_TAG as l,SafeHtml as m,mergeSummary as n,decodeEntities as o,builtinPipes as p,summarize as r,BUILTIN_VALIDATORS as s,merge as t,readValidatorExports as u,safeStyleValue as v,parseExpression as w,URL_ATTRS as x,sanitizeSrcset as y};
20
+ //# sourceMappingURL=summary-EefMyOjo.js.map