@forinda/kickjs-view 0.5.0 → 0.7.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 (44) hide show
  1. package/dist/cli.d.ts +61 -2
  2. package/dist/cli.d.ts.map +1 -1
  3. package/dist/cli.js +5 -2
  4. package/dist/cli.js.map +1 -1
  5. package/dist/edge.d.ts +8 -5
  6. package/dist/edge.js +2 -2
  7. package/dist/exports-CII2eM6o.js +17 -0
  8. package/dist/exports-CII2eM6o.js.map +1 -0
  9. package/dist/file-BIua9gOB.d.ts +925 -0
  10. package/dist/file-BIua9gOB.d.ts.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-CvHG95ck.js +18 -0
  15. package/dist/format-CvHG95ck.js.map +1 -0
  16. package/dist/i18n-EriU9b68.js +12 -0
  17. package/dist/i18n-EriU9b68.js.map +1 -0
  18. package/dist/index.d.ts +12 -5
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +2 -2
  21. package/dist/index.js.map +1 -1
  22. package/dist/project-mP4NzZhQ.d.ts +50 -0
  23. package/dist/project-mP4NzZhQ.d.ts.map +1 -0
  24. package/dist/serve-Df9_MrXE.d.ts +173 -0
  25. package/dist/serve-Df9_MrXE.d.ts.map +1 -0
  26. package/dist/summary-DOhWOKmu.js +20 -0
  27. package/dist/summary-DOhWOKmu.js.map +1 -0
  28. package/package.json +12 -10
  29. package/virtual.d.ts +4 -1
  30. package/dist/ast-bZ1jJ5-w.d.ts +0 -372
  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 +0 -29
  37. package/dist/project-XUrj8cl0.d.ts.map +0 -1
  38. package/dist/rolldown-runtime-BLRzqIEa.js +0 -11
  39. package/dist/serve-fHP-Eia9.d.ts +0 -97
  40. package/dist/serve-fHP-Eia9.d.ts.map +0 -1
  41. package/dist/template-DU9sjMgd.js +0 -20
  42. package/dist/template-DU9sjMgd.js.map +0 -1
  43. package/dist/views-_eQ9NTKn.d.ts +0 -198
  44. package/dist/views-_eQ9NTKn.d.ts.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@forinda/kickjs-view",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "KickJS views — .kick templates rendered on every runtime and the edge",
5
5
  "keywords": [
6
6
  "kickjs",
@@ -37,31 +37,33 @@
37
37
  "virtual.d.ts"
38
38
  ],
39
39
  "peerDependencies": {
40
- "@forinda/kickjs": "^10.14.1"
40
+ "@forinda/kickjs": "^10.15.0"
41
41
  },
42
42
  "peerDependenciesMeta": {
43
43
  "@forinda/kickjs": {
44
44
  "optional": true
45
45
  }
46
46
  },
47
+ "dependencies": {
48
+ "@forinda/kickjs-cli-kit": "0.1.4"
49
+ },
47
50
  "devDependencies": {
48
51
  "@fastify/middie": "^9.3.6",
49
- "@swc/core": "^1.16.20",
52
+ "@swc/core": "^1.16.22",
50
53
  "@types/ejs": "^3.1.5",
51
54
  "@types/node": "^26.6.6",
52
55
  "@types/supertest": "^7.2.1",
53
- "commander": "^15.0.0",
56
+ "commander": "^15.1.0",
54
57
  "ejs": "^7.0.2",
55
58
  "express": "^5.3.0",
56
- "fastify": "^5.12.7",
59
+ "fastify": "^5.12.8",
57
60
  "h3": "2.0.8",
58
61
  "happy-dom": "^21.0.4",
59
62
  "reflect-metadata": "^0.2.2",
60
- "supertest": "^7.3.1",
63
+ "supertest": "^7.3.2",
61
64
  "typescript": "^7.0.2",
62
- "vitest": "^5.0.5",
63
- "@forinda/kickjs": "10.14.1",
64
- "@forinda/kickjs-cli-kit": "0.1.3"
65
+ "vitest": "^5.1.0",
66
+ "@forinda/kickjs": "10.15.0"
65
67
  },
