@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.
- package/dist/{ast-bZ1jJ5-w.d.ts → ast-Pq3XT2Xi.d.ts} +163 -8
- package/dist/ast-Pq3XT2Xi.d.ts.map +1 -0
- package/dist/cli.d.ts +60 -2
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +5 -2
- package/dist/cli.js.map +1 -1
- package/dist/edge.d.ts +9 -5
- package/dist/edge.js +2 -2
- package/dist/exports-BsyGvnEU.js +17 -0
- package/dist/exports-BsyGvnEU.js.map +1 -0
- package/dist/file-loader.d.ts +2 -2
- package/dist/file-loader.js +3 -3
- package/dist/file-loader.js.map +1 -1
- package/dist/format-DBjtuDUY.js +18 -0
- package/dist/format-DBjtuDUY.js.map +1 -0
- package/dist/index.d.ts +13 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/{project-XUrj8cl0.d.ts → project-DeGFHgGJ.d.ts} +24 -5
- package/dist/project-DeGFHgGJ.d.ts.map +1 -0
- package/dist/project-XTTCeVf3.js +12 -0
- package/dist/project-XTTCeVf3.js.map +1 -0
- package/dist/serve-Hc5UlJ56.d.ts +174 -0
- package/dist/serve-Hc5UlJ56.d.ts.map +1 -0
- package/dist/summary-EefMyOjo.js +20 -0
- package/dist/summary-EefMyOjo.js.map +1 -0
- package/dist/{views-_eQ9NTKn.d.ts → types-D-OIrXCW.d.ts} +190 -34
- package/dist/types-D-OIrXCW.d.ts.map +1 -0
- package/package.json +10 -10
- package/dist/ast-bZ1jJ5-w.d.ts.map +0 -1
- package/dist/exports-DNeTdtX4.js +0 -17
- package/dist/exports-DNeTdtX4.js.map +0 -1
- package/dist/format-Cig7Gm1h.js +0 -18
- package/dist/format-Cig7Gm1h.js.map +0 -1
- package/dist/project-XUrj8cl0.d.ts.map +0 -1
- package/dist/rolldown-runtime-BLRzqIEa.js +0 -11
- package/dist/serve-fHP-Eia9.d.ts +0 -97
- package/dist/serve-fHP-Eia9.d.ts.map +0 -1
- package/dist/template-DU9sjMgd.js +0 -20
- package/dist/template-DU9sjMgd.js.map +0 -1
- package/dist/views-_eQ9NTKn.d.ts.map +0 -1
|
@@ -1,31 +1,21 @@
|
|
|
1
1
|
|
|
2
|
-
import { s as CheckedTemplate, v as Diagnostic } from "./ast-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
readonly html: string;
|
|
6
|
-
constructor(html: string);
|
|
7
|
-
toString(): string;
|
|
2
|
+
import { s as CheckedTemplate, v as Diagnostic } from "./ast-Pq3XT2Xi.js";
|
|
3
|
+
declare namespace file_d_exports {
|
|
4
|
+
export { fileLoader, loadPipesFile, multiRootLoader, readTextFile };
|
|
8
5
|
}
|
|
6
|
+
declare function fileLoader(viewsDir: string): Loader;
|
|
7
|
+
/** The app's pipes file, if there is one, imported as a module. */
|
|
9
8
|
/**
|
|
10
|
-
*
|
|
11
|
-
* as `
|
|
12
|
-
* something to call. Getters and Proxy traps run: they are the app's own code.
|
|
13
|
-
*/
|
|
14
|
-
declare function read(obj: unknown, key: unknown): unknown;
|
|
15
|
-
declare const escapeHtml: (s: string) => string;
|
|
16
|
-
/**
|
|
17
|
-
* A URL attribute's value, or `#` when its scheme could run script.
|
|
18
|
-
* Browsers ignore ASCII whitespace and control characters inside a scheme
|
|
19
|
-
* (`java\tscript:`), so those are removed before the scheme is read.
|
|
9
|
+
* The app's views folder plus named roots: a root's templates are listed and
|
|
10
|
+
* read as `root::path`.
|
|
20
11
|
*/
|
|
21
|
-
declare function
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
/** A CSS value for `[style.prop]`, or `undefined` when it could leave its property. */
|
|
27
|
-
declare function safeStyleValue(v: string): string | undefined;
|
|
12
|
+
declare function multiRootLoader(appDir: string, roots: Record<string, string>): Loader;
|
|
13
|
+
declare function loadPipesFile(file: string): Promise<Record<string, unknown> | undefined>;
|
|
14
|
+
/** A text file's contents, or undefined when there's none. */
|
|
15
|
+
declare function readTextFile(file: string): Promise<string | undefined>;
|
|
16
|
+
/** A pipe: takes the piped value and the pipe's arguments, returns the new value. */
|
|
28
17
|
type Pipe = (value: unknown, ...args: unknown[]) => unknown;
|
|
18
|
+
/** What a render needs besides the data: locale, pipes, how to resolve layouts and components. */
|
|
29
19
|
interface RenderEnv {
|
|
30
20
|
locale: string;
|
|
31
21
|
timeZone: string;
|
|
@@ -45,6 +35,7 @@ interface RenderEnv {
|
|
|
45
35
|
/** A template with a `validate` field rendered: the page ships the validator script. */
|
|
46
36
|
validation?(): void;
|
|
47
37
|
}
|
|
38
|
+
/** Thrown when a render fails; `diagnostic` has the template, position and message. */
|
|
48
39
|
declare class RenderError extends Error {
|
|
49
40
|
readonly diagnostic: Diagnostic;
|
|
50
41
|
constructor(diagnostic: Diagnostic);
|
|
@@ -59,14 +50,51 @@ declare const MAX_DEPTH = 64;
|
|
|
59
50
|
*/
|
|
60
51
|
declare function render(template: CheckedTemplate, data: object, env: RenderEnv, opts?: {
|
|
61
52
|
layout?: boolean | string;
|
|
53
|
+
/** Render only these fragments of the page, without layouts. */
|
|
54
|
+
fragment?: string | readonly string[];
|
|
55
|
+
/** The caller's own data, which a fragment's needs are checked against (default `data`). */
|
|
56
|
+
callerData?: object;
|
|
62
57
|
}): string;
|
|
58
|
+
/** HTML a pipe or the app marked as trusted: printed unescaped, in text only. */
|
|
59
|
+
declare class SafeHtml {
|
|
60
|
+
readonly html: string;
|
|
61
|
+
constructor(html: string);
|
|
62
|
+
toString(): string;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Read `obj[key]` for a template. Forbidden names and function values read
|
|
66
|
+
* as `undefined`, so a template can neither reach a prototype nor get hold of
|
|
67
|
+
* something to call. Getters and Proxy traps run: they are the app's own code.
|
|
68
|
+
*/
|
|
69
|
+
declare function read(obj: unknown, key: unknown): unknown;
|
|
70
|
+
/** Escapes `&`, `<`, `>`, `"` and `'` for HTML text and attribute values. */
|
|
71
|
+
declare const escapeHtml: (s: string) => string;
|
|
72
|
+
/**
|
|
73
|
+
* A URL attribute's value, or `#` when its scheme could run script.
|
|
74
|
+
* Browsers ignore ASCII whitespace and control characters inside a scheme
|
|
75
|
+
* (`java\tscript:`), so those are removed before the scheme is read.
|
|
76
|
+
*/
|
|
77
|
+
declare function sanitizeUrl(value: string): string;
|
|
78
|
+
/** `srcset`: each candidate URL is checked on its own. */
|
|
79
|
+
declare function sanitizeSrcset(value: string): string;
|
|
80
|
+
/** JSON text made safe inside `<script type="application/json">`: no `</script`, no `<!--`. */
|
|
81
|
+
declare const escapeJsonForScript: (json: string) => string;
|
|
82
|
+
/** A CSS value for `[style.prop]`, or `undefined` when it could leave its property. */
|
|
83
|
+
declare function safeStyleValue(v: string): string | undefined;
|
|
84
|
+
/** The names of the built-in pipes. */
|
|
63
85
|
declare const BUILTIN_PIPES: readonly string[];
|
|
86
|
+
/** What built-in pipes read from the render: locale, time zone, and the request's `urlFor`. */
|
|
64
87
|
interface PipeEnv {
|
|
65
88
|
locale: string;
|
|
66
89
|
timeZone: string;
|
|
67
90
|
/** The request's `ctx.urlFor` (params in path order), for `kvRoute`. Absent outside a request. */
|
|
68
91
|
urlFor?: (name: string, params: Array<string | number>) => string;
|
|
69
92
|
}
|
|
93
|
+
/**
|
|
94
|
+
* The built-in pipes bound to a render's locale and time zone (`date`, `currency`, `kvRoute`, ...).
|
|
95
|
+
*
|
|
96
|
+
* @see https://kickjs.app/guide/views/pipes
|
|
97
|
+
*/
|
|
70
98
|
declare function builtinPipes(env: PipeEnv): Record<string, Pipe>;
|
|
71
99
|
declare const ENV_PIPE: unique symbol;
|
|
72
100
|
/** A pipe built per render from the render's locale and time zone. */
|
|
@@ -82,20 +110,15 @@ declare function withEnv(make: (env: PipeEnv) => Pipe): EnvPipe;
|
|
|
82
110
|
declare const safeHtml: (html: string) => SafeHtml;
|
|
83
111
|
/** The pipes for one render: the built-ins and the app's, with env pipes built for `env`. */
|
|
84
112
|
declare function pipesFor(app: Record<string, Pipe | EnvPipe>, env: PipeEnv): Record<string, Pipe>;
|
|
85
|
-
|
|
86
|
-
export { fileLoader, loadPipesFile, readTextFile };
|
|
87
|
-
}
|
|
88
|
-
declare function fileLoader(viewsDir: string): Loader;
|
|
89
|
-
/** The app's pipes file, if there is one, imported as a module. */
|
|
90
|
-
declare function loadPipesFile(file: string): Promise<Record<string, unknown> | undefined>;
|
|
91
|
-
/** A text file's contents, or undefined when there's none. */
|
|
92
|
-
declare function readTextFile(file: string): Promise<string | undefined>;
|
|
113
|
+
/** Where `createViews` reads template sources from. */
|
|
93
114
|
interface Loader {
|
|
94
115
|
/** Every template name (`users/show`, `components/user-card`). */
|
|
95
116
|
list(): Promise<string[]>;
|
|
96
117
|
read(name: string): Promise<string>;
|
|
97
118
|
/** Changes when the source changes (an mtime); checked on every render in dev. */
|
|
98
119
|
version?(name: string): Promise<number>;
|
|
120
|
+
/** The file `name` came from, for messages (default `<name>.kick`). */
|
|
121
|
+
file?(name: string): string;
|
|
99
122
|
}
|
|
100
123
|
/** What a build emits: checked templates as data. */
|
|
101
124
|
interface ViewsBundle {
|
|
@@ -112,9 +135,15 @@ interface ViewsBundle {
|
|
|
112
135
|
disk?: string[];
|
|
113
136
|
};
|
|
114
137
|
}
|
|
138
|
+
/** Per-render options: layout, locale and time zone. */
|
|
115
139
|
interface RenderOptions {
|
|
116
140
|
/** A layout for this render, or `false` for none at all (htmx and other partial responses). */
|
|
117
141
|
layout?: boolean | string;
|
|
142
|
+
/**
|
|
143
|
+
* Render only these `@fragment`s of the page, in order, without layouts —
|
|
144
|
+
* an htmx swap (several for out-of-band swaps).
|
|
145
|
+
*/
|
|
146
|
+
fragment?: string | readonly string[];
|
|
118
147
|
locale?: string;
|
|
119
148
|
timeZone?: string;
|
|
120
149
|
}
|
|
@@ -123,9 +152,15 @@ interface ShareContext {
|
|
|
123
152
|
req: unknown;
|
|
124
153
|
get(key: string): unknown;
|
|
125
154
|
}
|
|
155
|
+
/** Options for `createViews` and `KickView`. */
|
|
126
156
|
interface ViewsOptions {
|
|
127
157
|
/** Default `src/views`. */
|
|
128
158
|
viewsDir?: string;
|
|
159
|
+
/**
|
|
160
|
+
* More view folders, by name (absolute paths): `{ billing: '/app/src/modules/billing/views' }`
|
|
161
|
+
* renders `billing::invoices/show`. The Vite plugin fills it in from kick.config's `views.roots`.
|
|
162
|
+
*/
|
|
163
|
+
roots?: Record<string, string>;
|
|
129
164
|
/** Default `components`, inside the views folder. */
|
|
130
165
|
componentsDir?: string;
|
|
131
166
|
/** Default `src/views/pipes.ts`. Read when `pipes` isn't given and there is no bundle. */
|
|
@@ -172,8 +207,14 @@ interface ViewsOptions {
|
|
|
172
207
|
/** A `file:` URL of the folder holding the bundle's `disk` files; `virtual:kick-views` exports it. */
|
|
173
208
|
clientDir?: string;
|
|
174
209
|
}
|
|
210
|
+
/** A views instance: renders templates and serves component client scripts. */
|
|
175
211
|
interface Views {
|
|
176
|
-
render(name:
|
|
212
|
+
render<N extends ViewName>(name: N, ...args: ViewRenderArgs<N>): Promise<string>;
|
|
213
|
+
render<N extends ViewName, const F extends ViewFragmentNames<N>>(name: N, data: ViewFragmentData<N, F>, opts: RenderOptions & {
|
|
214
|
+
fragment: F;
|
|
215
|
+
ctx?: unknown;
|
|
216
|
+
}): Promise<string>;
|
|
217
|
+
render<N extends string>(name: N & LooseViewName<N>, data?: object, opts?: RenderOptions & {
|
|
177
218
|
ctx?: unknown;
|
|
178
219
|
}): Promise<string>;
|
|
179
220
|
/** A component's script by its served file name (`<tag>.<hash>.js`); `undefined` when there's none by that name. */
|
|
@@ -188,11 +229,126 @@ interface Views {
|
|
|
188
229
|
/** Whether `name` is one of these views — `ctx.render` falls through to another engine when not. */
|
|
189
230
|
has(name: string): Promise<boolean>;
|
|
190
231
|
}
|
|
232
|
+
/** A loader over a build's bundle; throws when the bundle's format version doesn't match this runtime. */
|
|
191
233
|
declare function bundleLoader(bundle: ViewsBundle): Loader;
|
|
192
234
|
type FileLoaderModule = typeof file_d_exports;
|
|
235
|
+
/**
|
|
236
|
+
* How `createViews` reaches the file loader when it's given neither a loader
|
|
237
|
+
* nor a bundle. The Node entry sets it; the edge entry (`workerd`, `worker`,
|
|
238
|
+
* `browser` conditions) doesn't, so an edge build never contains `node:fs`.
|
|
239
|
+
*/
|
|
193
240
|
declare function useFileLoader(load: () => Promise<FileLoaderModule>): void;
|
|
241
|
+
/** The TypeScript stripper for `<script client>`; the Node entry sets it. */
|
|
194
242
|
declare function useStripTypes(strip: (code: string) => string): void;
|
|
243
|
+
/** Reads a client file the build wrote to disk; the Node entry sets it. */
|
|
195
244
|
declare function useClientFiles(read: ((url: URL) => Promise<Uint8Array>) | undefined): void;
|
|
245
|
+
/**
|
|
246
|
+
* Creates a views instance: templates from a loader or a build's bundle, checked on first use
|
|
247
|
+
* and cached, rendered with the app's pipes and shared data. Use it directly to render
|
|
248
|
+
* outside a request (emails, tests), or pass it to `KickView({ views })`.
|
|
249
|
+
*
|
|
250
|
+
* @example
|
|
251
|
+
* ```ts
|
|
252
|
+
* const views = createViews({ layout: 'layouts/main' })
|
|
253
|
+
* const html = await views.render('emails/welcome', { user })
|
|
254
|
+
* ```
|
|
255
|
+
*
|
|
256
|
+
* @see https://kickjs.app/guide/views
|
|
257
|
+
*/
|
|
196
258
|
declare function createViews(options?: ViewsOptions): Views;
|
|
197
|
-
|
|
198
|
-
|
|
259
|
+
/**
|
|
260
|
+
* Every `.kick` page by name: the data it reads and its fragments' needs.
|
|
261
|
+
* Filled by `kick typegen`; don't write entries by hand.
|
|
262
|
+
*
|
|
263
|
+
* @see https://kickjs.app/guide/views/typed-render-data
|
|
264
|
+
*/
|
|
265
|
+
interface KickViews {}
|
|
266
|
+
/**
|
|
267
|
+
* Names `createViews({ share })` supplies to every page, so a controller
|
|
268
|
+
* needn't pass them. Declare them once:
|
|
269
|
+
*
|
|
270
|
+
* ```ts
|
|
271
|
+
* declare module '@forinda/kickjs-view' {
|
|
272
|
+
* interface KickViewShared { user: User | undefined; csrfToken: string }
|
|
273
|
+
* }
|
|
274
|
+
* ```
|
|
275
|
+
*
|
|
276
|
+
* @see https://kickjs.app/guide/views/typed-render-data
|
|
277
|
+
*/
|
|
278
|
+
interface KickViewShared {}
|
|
279
|
+
/**
|
|
280
|
+
* Switches for the render types. `otherEngines: true` lets names outside
|
|
281
|
+
* {@link KickViews} through — for an app that also renders EJS or Pug with
|
|
282
|
+
* `ViewAdapter` (a misspelled `.kick` name then compiles too).
|
|
283
|
+
*
|
|
284
|
+
* @see https://kickjs.app/guide/views/typed-render-data
|
|
285
|
+
*/
|
|
286
|
+
interface KickViewTypeOptions {}
|
|
287
|
+
type Opts = Omit<RenderOptions, 'fragment'> & {
|
|
288
|
+
ctx?: unknown;
|
|
289
|
+
};
|
|
290
|
+
/** Template names `R` knows, `string` while it's empty or other engines are on. */
|
|
291
|
+
type ViewNameOf<R, O> = [keyof R] extends [never] ? string : O extends {
|
|
292
|
+
otherEngines: true;
|
|
293
|
+
} ? string : Extract<keyof R, string>;
|
|
294
|
+
type DataOf<R, N> = N extends keyof R ? (R[N] extends {
|
|
295
|
+
data: infer D;
|
|
296
|
+
} ? D : never) : never;
|
|
297
|
+
type Intersect<U> = (U extends unknown ? (x: U) => void : never) extends ((x: infer I) => void) ? I : never;
|
|
298
|
+
/**
|
|
299
|
+
* Shared names may be left out; extra keys are fine. The union keeps an
|
|
300
|
+
* interface or class instance assignable (they have no index signature),
|
|
301
|
+
* while an object literal's extra keys are allowed by the second member.
|
|
302
|
+
*/
|
|
303
|
+
type Shaped<D, S> = Omit<D, keyof S> & Partial<Pick<D, Extract<keyof D, keyof S>>>;
|
|
304
|
+
type WithShared<D, S> = Shaped<D, S> | (Shaped<D, S> & Record<string, unknown>);
|
|
305
|
+
/** The data `ctx.render(N, data)` takes; for a union of names, what every one of those pages needs. */
|
|
306
|
+
type ViewDataOf<R, S, N> = [DataOf<R, N>] extends [never] ? Record<string, any> : WithShared<Intersect<DataOf<R, N>>, S>;
|
|
307
|
+
type FragmentsOf<R, N> = N extends keyof R ? (R[N] extends {
|
|
308
|
+
fragments: infer F;
|
|
309
|
+
} ? F : {}) : never;
|
|
310
|
+
/** A fragment name of page `N` (any string for names the registry doesn't know). */
|
|
311
|
+
type ViewFragmentNameOf<R, N> = [FragmentsOf<R, N>] extends [never] ? string : Extract<keyof FragmentsOf<R, N>, string>;
|
|
312
|
+
/** What `opts.fragment` may be: one fragment of page `N`, or a list of them. */
|
|
313
|
+
type FragmentNames<R, N> = ViewFragmentNameOf<R, N> | readonly ViewFragmentNameOf<R, N>[];
|
|
314
|
+
type Part<R, N, K, P extends 'needs' | 'reads'> = K extends keyof FragmentsOf<R, N> ? FragmentsOf<R, N>[K] extends Record<P, infer X> ? X : never : never;
|
|
315
|
+
type Listed<F> = F extends readonly (infer X)[] ? X : F;
|
|
316
|
+
/**
|
|
317
|
+
* The data a fragment render takes: for every fragment named, its needs
|
|
318
|
+
* exactly (the controller passes them; `share()` doesn't count at render),
|
|
319
|
+
* plus the page data it reads.
|
|
320
|
+
*/
|
|
321
|
+
type ViewFragmentDataOf<R, S, N, F> = [FragmentsOf<R, N>] extends [never] ? Record<string, any> : Intersect<Part<R, N, Listed<F>, 'needs'>> & WithShared<Intersect<Part<R, N, Listed<F>, 'reads'>>, S>;
|
|
322
|
+
/**
|
|
323
|
+
* The arguments after the name, without a fragment: `data` (required when
|
|
324
|
+
* the page needs any) and options. Fragment renders have their own overload.
|
|
325
|
+
*/
|
|
326
|
+
type RenderArgs<R, S, N> = [DataOf<R, N>] extends [never] ? [data?: Record<string, any>, opts?: Opts & {
|
|
327
|
+
fragment?: string | readonly string[];
|
|
328
|
+
}] : {} extends ViewDataOf<R, S, N> ? [data?: ViewDataOf<R, S, N>, opts?: Opts & {
|
|
329
|
+
fragment?: undefined;
|
|
330
|
+
}] : [data: ViewDataOf<R, S, N>, opts?: Opts & {
|
|
331
|
+
fragment?: undefined;
|
|
332
|
+
}];
|
|
333
|
+
/**
|
|
334
|
+
* What name `N` the loose overload takes: any string while the registry is
|
|
335
|
+
* empty (so generic helpers compile); with other engines on, any name but a
|
|
336
|
+
* registered one — a known page can't skip its data through it; else none.
|
|
337
|
+
*/
|
|
338
|
+
type LooseViewNameOf<R, O, N> = [keyof R] extends [never] ? string : O extends {
|
|
339
|
+
otherEngines: true;
|
|
340
|
+
} ? [Extract<N, keyof R>] extends [never] ? string : never : never;
|
|
341
|
+
/** The app's template names. */
|
|
342
|
+
type ViewName = ViewNameOf<KickViews, KickViewTypeOptions>;
|
|
343
|
+
/** The data page `N` takes. */
|
|
344
|
+
type ViewData<N> = ViewDataOf<KickViews, KickViewShared, N>;
|
|
345
|
+
/** Arguments after the name, for the app's registry. */
|
|
346
|
+
type ViewRenderArgs<N> = RenderArgs<KickViews, KickViewShared, N>;
|
|
347
|
+
/** `opts.fragment` for page `N`. */
|
|
348
|
+
type ViewFragmentNames<N> = FragmentNames<KickViews, N>;
|
|
349
|
+
/** The data a fragment render of page `N` takes. */
|
|
350
|
+
type ViewFragmentData<N, F> = ViewFragmentDataOf<KickViews, KickViewShared, N, F>;
|
|
351
|
+
/** The loose overload's name, for the app's registry. */
|
|
352
|
+
type LooseViewName<N> = LooseViewNameOf<KickViews, KickViewTypeOptions, N>;
|
|
353
|
+
export { PipeEnv as A, Pipe as B, useFileLoader as C, safeHtml as D, pipesFor as E, read as F, loadPipesFile as G, RenderError as H, safeStyleValue as I, multiRootLoader as K, sanitizeSrcset as L, SafeHtml as M, escapeHtml as N, withEnv as O, escapeJsonForScript as P, sanitizeUrl as R, useClientFiles as S, EnvPipe as T, render as U, RenderEnv as V, fileLoader as W, Views as _, LooseViewNameOf as a, bundleLoader as b, ViewDataOf as c, ViewName as d, ViewNameOf as f, ShareContext as g, RenderOptions as h, KickViews as i, builtinPipes as j, BUILTIN_PIPES as k, ViewFragmentData as l, Loader as m, KickViewShared as n, RenderArgs as o, ViewRenderArgs as p, readTextFile as q, KickViewTypeOptions as r, ViewData as s, FragmentNames as t, ViewFragmentDataOf as u, ViewsBundle as v, useStripTypes as w, createViews as x, ViewsOptions as y, MAX_DEPTH as z };
|
|
354
|
+
//# sourceMappingURL=types-D-OIrXCW.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-D-OIrXCW.d.ts","names":["_$__loaders_file0"],"sources":["../src/loaders/file.ts","../src/render/render.ts","../src/render/safe.ts","../src/pipes/builtins.ts","../src/pipes/env.ts","../src/views.ts","../src/types.ts"],"mappings":";;;;;iBASgB,WAAW,mBAAmB;;;;;;iBA0B9B,gBAAgB,gBAAgB,OAAO,yBAAyB;iBA8C1D,cAAc,eAAe,QAAQ;;iBAYrC,aAAa,eAAe;;KCzEtC,QAAQ,mBAAmB;;UAGtB;EACf;EACA;EACA;EACA,OAAO,eAAe;EACtB,KAAK;;EAEL,QAAQ,eAAe;;EAEvB,WAAW;;EAEX;;EAEA,QAAQ,eAAe,MAAM;;EAE7B,cAAc,GAAG;;EAEjB;;;cAIW,oBAAoB;WACV,YAAY;EAAjC,YAAqB,YAAY;;;cAQtB;;;;;;;iBA4kBG,OACd,UAAU,iBACV,cACA,KAAK,WACL;EACE;;EAEA;;EAEA;;;cChoBS;WACU;EAArB,YAAqB;EACrB;;;;;;;iBAUc,KAAK,cAAc;;cAiBtB,aAAU;;;;;;iBASP,YAAY;;iBASZ,eAAe;;cAoBlB,sBAAmB;;iBAIhB,eAAe;;cCzElB;;UAqBI;EACf;EACA;;EAEA,UAAU,cAAc,QAAQ;;;;;;;iBA2DlB,aAAa,KAAK,UAAU,eAAe;cCtFrD;;UAGW;GACd,YAAY,KAAK,YAAY;;;;;;iBAOhB,QAAQ,OAAO,KAAK,YAAY,OAAO;;cAK1C,WAAQ,iBAAmB;;iBAKxB,SAAS,KAAK,eAAe,OAAO,UAAU,KAAK,UAAU,eAAe;;UCgB3E;;EAEf,QAAQ;EACR,KAAK,eAAe;;EAEpB,SAAS,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
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@forinda/kickjs-view",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "KickJS views — .kick templates rendered on every runtime and the edge",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"kickjs",
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
"virtual.d.ts"
|
|
38
38
|
],
|
|
39
39
|
"peerDependencies": {
|
|
40
|
-
"@forinda/kickjs": "^10.
|
|
40
|
+
"@forinda/kickjs": "^10.15.0"
|
|
41
41
|
},
|
|
42
42
|
"peerDependenciesMeta": {
|
|
43
43
|
"@forinda/kickjs": {
|
|
@@ -46,22 +46,22 @@
|
|
|
46
46
|
},
|
|
47
47
|
"devDependencies": {
|
|
48
48
|
"@fastify/middie": "^9.3.6",
|
|
49
|
-
"@swc/core": "^1.16.
|
|
49
|
+
"@swc/core": "^1.16.22",
|
|
50
50
|
"@types/ejs": "^3.1.5",
|
|
51
51
|
"@types/node": "^26.6.6",
|
|
52
52
|
"@types/supertest": "^7.2.1",
|
|
53
|
-
"commander": "^15.
|
|
53
|
+
"commander": "^15.1.0",
|
|
54
54
|
"ejs": "^7.0.2",
|
|
55
55
|
"express": "^5.3.0",
|
|
56
|
-
"fastify": "^5.12.
|
|
56
|
+
"fastify": "^5.12.8",
|
|
57
57
|
"h3": "2.0.8",
|
|
58
58
|
"happy-dom": "^21.0.4",
|
|
59
59
|
"reflect-metadata": "^0.2.2",
|
|
60
|
-
"supertest": "^7.3.
|
|
60
|
+
"supertest": "^7.3.2",
|
|
61
61
|
"typescript": "^7.0.2",
|
|
62
|
-
"vitest": "^5.0
|
|
63
|
-
"@forinda/kickjs": "10.
|
|
64
|
-
"@forinda/kickjs-cli-kit": "0.1.
|
|
62
|
+
"vitest": "^5.1.0",
|
|
63
|
+
"@forinda/kickjs": "10.15.0",
|
|
64
|
+
"@forinda/kickjs-cli-kit": "0.1.4"
|
|
65
65
|
},
|
|
66
66
|
"publishConfig": {
|
|
67
67
|
"access": "public"
|
|
@@ -83,7 +83,7 @@
|
|
|
83
83
|
"scripts": {
|
|
84
84
|
"build": "tsdown",
|
|
85
85
|
"dev": "tsdown --watch",
|
|
86
|
-
"test": "vitest run --passWithNoTests",
|
|
86
|
+
"test": "vitest run --typecheck --passWithNoTests",
|
|
87
87
|
"test:watch": "vitest",
|
|
88
88
|
"typecheck": "tsc --noEmit",
|
|
89
89
|
"clean": "rm -rf dist .wireit",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ast-bZ1jJ5-w.d.ts","names":[],"sources":["../src/diagnostics.ts","../src/ast.ts"],"mappings":";;UACiB;EACf;EACA;EACA;;UAGe;EACf,OAAO;EACP,KAAK;;UAGU;EACf;EACA,MAAM;EACN;EACA;;EAEA;;;cA6BW,aAAU,gBAAkB,mBAAmB;;cC5C/C;KAED;UAEK;;EAEf;;EAEA,WAAW;EACX;;KAGU;EACN;EAAiB,OAAO;EAAS,MAAM;;EACvC;EAAc;EAAc,UAAU;EAAe,MAAM;;EAC3D;EAAe;EAAe,KAAK;EAAM,MAAM;;EAE/C;EACA;EACA,MAAM;EACN,OAAO;EACP,MAAM;;EAEN;EAAiB;EAAwB,MAAM;EAAM,OAAO;EAAM,MAAM;;EACxE;EAAqB,MAAM;EAAM,UAAU;EAAM,WAAW;EAAM,MAAM;;EACxE;EAAc,OAAO;EAAM;EAAc,MAAM;EAAQ,MAAM;;;KAGvD;UAEK;;EAEf;;;;;EAKA;;EAEA,QAAQ,eAAe;;EAEvB,OAAO;;EAEP;EACA;EACA,MAAM;;UAGS;EACf;;EAEA;EACA,OAAO;EACP,UAAU;;EAEV;EACA;EACA;EACA,MAAM;;UAGS;;EAEf,OAAO;;EAEP;EACA,MAAM;;KAGI;KAEA;EACN;EAAW;EAAe,MAAM;;EAChC;EAAa,MAAM;EAAM,KAAK;EAAK,MAAM;IAC3C;EACE;EAAc,UAAU;EAAQ,MAAM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GAAG;IAAO,GAAG;;EAAY,IAAI;;EAC5D;EAAU;EAAW,GAAG;;;;EAGxB;EACA;EACA,IAAI;IAAQ;IAAW,GAAG;;EAC1B,IAAI;EACJ,GAAG,eAAe;EAClB,IAAI;;;;EAGJ;EAAQ;EAAW,IAAI;;EACvB;EAAS;;UAEE;EACf,UAAU;EACV;EACA;;EAEA;;EAEA;;EAEA,QAAQ;IAAQ;IAAW;IAAW,IAAI;IAAS;;;EAEnD,OAAO,eAAe;EACtB,MAAM;;EAEN;IAAW;IAAc;;;EAEzB"}
|
package/dist/exports-DNeTdtX4.js
DELETED
|
@@ -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,`"`));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,`"`):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,`"`)}"`:``,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
|