66
68
  "publishConfig": {
67
69
  "access": "public"
@@ -83,7 +85,7 @@
83
85
  "scripts": {
84
86
  "build": "tsdown",
85
87
  "dev": "tsdown --watch",
86
- "test": "vitest run --passWithNoTests",
88
+ "test": "vitest run --typecheck --passWithNoTests",
87
89
  "test:watch": "vitest",
88
90
  "typecheck": "tsc --noEmit",
89
91
  "clean": "rm -rf dist .wireit",
package/virtual.d.ts CHANGED
@@ -10,9 +10,11 @@
10
10
  * ```
11
11
  */
12
12
  declare module 'virtual:kick-views' {
13
- import type { EnvPipe, Pipe, ViewsBundle } from '@forinda/kickjs-view'
13
+ import type { EnvPipe, Messages, Pipe, ViewsBundle } from '@forinda/kickjs-view'
14
14
  export const bundle: ViewsBundle | null
15
15
  export const pipes: Record<string, Pipe | EnvPipe>
16
+ /** The build's message catalogues; `undefined` in dev, where they're read from disk. */
17
+ export const messages: Messages | undefined
16
18
  /** Where component scripts are served: the Vite plugin's `clientScriptPath`. */
17
19
  export const clientScriptPath: string
18
20
  /** A `file:` URL of the folder `kick build` wrote client files to; `undefined` in dev. */
@@ -22,6 +24,7 @@ declare module 'virtual:kick-views' {
22
24
  const views: {
23
25
  bundle: ViewsBundle | null
24
26
  pipes: Record<string, Pipe | EnvPipe>
27
+ messages: Messages | undefined
25
28
  clientScriptPath: string
26
29
  clientDir: string | undefined
27
30
  validatorsFile?: string
@@ -1,372 +0,0 @@
1
-
2
- /** A point in a template: 0-based offset, 1-based line and column (UTF-16 units). */
3
- interface Pos {
4
- offset: number;
5
- line: number;
6
- column: number;
7
- }
8
- interface Span {
9
- start: Pos;
10
- end: Pos;
11
- }
12
- interface Diagnostic {
13
- file: string;
14
- span: Span;
15
- message: string;
16
- severity: 'error' | 'warning';
17
- /** The templates being rendered, outermost first, when the error came from a render. */
18
- stack?: string[];
19
- }
20
- /** The position of `offset` in `source`. */
21
- declare const positionAt: (source: string, offset: number) => Pos;
22
- /** Bumped when the shape of a checked template changes; builds and runtimes must agree. */
23
- declare const AST_FORMAT_VERSION = 1;
24
- type Literal = string | number | boolean | null;
25
- interface PathSegment {
26
- /** `.name` / `?.name` */
27
- name?: string;
28
- /** `[expr]` / `?.[expr]` */
29
- computed?: Expr;
30
- optional: boolean;
31
- }
32
- type Expr = {
33
- kind: 'literal';
34
- value: Literal;
35
- span: Span;
36
- } | {
37
- kind: 'path';
38
- root: string;
39
- segments: PathSegment[];
40
- span: Span;
41
- } | {
42
- kind: 'unary';
43
- op: '!' | '-';
44
- arg: Expr;
45
- span: Span;
46
- } | {
47
- kind: 'binary';
48
- op: '+' | '-' | '<' | '>' | '<=' | '>=' | '==' | '!=' | '===' | '!==';
49
- left: Expr;
50
- right: Expr;
51
- span: Span;
52
- } | {
53
- kind: 'logical';
54
- op: '&&' | '||' | '??';
55
- left: Expr;
56
- right: Expr;
57
- span: Span;
58
- } | {
59
- kind: 'conditional';
60
- test: Expr;
61
- whenTrue: Expr;
62
- whenFalse: Expr;
63
- span: Span;
64
- } | {
65
- kind: 'pipe';
66
- input: Expr;
67
- name: string;
68
- args: Expr[];
69
- span: Span;
70
- };
71
- /** Where an interpolation lands, which decides how its value is escaped (spec §4). */
72
- type Ctx = 'text' | 'rcdata' | 'raw-text' | 'comment';
73
- interface Attr {
74
- /** As written: `href`, `userId` (from `[userId]`), `on` (from `[class.on]`). */
75
- name: string;
76
- /**
77
- * `static` `a="x"`, `interp` `a="x{{ y }}"`, `bare` `a`, `bind` `[a]="expr"`,
78
- * `class` `[class.a]="expr"`, `style` `[style.a(.unit)]="expr"`.
79
- */
80
- kind: 'static' | 'interp' | 'bare' | 'bind' | 'class' | 'style';
81
- /** `static` / `interp`: the value, literal text and expressions in order. */
82
- parts?: Array<string | Expr>;
83
- /** `bind` / `class` / `style`: the bound expression. */
84
- expr?: Expr;
85
- /** `[style.width.px]`: `px`. */
86
- unit?: string;
87
- quoted: boolean;
88
- span: Span;
89
- }
90
- interface Element {
91
- k: 'element';
92
- /** As written. */
93
- tag: string;
94
- attrs: Attr[];
95
- children: Node[];
96
- /** Inside `<svg>` / `<math>`: names keep their case. */
97
- foreign: boolean;
98
- void: boolean;
99
- selfClosing: boolean;
100
- span: Span;
101
- }
102
- interface IfBranch {
103
- /** Absent on `@else`. */
104
- cond?: Expr;
105
- /** `@if (x; as y)` */
106
- alias?: string;
107
- body: Node[];
108
- }
109
- type LoopVar = '$index' | '$first' | '$last' | '$even' | '$odd' | '$count';
110
- type Node = {
111
- k: 'text';
112
- value: string;
113
- span: Span;
114
- } | {
115
- k: 'interp';
116
- expr: Expr;
117
- ctx: Ctx;
118
- span: Span;
119
- } | Element | {
120
- k: 'comment';
121
- children: Node[];
122
- span: Span;
123
- } | {
124
- k: 'if';
125
- branches: IfBranch[];
126
- span: Span;
127
- } | {
128
- k: 'for';
129
- item: string | [string, string];
130
- of: Expr;
131
- lets: Record<string, LoopVar>;
132
- body: Node[];
133
- empty?: Node[];
134
- span: Span;
135
- } | {
136
- k: 'switch';
137
- on: Expr;
138
- cases: Array<{
139
- value: Expr;
140
- body: Node[];
141
- }>;
142
- default?: Node[];
143
- span: Span;
144
- } | {
145
- k: 'let';
146
- name: string;
147
- expr: Expr;
148
- span: Span;
149
- } | {
150
- k: 'verbatim';
151
- text: string;
152
- span: Span;
153
- } | {
154
- k: 'slot-outlet';
155
- name?: string;
156
- fallback: Node[];
157
- span: Span;
158
- } | {
159
- k: 'slot-fill';
160
- name: string;
161
- body: Node[];
162
- span: Span;
163
- } | {
164
- k: 'assets';
165
- entry: string;
166
- span: Span;
167
- };
168
- interface InputDecl {
169
- name: string;
170
- default?: {
171
- value: Literal;
172
- span: Span;
173
- };
174
- span: Span;
175
- }
176
- interface TemplateAst {
177
- file: string;
178
- /** `undefined`: none declared (the default layout applies); `null`: `@layout(none)`. */
179
- layout?: string | null;
180
- layoutSpan?: Span;
181
- inputs: InputDecl[];
182
- body: Node[];
183
- }
184
- /** `[line, column]` of a node in its template, for render errors. */
185
- type At = [number, number];
186
- /** A path segment: `.n` or `[e]`; `o` marks `?.`. */
187
- type CSeg = {
188
- n: string;
189
- o?: 1;
190
- } | {
191
- e: CExpr;
192
- o?: 1;
193
- };
194
- type CExpr =
195
- /** literal */
196
- {
197
- k: 'l';
198
- v: Literal;
199
- } |
200
- /** undefined (a name a component doesn't have) */
201
- {
202
- k: 'x';
203
- } |
204
- /** page / shared data: `n` then the path */
205
- {
206
- k: 'd';
207
- n: string;
208
- p: CSeg[];
209
- } |
210
- /** a scope slot (@let, loop item, @if alias, component input) then the path */
211
- {
212
- k: 'v';
213
- s: number;
214
- p: CSeg[];
215
- } |
216
- /** a loop variable of the loop whose meta is in slot `s` */
217
- {
218
- k: 'm';
219
- s: number;
220
- w: LoopVar;
221
- } | {
222
- k: 'u';
223
- o: '!' | '-';
224
- a: CExpr;
225
- } | {
226
- k: 'b';
227
- o: string;
228
- l: CExpr;
229
- r: CExpr;
230
- } | {
231
- k: 'c';
232
- t: CExpr;
233
- y: CExpr;
234
- n: CExpr;
235
- } | {
236
- k: 'p';
237
- n: string;
238
- i: CExpr;
239
- a: CExpr[];
240
- };
241
- /** One attribute of an element whose attributes need work at render time. */
242
- type CAttr =
243
- /** static; `v: true` is a bare attribute */
244
- {
245
- t: 's';
246
- n: string;
247
- v: string | true;
248
- } |
249
- /** `n="text {{ e }}"`; `u` marks a URL attribute (`srcset` checks each candidate) */
250
- {
251
- t: 'i';
252
- n: string;
253
- p: Array<string | CExpr>;
254
- u?: 'url' | 'srcset';
255
- } |
256
- /** `[n]="e"` */
257
- {
258
- t: 'b';
259
- n: string;
260
- e: CExpr;
261
- u?: 'url' | 'srcset';
262
- } |
263
- /** `[class.n]="e"` */
264
- {
265
- t: 'c';
266
- n: string;
267
- e: CExpr;
268
- } |
269
- /** `[style.n(.x)]="e"` */
270
- {
271
- t: 'y';
272
- n: string;
273
- e: CExpr;
274
- x?: string;
275
- };
276
- type CNode =
277
- /** static output */
278
- {
279
- k: 's';
280
- t: string;
281
- } |
282
- /** `{{ e }}`: `text` escapes HTML (trusted HTML prints as is), `rcdata` (`<title>`, `<textarea>`) escapes everything, `json` is the one value of a JSON script */
283
- {
284
- k: 'i';
285
- c: 'text' | 'rcdata' | 'json' | 'css';
286
- e: CExpr;
287
- at: At;
288
- } |
289
- /** the attributes of an element (between `<tag` and `>`); `f` takes a component caller's fallthrough attributes */
290
- {
291
- k: 'A';
292
- tag: string;
293
- a: CAttr[];
294
- f?: 1;
295
- at: At;
296
- } | {
297
- k: 'if';
298
- br: Array<{
299
- c?: CExpr;
300
- a?: number;
301
- b: CNode[];
302
- }>;
303
- } | {
304
- k: 'for';
305
- e: CExpr;
306
- it: number | [number, number];
307
- m: number;
308
- b: CNode[];
309
- em?: CNode[];
310
- at: At;
311
- } | {
312
- k: 'sw';
313
- e: CExpr;
314
- cs: Array<{
315
- e: CExpr;
316
- b: CNode[];
317
- }>;
318
- d?: CNode[];
319
- } | {
320
- k: 'let';
321
- s: number;
322
- e: CExpr;
323
- } |
324
- /** a component: inputs into its slots, fallthrough attributes, slot fills (`''` is the default) */
325
- {
326
- k: 'cmp';
327
- n: string;
328
- in: Array<{
329
- s: number;
330
- e: CExpr;
331
- }>;
332
- fa: CAttr[];
333
- f: Record<string, CNode[]>;
334
- at: At;
335
- } |
336
- /** `<slot name="n">fallback</slot>` */
337
- {
338
- k: 'o';
339
- n: string;
340
- fb: CNode[];
341
- } | {
342
- k: 'as';
343
- en: string;
344
- };
345
- interface CheckedTemplate {
346
- v: typeof AST_FORMAT_VERSION;
347
- name: string;
348
- file: string;
349
- /** declared layout; `null` is `@layout(none)`; absent means the default layout applies to a page */
350
- layout?: string | null;
351
- /** scope slots the template needs */
352
- slots: number;
353
- /** a component's inputs: name, slot, default, required */
354
- inputs: Array<{
355
- n: string;
356
- s: number;
357
- d?: Literal;
358
- r: boolean;
359
- }>;
360
- /** `@slot('name') { }` fills a page passes to its layout */
361
- fills: Record<string, CNode[]>;
362
- body: CNode[];
363
- /** a component's `<script client>`: TypeScript as written (`js: false`), or plain JS once a build stripped it */
364
- client?: {
365
- code: string;
366
- js: boolean;
367
- };
368
- /** a field in it has `validate`: pages rendering it ship the validator script */
369
- validates?: true;
370
- }
371
- export { TemplateAst as _, CNode as a, Span as b, Ctx as c, IfBranch as d, InputDecl as f, PathSegment as g, Node as h, CExpr as i, Element as l, LoopVar as m, Attr as n, CSeg as o, Literal as p, CAttr as r, CheckedTemplate as s, AST_FORMAT_VERSION as t, Expr as u, Diagnostic as v, positionAt as x, Pos as y };
372
- //# sourceMappingURL=ast-bZ1jJ5-w.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ast-bZ1jJ5-w.d.ts","names":[],"sources":["../src/diagnostics.ts","../src/ast.ts"],"mappings":"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"}
@@ -1,17 +0,0 @@
1
- /**
2
- * @forinda/kickjs-view v0.5.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 emptyFormState,M as takeFormState,T as error,_ as read,a as templateName,b as sanitizeUrl,c as VALIDATORS,f as BUILTIN_PIPES,g as escapeJsonForScript,h as escapeHtml,i as layoutResolver,j as rememberPage,k as FORM_GLOBALS,l as VALIDATORS_TAG,m as SafeHtml,n as check,o as decodeEntities,p as builtinPipes,r as componentTag,t as parse,u as readValidatorExports,v as safeStyleValue,y as sanitizeSrcset}from"./template-DU9sjMgd.js";function fnv1a(s){let h=2166136261;for(let i=0;i<s.length;i++)h^=s.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,`0`)}const CLIENT_SCRIPT_FILE=/^([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]{8})\.([a-z0-9]{1,16})$/,TYPES={js:`text/javascript; charset=utf-8`,css:`text/css; charset=utf-8`,json:`application/json; charset=utf-8`,svg:`image/svg+xml`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,avif:`image/avif`,ico:`image/x-icon`,woff:`font/woff`,woff2:`font/woff2`,ttf:`font/ttf`,otf:`font/otf`,mp4:`video/mp4`,webm:`video/webm`,wasm:`application/wasm`},contentType=file=>TYPES[file.slice(file.lastIndexOf(`.`)+1)]??`application/octet-stream`,IMPORTS=/(^|[\n;])\s*import[\s{*'"]|\bimport\s*\(|(^|[\n;])\s*export\s*(\*(\s+as\s+[\w$]+)?|\{[^}]*\})\s*from\s*['"]/,NOISE=/\/\*[\s\S]*?\*\/|\/\/[^\n]*|'(?:\\.|[^'\\\n])*'|"(?:\\.|[^"\\\n])*"|`(?:\\.|[^`\\])*`/g;function hasImports(code){let parts=[],masked=code.replace(NOISE,m=>m[0]===`/`?`
12
- `:(m[0]==="`"&&parts.push(...templateExpressions(m)),m[0]+m[0]));return IMPORTS.test(masked)||parts.some(hasImports)}function templateExpressions(literal){let out=[];for(let i=0;i<literal.length;i++)if(literal[i]===`\\`)i++;else if(literal[i]===`$`&&literal[i+1]===`{`){let depth=1,j=i+2;for(;j<literal.length&&depth;j++)depth+=literal[j]===`{`?1:literal[j]===`}`?-1:0;out.push(literal.slice(i+2,j-1)),i=j-1}return out}function injectScripts(html,tags){let at=-1;for(let m of html.matchAll(/<\/body\s*>/gi))at=m.index;return at<0?html+tags:html.slice(0,at)+tags+html.slice(at)}function injectHead(html,tags){let at=/<\/head\s*>/i.exec(html)?.index??-1;return at<0?injectScripts(html,tags):html.slice(0,at)+tags+html.slice(at)}const NO_STRIPPER=`client scripts need Node 22.13+ to strip TypeScript, or a kick build`;function runtime(messages,doc){let say=(name,args)=>messages[name].replace(/\{(\d+)\}/g,(_m,i)=>String(args[Number(i)])),valueOf=el=>{if(el.type!==`checkbox`&&el.type!==`radio`)return String(el.value??``);for(let other of(el.form||doc).querySelectorAll(`input`))if((other.type===`checkbox`||other.type===`radio`)&&other.name===el.name&&other.checked)return String(other.value||`on`);return``};function message(el){let rules;try{rules=JSON.parse(el.getAttribute(`data-kick-validate`)||`[]`)}catch{return``}let value=valueOf(el);for(let[name,...args]of rules){if(name===`required`){if(value.trim()===``)return say(name,args);continue}if(value===``)continue;if(!Object.hasOwn(messages,name)){let fn=globalThis.__kickValidators?.[name];if(typeof fn!=`function`)continue;try{let out=fn(value,...args,el.form);if(typeof out==`string`&&out)return out}catch(err){console.error(`[kick/view] validator '${name}' threw`,err)}continue}let n=Number(value),ok=!0;if(name===`email`)ok=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);else if(name===`url`)try{ok=/^https?:$/.test(new URL(value).protocol)}catch{ok=!1}else if(name===`minLength`)ok=value.length>=Number(args[0]);else if(name===`maxLength`)ok=value.length<=Number(args[0]);else if(name===`min`)ok=!Number.isNaN(n)&&n>=Number(args[0]);else if(name===`max`)ok=!Number.isNaN(n)&&n<=Number(args[0]);else if(name===`pattern`)try{ok=RegExp(`^(?:${args[0]})$`).test(value)}catch{ok=!0}else name===`in`&&(ok=String(args[0]).split(`,`).map(s=>s.trim()).includes(value));if(!ok)return say(name,args)}return``}let spotFor=el=>{let name=el.getAttribute(`name`);if(!name)return null;let root=el.form||doc;for(let s of root.querySelectorAll(`[data-kick-error]`))if(s.getAttribute(`data-kick-error`)===name)return s;return null},ids=0;function run(el){let msg=message(el);el.setCustomValidity?.(msg),el.setAttribute(`data-kick-checked`,``);let spot=spotFor(el);if(spot){spot.textContent=msg,spot.hidden=msg===``,spot.id||=`kick-error-${++ids}`;let described=(el.getAttribute(`aria-describedby`)||``).split(/\s+/).filter(Boolean);described.includes(spot.id)||el.setAttribute(`aria-describedby`,[...described,spot.id].join(` `))}return msg?el.setAttribute(`aria-invalid`,`true`):el.removeAttribute(`aria-invalid`),msg===``}let field=t=>t&&t.matches&&t.matches(`[data-kick-validate]`)?t:null,quiet=()=>{for(let el of doc.querySelectorAll(`[data-kick-validate]`))el.form&&(el.form.noValidate=!0)};quiet();let Observer=globalThis.MutationObserver;Observer&&new Observer(quiet).observe(doc.documentElement,{childList:!0,subtree:!0}),doc.addEventListener(`focusin`,e=>{let el=field(e.target);el?.form&&(el.form.noValidate=!0)}),doc.addEventListener(`focusout`,e=>{let el=field(e.target);el&&run(el)}),doc.addEventListener(`input`,e=>{let el=field(e.target);el?.hasAttribute(`data-kick-checked`)&&run(el)}),doc.addEventListener(`submit`,e=>{if(e.submitter?.formNoValidate)return;let form=e.target,fields=form.querySelectorAll(`[data-kick-validate]`);if(!fields.length)return;form.noValidate=!0;let first=null;for(let el of fields)!run(el)&&!first&&(first=el);first?(e.preventDefault(),first.focus()):form.reportValidity&&!form.reportValidity()&&e.preventDefault()},!0)}const VALIDATORS_REGISTER=`
13
- import(import.meta.url).then((m) => Object.assign((globalThis.__kickValidators ??= {}), m))
14
- `,MESSAGES=Object.fromEntries(Object.entries(VALIDATORS).map(([k,v])=>[k,v.message])),VALIDATE_RUNTIME=`(${runtime.toString()})(${JSON.stringify(MESSAGES)}, document);\n`,ENV_PIPE=Symbol.for(`kickjs.view.envPipe`);function withEnv(make){return{[ENV_PIPE]:make}}const safeHtml=html=>new SafeHtml(html),isEnvPipe=p=>typeof p==`object`&&!!p&&ENV_PIPE in p;function pipesFor(app,env){let out=builtinPipes(env);for(let[name,p]of Object.entries(app))isEnvPipe(p)?out[name]=p[ENV_PIPE](env):typeof p==`function`&&(out[name]=p);return out}var RenderError=class extends Error{diagnostic;constructor(diagnostic){let{file,span,message}=diagnostic;super(`${file}:${span.start.line}:${span.start.column} — ${message}`),this.diagnostic=diagnostic,this.name=`RenderError`}};const MAX_DEPTH=64,warnedNames=/* @__PURE__ */ new WeakMap;var Renderer=class{env;out=[];constructor(env){this.env=env}rootData=Object.create(null);html(){return this.out.join(``)}fail(inst,message){let[line,column]=inst.at??[1,1],pos={offset:0,line,column},d=error(inst.t.file,{start:pos,end:pos},message);throw d.stack=inst.stack,new RenderError(d)}path(value,p,inst){for(let seg of p){if(value==null)return;value=read(value,`n`in seg?seg.n:this.value(seg.e,inst))}return value}value(e,inst,optional=!1){switch(e.k){case`l`:return e.v;case`x`:return;case`d`:{let data=FORM_GLOBALS.has(e.n)&&!(e.n in inst.data)?this.rootData:inst.data;if(!(e.n in data)){if(FORM_GLOBALS.has(e.n))return this.path({},e.p,inst);if(optional||e.p[0]?.o)return;this.unresolved(e.n,inst)}return this.path(read(data,e.n),e.p,inst)}case`v`:return this.path(inst.slots[e.s],e.p,inst);case`m`:return loopVar(inst.slots[e.s],e.w);case`u`:{let a=this.value(e.a,inst);return e.o===`!`?!a:-a}case`b`:{if(e.o===`&&`)return this.value(e.l,inst)&&this.value(e.r,inst);if(e.o===`||`)return this.value(e.l,inst)||this.value(e.r,inst);if(e.o===`??`)return this.value(e.l,inst,!0)??this.value(e.r,inst,optional);let l=this.value(e.l,inst),r=this.value(e.r,inst);switch(e.o){case`==`:case`===`:return l===r;case`!=`:case`!==`:return l!==r;case`<`:return l<r;case`>`:return l>r;case`<=`:return l<=r;case`>=`:return l>=r;case`+`:return l+r;case`-`:return l-r}return}case`c`:return this.value(e.t,inst)?this.value(e.y,inst):this.value(e.n,inst);case`p`:{let pipe=this.env.pipes[e.n];pipe||this.fail(inst,`unknown pipe '${e.n}'`);let input=this.value(e.i,inst),args=e.a.map(a=>this.value(a,inst)),result;try{result=pipe(input,...args)}catch(err){if(err instanceof RenderError)throw err;this.fail(inst,`pipe '${e.n}' failed: ${err instanceof Error?err.message:String(err)}`)}return result&&typeof result.then==`function`&&this.fail(inst,`pipe '${e.n}' returned a Promise — pipes must be synchronous`),result}}}unresolved(name,inst){this.env.strict&&this.fail(inst,`'${name}' isn't in the data`);let seen=warnedNames.get(inst.t);seen||warnedNames.set(inst.t,seen=/* @__PURE__ */ new Set),seen.has(name)||(seen.add(name),this.env.warn(`${inst.t.file}: '${name}' isn't in the data passed to render`))}text(v,inst){if(v==null)return``;switch(typeof v){case`string`:return v;case`number`:case`bigint`:case`boolean`:return String(v)}if(v instanceof Date)return Number.isNaN(v.getTime())?``:v.toISOString();if(v instanceof SafeHtml)return v.html;let what=v&&typeof v.then==`function`?`a Promise — await it in the controller`:Array.isArray(v)?`an array — loop over it with @for, or use | json`:`an object — print one of its properties, or use | json`;return this.env.strict&&this.fail(inst,`can't print ${what}`),this.env.warn(`${inst.t.file}:${inst.at?.[0]??1}: can't print ${what}`),``}nodes(list,inst){for(let n of list)this.node(n,inst)}node(n,inst){switch(n.k){case`s`:this.out.push(n.t);return;case`i`:{inst.at=n.at;let v=this.value(n.e,inst);if(n.c===`json`)this.out.push(escapeJsonForScript(typeof v==`string`?v:JSON.stringify(v)??`null`));else if(n.c===`css`){let css=v instanceof SafeHtml?v.html:this.text(v,inst);/<\/style/i.test(css)&&this.fail(inst,`CSS for <style> can't contain '</style'`),this.out.push(css)}else v instanceof SafeHtml&&n.c===`text`?this.out.push(v.html):this.out.push(escapeHtml(v instanceof SafeHtml?v.html:this.text(v,inst)));return}case`A`:inst.at=n.at,this.attrs(this.resolve(n.a,inst),n.f?inst.fall:void 0);return;case`if`:for(let br of n.br){let v=!br.c||this.value(br.c,inst);if(v){br.a!==void 0&&(inst.slots[br.a]=v),this.nodes(br.b,inst);return}}return;case`for`:{inst.at=n.at;let items=this.iterable(this.value(n.e,inst),inst);if(!items.length){n.em&&this.nodes(n.em,inst);return}let meta={i:0,n:items.length};inst.slots[n.m]=meta;for(let i=0;i<items.length;i++){meta.i=i;let item=items[i];typeof n.it==`number`?inst.slots[n.it]=item:(inst.slots[n.it[0]]=item?.[0],inst.slots[n.it[1]]=item?.[1]),this.nodes(n.b,inst)}return}case`sw`:{let v=this.value(n.e,inst),hit=n.cs.find(c=>this.value(c.e,inst)===v);hit?this.nodes(hit.b,inst):n.d&&this.nodes(n.d,inst);return}case`let`:inst.slots[n.s]=this.value(n.e,inst);return;case`cmp`:inst.at=n.at,this.component(n,inst);return;case`o`:{let fill=inst.fills[n.n];fill?this.nodes(fill.nodes,fill.inst):this.nodes(n.fb,inst);return}case`as`:this.env.assets?this.out.push(this.env.assets(n.en,inst.data)):this.env.warn(`${inst.t.file}: @assets('${n.en}') needs the Vite plugin or an assets option`)}}iterable(v,inst){if(v==null)return[];if(Array.isArray(v))return v;if(typeof v==`string`)return[...v];if(v instanceof Map)return[...v.entries()];if(v instanceof Set)return[...v];this.fail(inst,`@for can't loop over ${typeof v==`object`?`an object — use | entries`:`a ${typeof v}`}`)}attrValue(v,inst){return escapeHtml(this.plain(v,inst))}plain(v,inst){return v instanceof SafeHtml?v.html:this.text(v,inst)}resolve(list,inst){let r={attrs:[],cls:[],style:[]},put=(name,value)=>{let lower=name.toLowerCase();lower===`class`?value!==!0&&value.trim()&&r.cls.push(value.trim()):lower===`style`?value!==!0&&value.trim()&&r.style.push(value.trim().replace(/;\s*$/,``)):r.attrs.push([name,value])};for(let a of list)switch(a.t){case`s`:put(a.n,a.v===!0||a.v.replace(/"/g,`&quot;`));break;case`i`:{let values=a.p.map(p=>typeof p==`string`?void 0:this.value(p,inst)),html=a.p.map((p,i)=>typeof p==`string`?p.replace(/"/g,`&quot;`):this.attrValue(values[i],inst)).join(``);if(!a.u){put(a.n,html);break}let plain=decodeEntities(html),safe=a.u===`url`?sanitizeUrl(plain):sanitizeSrcset(plain);put(a.n,safe===plain?html:escapeHtml(safe));break}case`b`:{let v=this.value(a.e,inst);if(v==null||v===!1)break;if(v===!0){put(a.n,!0);break}let plain=this.plain(v,inst);put(a.n,escapeHtml(a.u===`url`?sanitizeUrl(plain):a.u===`srcset`?sanitizeSrcset(plain):plain));break}case`c`:this.value(a.e,inst)&&r.cls.push(escapeHtml(a.n));break;case`y`:{let v=this.value(a.e,inst);if(v==null||v===!1)break;let value=safeStyleValue(`${this.text(v,inst)}${a.x??``}`);if(value===void 0){this.env.warn(`${inst.t.file}:${inst.at?.[0]??1}: dropped an unsafe value for [style.${a.n}]`);break}r.style.push(`${escapeHtml(a.n)}:${escapeHtml(value)}`);break}}return r}attrs(own,fall){let attrs=own.attrs,cls=own.cls,style=own.style;if(fall){let names=new Set(fall.attrs.map(([n])=>n.toLowerCase()));attrs=[...attrs.filter(([n])=>!names.has(n.toLowerCase())),...fall.attrs],cls=[...cls,...fall.cls],style=[...style,...fall.style]}for(let[n,v]of attrs)this.out.push(v===!0?` ${n}`:` ${n}="${v}"`);cls.length&&this.out.push(` class="${cls.join(` `)}"`),style.length&&this.out.push(` style="${style.join(`;`)}"`)}component(n,caller){caller.depth>=64&&this.fail(caller,`components nest more than 64 deep — is ${n.n} including itself?`);let t=this.env.resolve(n.n);t.client&&this.env.clientScript?.(t),t.validates&&this.env.validation?.();let slots=Array.from({length:t.slots});for(let i of t.inputs)i.d!==void 0&&(slots[i.s]=i.d);for(let i of n.in)slots[i.s]=this.value(i.e,caller);let fills={};for(let[name,nodes]of Object.entries(n.f))fills[name]={nodes,inst:caller};let inst={t,data:Object.create(null),slots,fills,fall:this.resolve(n.fa,caller),stack:[...caller.stack,n.n],depth:caller.depth+1};this.nodes(t.body,inst)}};function loopVar(m,w){switch(w){case`$index`:return m.i;case`$first`:return m.i===0;case`$last`:return m.i===m.n-1;case`$even`:return m.i%2==0;case`$odd`:return m.i%2==1;case`$count`:return m.n}}function render(template,data,env,opts={}){let r=new Renderer(env);r.rootData=data;let page={t:template,data,slots:Array.from({length:template.slots}),fills:{},stack:[template.name],depth:0},none=opts.layout===!1||opts.layout===void 0&&template.layout===null,chain=[];if(!none){let next=typeof opts.layout==`string`?opts.layout:template.layout??env.layoutFor?.(template.name);for(;next&&next!==template.name&&!chain.some(t=>t.name===next);){let t=env.resolve(next);chain.push(t),next=t.layout??void 0}let base=env.baseLayout;base&&base!==template.name&&!chain.some(t=>t.name===base)&&chain.push(env.resolve(base))}if((template.validates||chain.some(t=>t.validates))&&env.validation?.(),!chain.length)return r.nodes(template.body,page),r.html();let fills={"":{nodes:template.body,inst:page}};for(let[name,nodes]of Object.entries(template.fills))fills[name]={nodes,inst:page};let inst=page;for(let[i,t]of chain.entries()){if(inst={t,data:page.data,slots:Array.from({length:t.slots}),fills,stack:[...inst.stack,t.name],depth:0},i===chain.length-1)break;let outer={...fills,"":{nodes:t.body,inst}};for(let[name,nodes]of Object.entries(t.fills))outer[name]={nodes,inst};fills=outer}return r.nodes(inst.t.body,inst),r.html()}const VALIDATE_TAG=`kick-validate`,VALIDATE_HASH=fnv1a(VALIDATE_RUNTIME);function bundleLoader(bundle){if(bundle.v!==1)throw Error(`views bundle format v${bundle.v}, this runtime reads v1`);return{list:async()=>Object.keys(bundle.templates),read:async()=>{throw Error(`a bundled template has no source`)}}}let fileLoaderModule;function useFileLoader(load){fileLoaderModule=load}let typeStripper;function useStripTypes(strip){typeStripper=strip}let clientReader;function useClientFiles(read){clientReader=read}function fileLoaders(){return fileLoaderModule?fileLoaderModule():Promise.reject(/* @__PURE__ */ Error(`createViews has no templates: pass the build's bundle (import kickViews from 'virtual:kick-views') or a loader`))}function createViews(options={}){let bundle=options.bundle??void 0,dev=options.dev??options.bundle===null;bundle&&bundleLoader(bundle);let componentsDir=options.componentsDir??`components`,disk=new Set(bundle?.client?.disk),scriptPath=(options.clientScriptPath??`/_kick/c`).replace(/\/+$/,``),stripTypes=options.stripTypes??(code=>{if(!typeStripper)throw Error(`client scripts need Node 22.13+ to strip TypeScript, or a kick build`);return typeStripper(code)}),validatorsFile=options.validatorsFile??`${(options.viewsDir??`src/views`).replace(/\/+$/,``)}/validators.ts`,validatorsJs,validatorsScript=source=>{if(options.bundle===void 0&&hasImports(source))return Promise.reject(/* @__PURE__ */ Error(`client scripts that import need kick dev or a kick build`));if(validatorsJs?.source===source)return validatorsJs.js;let js=(options.bundle===null?Promise.resolve(source):Promise.resolve(/\.m?js$/.test(validatorsFile)?source:stripTypes(source)).then(code=>code+VALIDATORS_REGISTER)).then(code=>({js:code,hash:fnv1a(code)}));return js.catch(()=>validatorsJs?.js===js&&(validatorsJs=void 0)),validatorsJs={source,js},js},scripts=/* @__PURE__ */ new Map,scriptFor=t=>{let client=t.client;if(options.bundle===void 0&&hasImports(client.code))return Promise.reject(/* @__PURE__ */ Error(`client scripts that import need kick dev or a kick build`));let hit=scripts.get(t.name);if(hit?.code===client.code)return hit.js;let raw=client.js||options.bundle===null,js=Promise.resolve(raw?client.code:stripTypes(client.code)).then(code=>({js:code,hash:fnv1a(code)}));return js.catch(()=>scripts.get(t.name)?.js===js&&scripts.delete(t.name)),scripts.set(t.name,{code:client.code,js}),js},layoutFor=layoutResolver(options.layout),warn=options.warn??(m=>console.warn(`[kick/view] ${m}`));disk.size&&clientReader&&!options.clientDir&&warn(`the build wrote client files to disk but createViews has no clientDir: pass { ...kickViews } from 'virtual:kick-views'`);let loader,appPipes,state,settle=(p,forget)=>p.catch(err=>{throw forget(),err}),getLoader=()=>loader??=settle(options.loader?Promise.resolve(options.loader):fileLoaders().then(m=>m.fileLoader(options.viewsDir??`src/views`)),()=>loader=void 0),getPipes=()=>appPipes??=settle(options.pipes||bundle?Promise.resolve(options.pipes??{}):fileLoaders().then(m=>m.loadPipesFile(options.pipesFile??`src/views/pipes.ts`)).then(mod=>mod??{}),()=>appPipes=void 0),reload=()=>state=settle(load(),()=>state=void 0),readValidators=async()=>bundle||!fileLoaderModule?void 0:(await fileLoaderModule()).readTextFile(validatorsFile);async function load(){let l=await getLoader(),pipes=await getPipes(),validators=await readValidators(),custom=validators===void 0?void 0:readValidatorExports(validators,validatorsFile);for(let d of custom?.diagnostics??[])warn(`${d.file}:${d.span.start.line}:${d.span.start.column} — ${d.message}`);let names=await l.list(),templates=/* @__PURE__ */ new Map,versions=/* @__PURE__ */ new Map,parseErrors=/* @__PURE__ */ new Map;return await Promise.all(names.map(async name=>{let r=parse(await l.read(name),`${name}.kick`);templates.set(name,r.ast);let first=r.diagnostics.find(d=>d.severity===`error`);first&&parseErrors.set(name,first),dev&&l.version&&versions.set(name,await l.version(name))})),{project:{templates,pipes:/* @__PURE__ */ new Set([...BUILTIN_PIPES,...Object.keys(pipes)]),validators:new Set(custom?.names),componentsDir,layouts:options.layout,baseLayout:options.baseLayout},versions,parseErrors,checked:/* @__PURE__ */ new Map,validators}}async function current(){if(options.cache===!1)return reload();let s=await(state??reload());if(!dev)return s;let l=await getLoader();if(!l.version)return s;let names=await l.list();return!(names.length!==s.project.templates.size||(await Promise.all(names.map(async n=>await l.version(n)!==s.versions.get(n)))).some(Boolean))&&await readValidators()===s.validators?s:reload()}function checked(s,name){let t=s.checked.get(name);if(t)return t;let syntax=s.parseErrors.get(name);if(syntax)throw new RenderError(syntax);let r=check(name,s.project);if(!r.template)throw new RenderError(r.diagnostics.find(x=>x.severity===`error`));for(let w of r.diagnostics)warn(`${w.file}:${w.span.start.line}:${w.span.start.column} — ${w.message}`);return t=r.template,s.checked.set(name,t),t}async function has(name){return templateName(name)?bundle?Object.hasOwn(bundle.templates,name):(await current()).project.templates.has(name):!1}let views={has,async render(name,data={},opts={}){if(!templateName(name))throw Error(`invalid template name '${name}'`);if(!await has(name))throw Error(`template '${name}' not found`);let st=bundle?void 0:await current(),resolve=bundle?n=>{let t=Object.hasOwn(bundle.templates,n)?bundle.templates[n]:void 0;if(!t)throw new RenderError(error(`${n}.kick`,zeroSpan,`template '${n}' not found`));return t}:n=>checked(st,n),template=resolve(name);rememberPage(opts.ctx,opts.layout);let shared=options.share?await options.share(opts.ctx):{},locale=opts.locale??options.locale??`en-US`,timeZone=opts.timeZone??options.timeZone??`UTC`,used=/* @__PURE__ */ new Map,validation=!1,page={...emptyFormState(),...shared,...takeFormState(opts.ctx),...data},html=render(template,page,{locale,timeZone,strict:options.strict??!1,pipes:pipesFor(await getPipes(),{locale,timeZone,urlFor:urlForOf(opts.ctx)}),warn,resolve,layoutFor,baseLayout:options.baseLayout,assets:options.assets,clientScript:t=>used.set(t.name,t),validation:()=>validation=!0},{layout:opts.layout});if(!used.size&&!validation)return html;let nonce=page.cspNonce,nonceAttr=typeof nonce==`string`?` nonce="${nonce.replace(/"/g,`&quot;`)}"`:``,tags=await Promise.all([...used.values()].map(async t=>{let tag=componentTag(t.name,componentsDir),file=bundle?.client?.entries[tag]??`${tag}.${(await scriptFor(t)).hash}.js`;return`<script type="module" src="${scriptPath}/${file}"${nonceAttr}><\/script>`}));if(validation){tags.push(`<script type="module" src="${scriptPath}/${VALIDATE_TAG}.${VALIDATE_HASH}.js"${nonceAttr}><\/script>`);let custom=bundle?bundle.client?.entries[VALIDATORS_TAG]:st?.validators===void 0?void 0:`${VALIDATORS_TAG}.${(await validatorsScript(st.validators)).hash}.js`;custom&&tags.push(`<script type="module" src="${scriptPath}/${custom}"${nonceAttr}><\/script>`)}let links=[.../* @__PURE__ */ new Set([...[...used.values()].flatMap(t=>bundle?.client?.css?.[componentTag(t.name,componentsDir)]??[]),...validation&&bundle?.client?.css?.[`kick-validators`]||[]])].map(f=>`<link rel="stylesheet" href="${scriptPath}/${f}"${nonceAttr}>`).join(``);return injectScripts(links?injectHead(html,links):html,tags.join(``))},clientScriptPath:scriptPath,async clientScript(file){let m=CLIENT_SCRIPT_FILE.exec(file);if(!m)return;if(m[1]===VALIDATE_TAG)return m[2]===VALIDATE_HASH&&m[3]===`js`?VALIDATE_RUNTIME:void 0;let files=bundle?.client?.files;if(files)return Object.hasOwn(files,file)?files[file]:void 0;if(m[1]===`kick-validators`){if(options.bundle!==void 0||m[3]!==`js`)return;let source=(await current()).validators;if(source===void 0)return;let{js,hash}=await validatorsScript(source);return hash===m[2]?js:void 0}if(m[3]!==`js`)return;let name=(bundle?Object.keys(bundle.templates):[...(await current()).project.templates.keys()]).find(n=>n.startsWith(`${componentsDir}/`)&&componentTag(n,componentsDir)===m[1]);if(!name)return;let t=bundle?bundle.templates[name]:checked(await current(),name);if(!t.client)return;let{js,hash}=await scriptFor(t);return hash===m[2]?js:void 0},async clientFile(file){if(!CLIENT_SCRIPT_FILE.test(file))return;if(disk.has(file)){if(!clientReader||!options.clientDir)return;try{return{body:await clientReader(new URL(file,options.clientDir)),type:contentType(file)}}catch(err){if(err.code===`ENOENT`)return;throw err}}let text=await views.clientScript(file);return text===void 0?void 0:{body:text,type:contentType(file)}}};return views}function urlForOf(ctx){let c=ctx;return typeof c?.urlFor==`function`?(name,params)=>c.urlFor(name,params):void 0}const zeroSpan={start:{offset:0,line:1,column:1},end:{offset:0,line:1,column:1}},clientFileHeaders=file=>({"content-type":contentType(file),"cache-control":`public, max-age=31536000, immutable`});function clientScriptFile(views,method,url){let m=String(method??`GET`).toUpperCase();if(m!==`GET`&&m!==`HEAD`)return;let path=url.split(`?`)[0],prefix=`${views.clientScriptPath}/`;if(!path.startsWith(prefix))return;let file=path.slice(prefix.length);return CLIENT_SCRIPT_FILE.test(file)?file:void 0}async function clientScriptResponse(views,request){let file=clientScriptFile(views,request.method,new URL(request.url).pathname);if(!file)return;let found=await views.clientFile(file);if(found)return new Response(request.method===`HEAD`?null:found.body,{status:200,headers:clientFileHeaders(file)})}const VIEW_RENDERER=Symbol.for(`kickjs.viewRenderer`);function rendererFor(views){return async(name,data,opts,ctx)=>await views.has(name)?views.render(name,data,{layout:opts.layout,locale:opts.locale,timeZone:opts.timeZone,ctx}):void 0}function bindViews(views){let renderer=rendererFor(views);return(req,res,next)=>{let r=req,file=clientScriptFile(views,r.method,r.url??`/`);if(!file)return r[VIEW_RENDERER]=renderer,next();views.clientFile(file).then(found=>{if(!found)return r[VIEW_RENDERER]=renderer,next();let out=res;out.statusCode=200;for(let[k,v]of Object.entries(clientFileHeaders(file)))out.setHeader(k,v);out.end(String(r.method).toUpperCase()===`HEAD`?void 0:found.body)},err=>next(err))}}function viewsMiddleware(views){let renderer=rendererFor(views);return(ctx,next)=>(ctx.req[VIEW_RENDERER]=renderer,next())}function kickViewDev(options,nodeEnv){return options.dev??(nodeEnv===`development`||options.bundle===null)}function KickView(options={}){let views=options.views??createViews({...options,dev:kickViewDev(options,globalThis.process?.env?.NODE_ENV)}),handler=bindViews(views);return{name:`KickView`,views,middleware:()=>[{handler,phase:`beforeGlobal`}]}}function assetTags(entry,mode,nonce){let base=mode.base.endsWith(`/`)?mode.base:`${mode.base}/`,n=nonce?` nonce="${escapeHtml(nonce)}"`:``,url=file=>escapeHtml(`${base}${file.replace(/^\//,``)}`);if(mode.dev)return[`<script type="module"${n} src="${url(`@vite/client`)}"><\/script>`,`<script type="module"${n} src="${url(entry)}"><\/script>`].join(`
15
- `);let chunk=mode.manifest[entry];if(!chunk)throw Error(`@assets: '${entry}' isn't an entry in the Vite manifest`);let css=new Set(chunk.css??[]),preload=/* @__PURE__ */ new Set,walk=key=>{let c=mode.manifest[key];if(c&&!preload.has(c.file)){preload.add(c.file);for(let s of c.css??[])css.add(s);for(let i of c.imports??[])walk(i)}};for(let i of chunk.imports??[])walk(i);return[...[...css].map(f=>`<link rel="stylesheet"${n} href="${url(f)}">`),...[...preload].map(f=>`<link rel="modulepreload"${n} href="${url(f)}">`),`<script type="module"${n} src="${url(chunk.file)}"><\/script>`].join(`
16
- `)}export{NO_STRIPPER as _,bundleLoader as a,useFileLoader as c,RenderError as d,render as f,VALIDATORS_REGISTER as g,withEnv as h,clientScriptResponse as i,useStripTypes as l,safeHtml as m,KickView as n,createViews as o,pipesFor as p,viewsMiddleware as r,useClientFiles as s,assetTags as t,MAX_DEPTH as u};
17
- //# sourceMappingURL=exports-DNeTdtX4.js.map