@lipsjs/lips 0.1.1 → 0.3.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/README.md +185 -85
- package/dist/lips.js +6274 -0
- package/dist/lips.js.map +53 -0
- package/dist/lips.min.js +13 -2
- package/dist/lips.min.js.map +47 -43
- package/dist/mf2.min.js +4 -0
- package/dist/mf2.min.js.map +38 -0
- package/dist/precompile.min.js +23 -0
- package/dist/precompile.min.js.map +14 -0
- package/dist/runtime.min.js +5 -0
- package/dist/runtime.min.js.map +20 -0
- package/dist/stylis.min.js +3 -0
- package/dist/stylis.min.js.map +16 -0
- package/dist/types/events.d.ts +1 -1
- package/dist/types/i18n/engine.d.ts +14 -0
- package/dist/types/i18n/index.d.ts +122 -5
- package/dist/types/i18n/intl.d.ts +1 -0
- package/dist/types/i18n/lookup.d.ts +22 -0
- package/dist/types/ir/compiler.d.ts +226 -0
- package/dist/types/ir/expression.d.ts +149 -0
- package/dist/types/ir/facade.d.ts +138 -0
- package/dist/types/ir/host.d.ts +75 -0
- package/dist/types/ir/index.d.ts +18 -0
- package/dist/types/ir/parser.d.ts +124 -0
- package/dist/types/ir/policy.d.ts +95 -0
- package/dist/types/ir/router.d.ts +47 -0
- package/dist/types/ir/runtime.d.ts +130 -0
- package/dist/types/ir/signal.d.ts +28 -0
- package/dist/types/ir/style.d.ts +119 -0
- package/dist/types/ir/swap.d.ts +28 -0
- package/dist/types/ir/tree.d.ts +51 -0
- package/dist/types/lips.d.ts +33 -37
- package/dist/types/lynx/a11y.d.ts +61 -0
- package/dist/types/lynx/background.d.ts +71 -0
- package/dist/types/lynx/main.d.ts +46 -0
- package/dist/types/lynx/protocol.d.ts +52 -0
- package/dist/types/lynx/style.d.ts +49 -0
- package/dist/types/lynx/template.d.ts +37 -0
- package/dist/types/mf2.d.ts +14 -0
- package/dist/types/precompile.d.ts +85 -0
- package/dist/types/runtime.d.ts +16 -0
- package/dist/types/stylesheet.d.ts +21 -41
- package/dist/types/stylis.d.ts +2 -0
- package/dist/types/types.d.ts +176 -185
- package/dist/types/untrusted.d.ts +17 -0
- package/dist/untrusted.min.js +5 -0
- package/dist/untrusted.min.js.map +13 -0
- package/package.json +46 -10
- package/dist/test.component.min.js +0 -3
- package/dist/test.component.min.js.map +0 -50
- package/dist/test.stress.min.js +0 -476
- package/dist/test.stress.min.js.map +0 -50
- package/dist/types/component.d.ts +0 -107
- package/dist/types/constants.d.ts +0 -23
- package/dist/types/dws.d.ts +0 -14
- package/dist/types/iuc/index.d.ts +0 -25
- package/dist/types/iuc/tick.d.ts +0 -38
- package/dist/types/iuc.d.ts +0 -25
- package/dist/types/metrics.d.ts +0 -50
- package/dist/types/preprocess.d.ts +0 -2
- package/dist/types/signal.d.ts +0 -30
- package/dist/types/syntax/async.d.ts +0 -16
- package/dist/types/syntax/for.d.ts +0 -25
- package/dist/types/syntax/if.d.ts +0 -14
- package/dist/types/syntax/router.d.ts +0 -40
- package/dist/types/syntax/switch.d.ts +0 -16
- package/dist/types/tick.d.ts +0 -38
- package/dist/types/tps.d.ts +0 -11
- package/dist/types/uqs.d.ts +0 -37
- package/dist/types/utils.d.ts +0 -25
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Build-time precompilation (RFC-001 §5, §9 — Phase 3).
|
|
3
|
+
*
|
|
4
|
+
* Turns `{ default: '<template…>' }` into `{ ir: {…} }` ahead of time.
|
|
5
|
+
* Two payoffs:
|
|
6
|
+
*
|
|
7
|
+
* 1. **CSP**: with `mode: 'interpreted'`, a precompiled app never
|
|
8
|
+
* calls `Function`/`eval`, so it runs under `script-src` without
|
|
9
|
+
* `unsafe-eval`.
|
|
10
|
+
* 2. **Startup**: no parse/compile at runtime — the app boots
|
|
11
|
+
* straight into cloning skeletons.
|
|
12
|
+
*
|
|
13
|
+
* The IR is plain JSON, so it can be emitted into a bundle, shipped
|
|
14
|
+
* from a server, or stored as a Modela artifact.
|
|
15
|
+
*/
|
|
16
|
+
import type { TemplateIR, CompileOptions } from './ir/compiler';
|
|
17
|
+
import type { StyleIR, StylePreprocessor } from './ir/style';
|
|
18
|
+
import type { TemplateDiagnostic } from './ir/parser';
|
|
19
|
+
export interface PrecompiledTemplate {
|
|
20
|
+
ir: TemplateIR;
|
|
21
|
+
/** Compiled stylesheet — replaces `stylesheet` source (RFC-004) */
|
|
22
|
+
style?: StyleIR;
|
|
23
|
+
state?: Record<string, any>;
|
|
24
|
+
_static?: Record<string, any>;
|
|
25
|
+
context?: string[];
|
|
26
|
+
handler?: Record<string, (...args: any[]) => any>;
|
|
27
|
+
}
|
|
28
|
+
export interface PrecompileOptions {
|
|
29
|
+
/**
|
|
30
|
+
* Scope name for the stylesheet — baked into the StyleIR, so it must
|
|
31
|
+
* match how the component is registered. Defaults to `'lips'`.
|
|
32
|
+
*/
|
|
33
|
+
name?: string;
|
|
34
|
+
/**
|
|
35
|
+
* CSS preprocessor for the stylesheet, e.g. `stylisPreprocessor` from
|
|
36
|
+
* `@lipsjs/lips/stylis`. Absent, the sheet is baked nested and native
|
|
37
|
+
* CSS nesting resolves it. Passed here, not set globally: this entry
|
|
38
|
+
* and `@lipsjs/lips/stylis` are separate bundles with separate state.
|
|
39
|
+
*/
|
|
40
|
+
preprocess?: StylePreprocessor;
|
|
41
|
+
/** The kind of host the IR is for — see `CompileOptions.target` */
|
|
42
|
+
target?: CompileOptions['target'];
|
|
43
|
+
}
|
|
44
|
+
export interface PrecompileResult {
|
|
45
|
+
template: PrecompiledTemplate;
|
|
46
|
+
diagnostics: TemplateDiagnostic[];
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Precompile one authoring template. Macros are inlined at this point,
|
|
50
|
+
* so the `macros` source does not ship to the client — and the stylesheet
|
|
51
|
+
* is compiled to StyleIR, so the `./runtime` build needs no CSS
|
|
52
|
+
* preprocessor either (RFC-004 §1).
|
|
53
|
+
*/
|
|
54
|
+
export declare function precompile(template: Record<string, any>, options?: PrecompileOptions): PrecompileResult;
|
|
55
|
+
/** Serialize an IR for embedding in generated source */
|
|
56
|
+
export declare const serializeIR: (ir: TemplateIR) => string;
|
|
57
|
+
export declare const serializeStyleIR: (ir: StyleIR) => string;
|
|
58
|
+
export interface PluginOptions {
|
|
59
|
+
/** Files to transform (default: `.lips` single-file components) */
|
|
60
|
+
include?: RegExp;
|
|
61
|
+
/** Emit diagnostics as build warnings (default true) */
|
|
62
|
+
reportDiagnostics?: boolean;
|
|
63
|
+
/** CSS preprocessor for lifted stylesheets — see `PrecompileOptions.preprocess` */
|
|
64
|
+
preprocess?: StylePreprocessor;
|
|
65
|
+
/** The kind of host the IR is for — see `CompileOptions.target` */
|
|
66
|
+
target?: CompileOptions['target'];
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Vite/Rollup plugin: compiles `.lips` single-file components into a
|
|
70
|
+
* module exporting a precompiled template.
|
|
71
|
+
*
|
|
72
|
+
* import Card from './card.lips'
|
|
73
|
+
* lips.register('card', Card) // no runtime parsing
|
|
74
|
+
*
|
|
75
|
+
* Kept dependency-free (duck-typed plugin object) so importing this
|
|
76
|
+
* module never pulls a bundler into the runtime graph.
|
|
77
|
+
*/
|
|
78
|
+
export declare function lipsPlugin(options?: PluginOptions): {
|
|
79
|
+
name: string;
|
|
80
|
+
enforce: "pre";
|
|
81
|
+
transform(code: string, id: string): Promise<{
|
|
82
|
+
code: string;
|
|
83
|
+
map: null;
|
|
84
|
+
} | null>;
|
|
85
|
+
};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Precompiled-only entry: the runtime WITHOUT the template parser
|
|
3
|
+
* and compiler.
|
|
4
|
+
*
|
|
5
|
+
* import Lips from '@lipsjs/lips/runtime'
|
|
6
|
+
*
|
|
7
|
+
* Templates must carry precompiled `ir` (see `precompile()` or the
|
|
8
|
+
* bundler plugin). Combined with `mode: 'interpreted'` this build
|
|
9
|
+
* never constructs a Function, so it runs under a strict CSP.
|
|
10
|
+
*/
|
|
11
|
+
import { IRLips } from './ir/facade';
|
|
12
|
+
export * from './types';
|
|
13
|
+
export { renderIR } from './ir/runtime';
|
|
14
|
+
export { signal, effect, untrack, reactive } from './ir/signal';
|
|
15
|
+
export type { TemplateIR, IRInstance, RuntimeOptions, RenderSetup, SwapReport, Host } from './ir';
|
|
16
|
+
export default IRLips;
|
|
@@ -1,51 +1,31 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Component stylesheets — injected once per namespace and reference
|
|
3
|
+
* counted so shared components clean up correctly. Native DOM only.
|
|
4
|
+
*
|
|
5
|
+
* Compilation lives in `ir/style.ts` and happens at COMPILE time: what
|
|
6
|
+
* arrives here is final, scoped, compact CSS (StyleIR.css). That
|
|
7
|
+
* is what lets the precompiled-only `./runtime` build ship styles with
|
|
8
|
+
* no CSS preprocessor at all — see RFC-004 §1.
|
|
9
|
+
*/
|
|
10
|
+
export type StyleSettings = {
|
|
11
|
+
/** Final CSS — already scoped and preprocessed */
|
|
2
12
|
sheet?: string;
|
|
13
|
+
/** Marks a globally-injected sheet (prepended, so authors can override) */
|
|
3
14
|
meta?: boolean;
|
|
4
|
-
custom?: {
|
|
5
|
-
enabled: boolean;
|
|
6
|
-
allowedRules: string[];
|
|
7
|
-
allowedProperties: string[];
|
|
8
|
-
};
|
|
9
15
|
};
|
|
10
16
|
export default class Stylesheet {
|
|
11
17
|
private nsp;
|
|
12
18
|
private settings;
|
|
13
|
-
private $head;
|
|
14
19
|
constructor(nsp: string, settings?: StyleSettings);
|
|
20
|
+
private get rel();
|
|
21
|
+
/** Quoted, so a name can only ever select its own `<style>` */
|
|
22
|
+
private get styleElement();
|
|
15
23
|
/**
|
|
16
|
-
*
|
|
24
|
+
* Inject. `dindex` counts live instances sharing this namespace: it
|
|
25
|
+
* increases per instance and decreases on clear, so the element is
|
|
26
|
+
* removed only by the last one out.
|
|
17
27
|
*/
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
|
|
21
|
-
*/
|
|
22
|
-
private waitForStyles;
|
|
23
|
-
/**
|
|
24
|
-
* Compile and inject a style chunk in the DOM
|
|
25
|
-
* using `<style mv-style="*">...</style>` tag
|
|
26
|
-
*/
|
|
27
|
-
private inject;
|
|
28
|
-
/**
|
|
29
|
-
* Load/inject predefined sheet to the document
|
|
30
|
-
*/
|
|
31
|
-
load(settings: StyleSettings): Promise<void>;
|
|
32
|
-
/**
|
|
33
|
-
* Retreive this view's main node styles including natively
|
|
34
|
-
* defined ones.
|
|
35
|
-
*/
|
|
36
|
-
get(): void;
|
|
37
|
-
/**
|
|
38
|
-
* Remove all injected styles from the DOM
|
|
39
|
-
*/
|
|
40
|
-
clear(): Promise<void>;
|
|
41
|
-
/**
|
|
42
|
-
* Return css custom properties
|
|
43
|
-
*/
|
|
44
|
-
custom(): Promise<Record<string, string>>;
|
|
45
|
-
/**
|
|
46
|
-
* Overridable function to return an element
|
|
47
|
-
* style attribute value as JSON object.
|
|
48
|
-
*/
|
|
49
|
-
style(): Promise<Record<string, string>>;
|
|
28
|
+
load(settings: StyleSettings): HTMLStyleElement | undefined;
|
|
29
|
+
/** Release this instance's reference; removes the element at zero */
|
|
30
|
+
clear(): void;
|
|
50
31
|
}
|
|
51
|
-
export {};
|
package/dist/types/types.d.ts
CHANGED
|
@@ -1,211 +1,202 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Public types.
|
|
3
|
+
*
|
|
4
|
+
* Component authoring shape — the same plain object the framework has
|
|
5
|
+
* always taken, and the serializable artifact a generator can emit:
|
|
6
|
+
*
|
|
7
|
+
* { default, state, handler, _static, context, macros, stylesheet }
|
|
8
|
+
*
|
|
9
|
+
* These are the types `register`/`render`/`root` actually accept: the
|
|
10
|
+
* facade is generic over `Metavars`, so `Template<MT>` here and the
|
|
11
|
+
* argument the engine takes are the same type, not parallel ones.
|
|
12
|
+
*/
|
|
13
|
+
import type { MessageFormat, Model } from 'messageformat';
|
|
14
|
+
import type { MessageFunction } from 'messageformat/functions';
|
|
15
|
+
import type { TemplateIR } from './ir/compiler';
|
|
16
|
+
import type { StyleIR } from './ir/style';
|
|
17
|
+
import type { Untrusted } from './ir/policy';
|
|
18
|
+
/**
|
|
19
|
+
* The four typed surfaces of a component. Defaults are permissive on
|
|
20
|
+
* purpose: an untyped `lips.render('x', { state: { n: 0 } })` still
|
|
21
|
+
* gets `c.state.n` without annotation, and a component that declares
|
|
22
|
+
* its metavars gets exact types. Tightening these to `{}` would turn
|
|
23
|
+
* every unannotated read into a compile error.
|
|
24
|
+
*/
|
|
25
|
+
export interface Metavars<Input extends Object = Record<string, any>, State extends Object = Record<string, any>, Static extends Object = Record<string, any>, Context extends Object = Record<string, any>> {
|
|
5
26
|
Input: Input;
|
|
6
27
|
State: State;
|
|
7
28
|
Static: Static;
|
|
8
29
|
Context: Context;
|
|
9
30
|
}
|
|
10
|
-
export
|
|
11
|
-
|
|
31
|
+
export type LifeCycleEventTypes = 'onCreate' | 'onInput' | 'onMount' | 'onRender' | 'onUpdate' | 'onAttach' | 'onDetach' | 'onContext' | 'onError' | 'onDestroy';
|
|
32
|
+
/**
|
|
33
|
+
* `this` inside a handler: reactive stores plus the component's
|
|
34
|
+
* own API (emit/on/off, setContext).
|
|
35
|
+
*/
|
|
36
|
+
export interface ComponentSelf<MT extends Metavars = Metavars> {
|
|
12
37
|
state: MT['State'];
|
|
38
|
+
input: MT['Input'];
|
|
13
39
|
context: MT['Context'];
|
|
40
|
+
static: MT['Static'];
|
|
41
|
+
/** Live root elements of this component */
|
|
42
|
+
readonly node: Element[];
|
|
43
|
+
/**
|
|
44
|
+
* Active language, read reactively — a bind that reads it re-renders
|
|
45
|
+
* on `setLanguage()`. Component-grained: a component under
|
|
46
|
+
* `<i18n lang=…>` reports the scoped language, but an `<i18n>` block
|
|
47
|
+
* inside this component's own template does not change it (RFC-005 §2).
|
|
48
|
+
*/
|
|
49
|
+
readonly lang: string;
|
|
50
|
+
/** Switches the language for the whole app — the single writer */
|
|
51
|
+
setLanguage(lang: string): void;
|
|
52
|
+
/** Reaches both this component's own listeners and external ones */
|
|
53
|
+
emit(event: string, ...args: any[]): void;
|
|
54
|
+
/**
|
|
55
|
+
* Also the inbound channel: a listener registered here receives
|
|
56
|
+
* `component.emit(…)` calls made by whoever holds the handle.
|
|
57
|
+
*/
|
|
58
|
+
on(event: string, fn: (...args: any[]) => void): ComponentSelf<MT>;
|
|
59
|
+
once(event: string, fn: (...args: any[]) => void): ComponentSelf<MT>;
|
|
60
|
+
off(event: string, fn?: (...args: any[]) => void): ComponentSelf<MT>;
|
|
61
|
+
setContext(arg: string | Record<string, any>, value?: any): void;
|
|
62
|
+
/** Sibling handlers, reachable as `this.otherMethod()` */
|
|
63
|
+
[key: string]: any;
|
|
14
64
|
}
|
|
15
|
-
export type Variable = {
|
|
16
|
-
value: any;
|
|
17
|
-
type: 'let' | 'const' | 'arg';
|
|
18
|
-
};
|
|
19
|
-
export type VariableArguments = Record<string, any>;
|
|
20
|
-
export type VariableSet = Record<string, Variable> & {
|
|
21
|
-
__arguments__?: VariableArguments;
|
|
22
|
-
};
|
|
23
|
-
export interface SpreadOpeartor {
|
|
24
|
-
each(key: string, value: any): void;
|
|
25
|
-
nullify?: (attrs: string[]) => void;
|
|
26
|
-
get keystore(): string[];
|
|
27
|
-
set keystore(__: string[]);
|
|
28
|
-
memo: VariableSet;
|
|
29
|
-
}
|
|
30
|
-
export type I18nVariant = Record<string, string>;
|
|
31
|
-
export type I18nFormat = {
|
|
32
|
-
type: string;
|
|
33
|
-
value: string | I18nVariant | Record<string, string | I18nVariant>;
|
|
34
|
-
};
|
|
35
|
-
export type Dictionary = Record<string, string | I18nFormat | I18nVariant>;
|
|
36
|
-
export type DeclarationTagType = 'nexted' | 'child';
|
|
37
|
-
export type DeclarationTag = {
|
|
38
|
-
type: DeclarationTagType;
|
|
39
|
-
many?: boolean;
|
|
40
|
-
alts?: string[];
|
|
41
|
-
optional?: boolean;
|
|
42
|
-
};
|
|
43
|
-
export type Declaration = {
|
|
44
|
-
name: string;
|
|
45
|
-
syntax?: boolean;
|
|
46
|
-
iterator?: boolean;
|
|
47
|
-
contents?: boolean;
|
|
48
|
-
tags?: Record<string, DeclarationTag>;
|
|
49
|
-
};
|
|
50
|
-
export type LifeCycleEventTypes = 'onCreate' | 'onInput' | 'onMount' | 'onRender' | 'onUpdate' | 'onAttach' | 'onDetach' | 'onContext' | 'onDestroy';
|
|
51
65
|
export interface LifecycleEvents<MT extends Metavars> {
|
|
52
|
-
onCreate
|
|
53
|
-
onInput
|
|
54
|
-
onMount
|
|
55
|
-
onRender
|
|
56
|
-
onUpdate
|
|
57
|
-
onAttach
|
|
58
|
-
onDetach
|
|
59
|
-
onContext
|
|
60
|
-
|
|
66
|
+
onCreate(this: ComponentSelf<MT>): void;
|
|
67
|
+
onInput(this: ComponentSelf<MT>): void;
|
|
68
|
+
onMount(this: ComponentSelf<MT>): void;
|
|
69
|
+
onRender(this: ComponentSelf<MT>): void;
|
|
70
|
+
onUpdate(this: ComponentSelf<MT>): void;
|
|
71
|
+
onAttach(this: ComponentSelf<MT>): void;
|
|
72
|
+
onDetach(this: ComponentSelf<MT>): void;
|
|
73
|
+
onContext(this: ComponentSelf<MT>): void;
|
|
74
|
+
onError(this: ComponentSelf<MT>, error: Error): void;
|
|
75
|
+
onDestroy(this: ComponentSelf<MT>): void;
|
|
61
76
|
}
|
|
62
77
|
export type Handler<MT extends Metavars> = Partial<LifecycleEvents<MT>> & {
|
|
63
|
-
[K in string as K extends keyof LifecycleEvents<MT> ? never : K]?: (this:
|
|
78
|
+
[K in string as K extends keyof LifecycleEvents<MT> ? never : K]?: (this: ComponentSelf<MT>, ...args: any[]) => any;
|
|
64
79
|
};
|
|
65
|
-
export type Template<MT extends Metavars> = {
|
|
80
|
+
export type Template<MT extends Metavars = Metavars> = {
|
|
81
|
+
/** Template source — the component's markup */
|
|
66
82
|
default?: string;
|
|
83
|
+
/** Precompiled template IR — used instead of `default` (see `precompile`) */
|
|
84
|
+
ir?: TemplateIR;
|
|
67
85
|
state?: MT['State'];
|
|
86
|
+
/**
|
|
87
|
+
* Constants — read as `this.static` in a handler and `static.x` in a
|
|
88
|
+
* template. `_static` is the same field: a NAMED MODULE EXPORT cannot
|
|
89
|
+
* be called `static` (it is reserved in strict mode, and ES modules
|
|
90
|
+
* are always strict), so the underscore exists for that form only.
|
|
91
|
+
* Object literals should use `static`.
|
|
92
|
+
*/
|
|
93
|
+
static?: MT['Static'];
|
|
68
94
|
_static?: MT['Static'];
|
|
95
|
+
/**
|
|
96
|
+
* Context fields whose change fires this component's `onContext`.
|
|
97
|
+
*
|
|
98
|
+
* It does NOT declare what the component reads: bindings that read
|
|
99
|
+
* `context.x` are tracked individually and update whether or not `x`
|
|
100
|
+
* is listed here. The old spelling for this was `context`, which read
|
|
101
|
+
* as "the context this component uses" and misled accordingly.
|
|
102
|
+
*/
|
|
103
|
+
watchContext?: string[];
|
|
104
|
+
/** @deprecated Renamed to `watchContext` — same meaning (RFC-005 §4.3) */
|
|
69
105
|
context?: string[];
|
|
106
|
+
/** `<macro [argv] name="X">…</macro>` definitions, inlined at compile time */
|
|
70
107
|
macros?: string;
|
|
71
108
|
handler?: Handler<MT>;
|
|
109
|
+
/** Scoped CSS — declaration values may be `{expr}` (RFC-004) */
|
|
72
110
|
stylesheet?: string;
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
export type DynamicTemplate<MT extends Metavars> = {
|
|
76
|
-
name?: string;
|
|
77
|
-
template?: Template<MT>;
|
|
111
|
+
/** Precompiled StyleIR — used instead of `stylesheet` (see `precompile`) */
|
|
112
|
+
style?: StyleIR;
|
|
78
113
|
};
|
|
79
|
-
export type
|
|
80
|
-
input?: MT['Input'];
|
|
81
|
-
state?: MT['State'];
|
|
82
|
-
context?: MT['Context'];
|
|
83
|
-
_static?: MT['Static'];
|
|
84
|
-
macros?: string;
|
|
85
|
-
handler?: Handler<MT>;
|
|
86
|
-
stylesheet?: string;
|
|
87
|
-
declaration?: Declaration;
|
|
88
|
-
};
|
|
89
|
-
export type ComponentOptions<Context extends Object> = {
|
|
90
|
-
lips: Lips<Context>;
|
|
91
|
-
debug?: boolean;
|
|
92
|
-
prepath?: string;
|
|
93
|
-
boundaries?: FragmentBoundaries;
|
|
94
|
-
};
|
|
95
|
-
export type LipsConfig<Context extends Object> = {
|
|
114
|
+
export type LipsConfig<Context extends Object = {}> = {
|
|
96
115
|
debug?: boolean;
|
|
97
116
|
context?: Context;
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
117
|
+
/** Reserved for engine selection; the IR engine is the only one shipped */
|
|
118
|
+
engine?: string;
|
|
119
|
+
/**
|
|
120
|
+
* Initial i18n language, e.g. 'fr-FR'. Defaults to `navigator.language`,
|
|
121
|
+
* falling back to 'en-US' where there is no navigator (SSR, workers).
|
|
122
|
+
* Set it when the language comes from the app — a user preference, a
|
|
123
|
+
* URL segment, a server-rendered locale — rather than from the browser.
|
|
124
|
+
* Change it later with `lips.setLanguage()`.
|
|
125
|
+
*/
|
|
126
|
+
lang?: string;
|
|
127
|
+
/**
|
|
128
|
+
* Emit component sheets inside `@layer <name>` (RFC-004 §9). Absent by
|
|
129
|
+
* default, and absent output is byte-identical to no layer at all —
|
|
130
|
+
* only utility-framework users (Tailwind) need this, because unlayered
|
|
131
|
+
* styles beat layered ones regardless of specificity.
|
|
132
|
+
*/
|
|
133
|
+
styleLayer?: string;
|
|
134
|
+
/**
|
|
135
|
+
* CSS preprocessor for component stylesheets. Absent, the sheet ships
|
|
136
|
+
* nested and the browser's own CSS nesting resolves the scope wrap —
|
|
137
|
+
* Chrome/Edge 112+, Safari 16.5+, Firefox 117+ — 1.9 KB gzipped
|
|
138
|
+
* lighter. Older engines drop a nested sheet whole.
|
|
139
|
+
*
|
|
140
|
+
* import { stylisPreprocessor } from '@lipsjs/lips/stylis'
|
|
141
|
+
* new Lips({ stylePreprocessor: stylisPreprocessor })
|
|
142
|
+
*
|
|
143
|
+
* Wire it to flatten for pre-nesting engines, or pass a preprocessor
|
|
144
|
+
* of your own: it receives the scoped sheet, comments kept, with the
|
|
145
|
+
* at-rules that cannot nest already hoisted. `@import`, `@charset` and
|
|
146
|
+
* `@namespace` are placed ahead of its output as written. It is passed
|
|
147
|
+
* here rather than imported for its side effect because the two
|
|
148
|
+
* entries are separate bundles with separate module state.
|
|
149
|
+
*/
|
|
150
|
+
stylePreprocessor?: (css: string) => string;
|
|
151
|
+
/**
|
|
152
|
+
* The MessageFormat 2 engine dictionaries are formatted with. The full
|
|
153
|
+
* build wires it in; the precompiled `./runtime` entry ships without it
|
|
154
|
+
* (~7.2 KB gzipped), so an app that translates passes it:
|
|
155
|
+
*
|
|
156
|
+
* import { messageFormat } from '@lipsjs/lips/i18n'
|
|
157
|
+
* new Lips({ messageFormat })
|
|
158
|
+
*
|
|
159
|
+
* Without one, registering a dictionary is refused rather than read
|
|
160
|
+
* some other way. Passed by value for the same reason as
|
|
161
|
+
* `stylePreprocessor`: the entries are separate bundles.
|
|
162
|
+
*/
|
|
163
|
+
messageFormat?: MessageFormatEngine;
|
|
164
|
+
/**
|
|
165
|
+
* Expression execution, for templates you trust:
|
|
166
|
+
* - 'compiled' (default) — one cached Function per expression
|
|
167
|
+
* - 'interpreted' — an AST walker that never builds a Function, for a
|
|
168
|
+
* CSP without `unsafe-eval`. CSP-safe, NOT a sandbox: a template run
|
|
169
|
+
* this way can still reach anything it can name a path to.
|
|
170
|
+
*/
|
|
171
|
+
mode?: 'compiled' | 'interpreted';
|
|
172
|
+
/**
|
|
173
|
+
* Every template this instance renders is one you did not write
|
|
174
|
+
* (RFC-007). It reaches only the data and functions it is handed, the
|
|
175
|
+
* globals the policy offers, and its own subtree through the template
|
|
176
|
+
* language; refusals are diagnostics.
|
|
177
|
+
*
|
|
178
|
+
* import { untrusted, untrustedPolicy } from '@lipsjs/lips/untrusted'
|
|
179
|
+
* new Lips({ untrusted: untrusted() })
|
|
180
|
+
* new Lips({ untrusted: untrusted({ ...untrustedPolicy, url: sameOriginOnly }) })
|
|
181
|
+
*
|
|
182
|
+
* Passed by value, like `messageFormat`: an app that never renders an
|
|
183
|
+
* untrusted template ships none of it. Runs interpreted — `mode:
|
|
184
|
+
* 'compiled'` is refused. On `./runtime` templates must be precompiled;
|
|
185
|
+
* their skeletons are checked when first used.
|
|
186
|
+
*/
|
|
187
|
+
untrusted?: Untrusted;
|
|
108
188
|
};
|
|
109
189
|
export type EventListener = (...args: any[]) => void;
|
|
110
|
-
export type Macro = {
|
|
111
|
-
argv: string[];
|
|
112
|
-
$node: Cash;
|
|
113
|
-
};
|
|
114
|
-
export type SyntaxAttributes = {
|
|
115
|
-
literals: Record<string, any>;
|
|
116
|
-
expressions: Record<string, any>;
|
|
117
|
-
map: {
|
|
118
|
-
explicitAttrs: string[];
|
|
119
|
-
spreadAttrs: string[];
|
|
120
|
-
beforeSpreadAttrs: string[];
|
|
121
|
-
afterSpreadAttrs: string[];
|
|
122
|
-
metaAttrs: string[];
|
|
123
|
-
};
|
|
124
|
-
};
|
|
125
|
-
export interface VirtualEvent<MT extends Metavars> {
|
|
126
|
-
element: Cash | Component<MT>;
|
|
127
|
-
_event: string;
|
|
128
|
-
instruction: string;
|
|
129
|
-
nodepath: string;
|
|
130
|
-
scope?: Record<string, any>;
|
|
131
|
-
get __dependencies__(): FGUDependencies;
|
|
132
|
-
}
|
|
133
190
|
/**
|
|
134
|
-
*
|
|
191
|
+
* A Unicode MessageFormat 2 message: its source, or its data model as JSON
|
|
192
|
+
* (what `parseMessage` makes of it, and what a server that parsed it once
|
|
193
|
+
* serves).
|
|
135
194
|
*/
|
|
136
|
-
export type
|
|
137
|
-
|
|
138
|
-
export
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
nodepath: string;
|
|
145
|
-
deppath?: string;
|
|
146
|
-
target: FGUDTarget;
|
|
147
|
-
$fragment: Cash | null;
|
|
148
|
-
boundaries?: FragmentBoundaries;
|
|
149
|
-
haslet?: boolean;
|
|
150
|
-
syntax?: boolean;
|
|
151
|
-
partial?: string[];
|
|
152
|
-
priority?: number;
|
|
153
|
-
level?: number;
|
|
154
|
-
garbage?: boolean;
|
|
155
|
-
update: (memo: VariableSet, by?: string) => FGUSync | void;
|
|
156
|
-
}
|
|
157
|
-
export type FGUDependencies = Map<string, Map<string, FGUDependency>>;
|
|
158
|
-
export type FGUDBatchEntry = {
|
|
159
|
-
dep: string;
|
|
160
|
-
deppath: string;
|
|
161
|
-
priority?: number;
|
|
162
|
-
};
|
|
163
|
-
export type FGUDMemorySlot = {
|
|
164
|
-
tracks: Map<string, number>;
|
|
165
|
-
memo: VariableSet;
|
|
166
|
-
};
|
|
167
|
-
export type FGUDMemory = Map<string, FGUDMemorySlot>;
|
|
168
|
-
export interface I18nDependency {
|
|
169
|
-
nodetype: NodeType;
|
|
170
|
-
nodepath: string;
|
|
171
|
-
deppath?: string;
|
|
172
|
-
target: FGUDTarget;
|
|
173
|
-
$fragment: Cash;
|
|
174
|
-
priority?: number;
|
|
175
|
-
update: (memo: VariableSet, by?: string) => FGUSync | void;
|
|
176
|
-
}
|
|
177
|
-
export type RenderedNode<MT extends Metavars> = {
|
|
178
|
-
$log: Cash;
|
|
179
|
-
dependencies: FGUDependencies;
|
|
180
|
-
events?: VirtualEvent<MT>[];
|
|
181
|
-
};
|
|
182
|
-
export type FragmentBoundaries = {
|
|
183
|
-
start: Comment;
|
|
184
|
-
end: Comment;
|
|
185
|
-
};
|
|
186
|
-
export interface MeshRenderer {
|
|
187
|
-
path: string | null;
|
|
188
|
-
argv: string[];
|
|
189
|
-
mesh(argvalues?: VariableSet, scope?: VariableSet, suffix?: string): Cash | null;
|
|
190
|
-
update(deps: string[], argvalues: VariableSet, scope: VariableSet, boundaries?: FragmentBoundaries, suffix?: string): void;
|
|
191
|
-
cleanup(boundaries?: FragmentBoundaries, suffix?: string | true): void;
|
|
192
|
-
demarcate($log: Cash, sufix: string): {
|
|
193
|
-
$partial: Cash;
|
|
194
|
-
boundaries: FragmentBoundaries;
|
|
195
|
-
};
|
|
196
|
-
fill($log: Cash, boundaries?: FragmentBoundaries): void;
|
|
197
|
-
}
|
|
198
|
-
export type MeshTemplate = Record<string, any> & {
|
|
199
|
-
renderer: MeshRenderer;
|
|
200
|
-
};
|
|
201
|
-
export interface MeshWireSetup {
|
|
202
|
-
argv: string[];
|
|
203
|
-
scope: VariableSet;
|
|
204
|
-
declaration?: Declaration;
|
|
205
|
-
useAttributes: boolean;
|
|
206
|
-
xmlns?: boolean;
|
|
207
|
-
$node: Cash;
|
|
208
|
-
meshPath: string | null;
|
|
209
|
-
fragmentPath: string;
|
|
210
|
-
fragmentBoundaries: FragmentBoundaries;
|
|
211
|
-
}
|
|
195
|
+
export type Message = string | Model.Message;
|
|
196
|
+
/** `messageformat`'s formatter and the functions a message may call — what `@lipsjs/lips/i18n` exports as `messageFormat`. */
|
|
197
|
+
export type MessageFormatEngine = {
|
|
198
|
+
MessageFormat: typeof MessageFormat;
|
|
199
|
+
functions: Record<string, MessageFunction<any, any>>;
|
|
200
|
+
};
|
|
201
|
+
/** One language's messages, by stable key or by source text. */
|
|
202
|
+
export type Dictionary = Record<string, Message>;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Untrusted templates (RFC-007) — an entry of its own, passed to Lips by
|
|
3
|
+
* value so an app that never renders one ships none of it:
|
|
4
|
+
*
|
|
5
|
+
* import Lips from '@lipsjs/lips'
|
|
6
|
+
* import { untrusted, untrustedPolicy } from '@lipsjs/lips/untrusted'
|
|
7
|
+
*
|
|
8
|
+
* const embed = new Lips({ untrusted: untrusted() })
|
|
9
|
+
* const strict = new Lips({ untrusted: untrusted({ ...untrustedPolicy, url: sameOriginOnly }) })
|
|
10
|
+
*
|
|
11
|
+
* `checkTemplate( policy )` is the compile-time half on its own, for a
|
|
12
|
+
* build step or a generator that wants the diagnostics:
|
|
13
|
+
*
|
|
14
|
+
* compileTemplate( src, { check: checkTemplate( untrustedPolicy ) } )
|
|
15
|
+
*/
|
|
16
|
+
export { untrusted, untrustedPolicy, checkTemplate } from './ir/policy';
|
|
17
|
+
export type { TemplatePolicy, Refusal, Verdict, Untrusted } from './ir/policy';
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
var G=["===","!==","...","=>","==","!=","<=",">=","&&","||","??","?.","++","--","+=","-=","*=","/=","%=","+","-","*","/","%","<",">","!","?",":",".",",","(",")","[","]","{","}","="];function z(t,e){let r=[],s=0,f=(g)=>/[A-Za-z_$]/.test(g),m=(g)=>/[A-Za-z0-9_$]/.test(g);while(s<t.length){let g=t[s];if(/\s/.test(g)){s++;continue}if(/[0-9]/.test(g)||g==="."&&/[0-9]/.test(t[s+1])){let p=s;while(s<t.length&&/[0-9]/.test(t[s]))s++;if(t[s]==="."){s++;while(s<t.length&&/[0-9]/.test(t[s]))s++}if(t[s]==="e"||t[s]==="E"){if(s++,t[s]==="+"||t[s]==="-")s++;while(s<t.length&&/[0-9]/.test(t[s]))s++}r.push({t:"num",value:t.slice(p,s),start:p,end:s});continue}if(g==="'"||g==='"'){let p=s;s++;let l="",o=!1;while(s<t.length){let n=t[s];if(n==="\\"){let a=t[s+1],c={n:`
|
|
2
|
+
`,t:"\t",r:"\r",b:"\b",f:"\f",v:"\v","0":"\x00"};if(a==="u"){let h=t.slice(s+2,s+6);l+=String.fromCharCode(parseInt(h,16)||0),s+=6}else l+=c[a]??a,s+=2;continue}if(n===g){o=!0,s++;break}l+=n,s++}if(!o)e.push({code:"LIPS-E001",message:"Unterminated string literal",loc:{offset:p,length:s-p}});r.push({t:"str",value:l,start:p,end:s});continue}if(f(g)){let p=s;while(s<t.length&&m(t[s]))s++;r.push({t:"id",value:t.slice(p,s),start:p,end:s});continue}let d=G.find((p)=>t.startsWith(p,s));if(d==="?."&&/[0-9]/.test(t[s+2]??""))d="?";if(d){r.push({t:"punct",value:d,start:s,end:s+d.length}),s+=d.length;continue}e.push({code:"LIPS-E002",message:`Unexpected character '${g}'`,loc:{offset:s,length:1}}),s++}return r.push({t:"eof",value:"",start:t.length,end:t.length}),r}class C{tokens;diagnostics;pos=0;constructor(t,e){this.tokens=t;this.diagnostics=e}peek(t=0){return this.tokens[Math.min(this.pos+t,this.tokens.length-1)]}next(){return this.tokens[this.pos++]??this.tokens[this.tokens.length-1]}at(t){let e=this.peek();return e.t==="punct"&&e.value===t}eat(t){if(this.at(t))return this.pos++,!0;return!1}error(t,e,r=this.peek()){return this.diagnostics.push({code:t,message:e,loc:{offset:r.start,length:Math.max(1,r.end-r.start)}}),{t:"error"}}expect(t,e){if(!this.eat(t))this.error(e,`Expected '${t}'`)}parse(){let t=this.assign();if(this.peek().t!=="eof")this.error("LIPS-E003",`Unexpected token '${this.peek().value}' after expression`);return t}isArrowAhead(){let t=this.peek();if(t.t==="id"){let e=this.peek(1);return e.t==="punct"&&e.value==="=>"}if(t.t==="punct"&&t.value==="("){let e=0,r=0;while(!0){let s=this.peek(r);if(s.t==="eof")return!1;if(s.t==="punct"&&s.value==="(")e++;if(s.t==="punct"&&s.value===")"){if(e--,e===0){let f=this.peek(r+1);return f.t==="punct"&&f.value==="=>"}}r++}}return!1}assign(){if(this.isArrowAhead()){let r=[];if(this.peek().t==="id")r.push(this.next().value);else{this.expect("(","LIPS-E004");while(!this.at(")")&&this.peek().t!=="eof"){let s=this.next();if(s.t!=="id")return this.error("LIPS-E005","Invalid arrow parameter",s);if(r.push(s.value),!this.eat(","))break}this.expect(")","LIPS-E004")}return this.expect("=>","LIPS-E004"),{t:"arrow",params:r,body:this.assign()}}let t=this.conditional(),e=this.peek();if(e.t==="punct"&&["=","+=","-=","*=","/=","%="].includes(e.value)){if(t.t!=="id"&&t.t!=="member")return this.error("LIPS-E006","Invalid assignment target",e);return this.next(),{t:"assign",op:e.value,target:t,value:this.assign()}}return t}conditional(){let t=this.nullish();if(this.eat("?")){let e=this.assign();return this.expect(":","LIPS-E007"),{t:"cond",test:t,cons:e,alt:this.assign()}}return t}nullish(){let t=this.or();while(this.at("??"))this.next(),t={t:"logic",op:"??",l:t,r:this.or()};return t}or(){let t=this.and();while(this.at("||"))this.next(),t={t:"logic",op:"||",l:t,r:this.and()};return t}and(){let t=this.equality();while(this.at("&&"))this.next(),t={t:"logic",op:"&&",l:t,r:this.equality()};return t}equality(){let t=this.relational();while(["===","!==","==","!="].some((e)=>this.at(e)))t={t:"bin",op:this.next().value,l:t,r:this.relational()};return t}relational(){let t=this.additive();while(["<=",">=","<",">"].some((e)=>this.at(e)))t={t:"bin",op:this.next().value,l:t,r:this.additive()};return t}additive(){let t=this.multiplicative();while(this.at("+")||this.at("-"))t={t:"bin",op:this.next().value,l:t,r:this.multiplicative()};return t}multiplicative(){let t=this.unary();while(this.at("*")||this.at("/")||this.at("%"))t={t:"bin",op:this.next().value,l:t,r:this.unary()};return t}unary(){if(this.at("!")||this.at("-")||this.at("+"))return{t:"unary",op:this.next().value,arg:this.unary()};if(this.at("++")||this.at("--")){let t=this.next().value,e=this.unary();if(e.t!=="id"&&e.t!=="member")return this.error("LIPS-E006","Invalid update target");return{t:"update",op:t,arg:e,prefix:!0}}return this.postfix()}postfix(){let t=this.callMember();if(this.at("++")||this.at("--")){let e=this.next().value;if(t.t!=="id"&&t.t!=="member")return this.error("LIPS-E006","Invalid update target");t={t:"update",op:e,arg:t,prefix:!1}}return t}callMember(){let t=this.primary();while(!0)if(this.eat(".")){let e=this.next();if(e.t!=="id")return this.error("LIPS-E008","Expected property name",e);t={t:"member",obj:t,prop:e.value,computed:!1,optional:!1,at:e.start}}else if(this.eat("?."))if(this.at("("))t={t:"call",callee:t,args:this.argList(),optional:!0};else if(this.eat("[")){let e=this.peek().start,r=this.assign();this.expect("]","LIPS-E009"),t={t:"member",obj:t,prop:r,computed:!0,optional:!0,at:e}}else{let e=this.next();if(e.t!=="id")return this.error("LIPS-E008","Expected property name",e);t={t:"member",obj:t,prop:e.value,computed:!1,optional:!0,at:e.start}}else if(this.eat("[")){let e=this.peek().start,r=this.assign();this.expect("]","LIPS-E009"),t={t:"member",obj:t,prop:r,computed:!0,optional:!1,at:e}}else if(this.at("("))t={t:"call",callee:t,args:this.argList(),optional:!1};else break;return t}argList(){this.expect("(","LIPS-E010");let t=[];while(!this.at(")")&&this.peek().t!=="eof")if(t.push(this.assign()),!this.eat(","))break;return this.expect(")","LIPS-E010"),t}primary(){let t=this.peek();if(t.t==="num")return this.next(),{t:"lit",v:parseFloat(t.value)};if(t.t==="str")return this.next(),{t:"lit",v:t.value};if(t.t==="id")switch(this.next(),t.value){case"true":return{t:"lit",v:!0};case"false":return{t:"lit",v:!1};case"null":return{t:"lit",v:null};case"undefined":return{t:"lit",v:void 0};case"NaN":return{t:"lit",v:NaN};case"Infinity":return{t:"lit",v:1/0};default:return{t:"id",name:t.value,at:t.start}}if(this.eat("(")){let e=this.assign();return this.expect(")","LIPS-E010"),e}if(this.eat("[")){let e=[];while(!this.at("]")&&this.peek().t!=="eof"){let r=this.eat("...");if(e.push({spread:r||void 0,value:this.assign()}),!this.eat(","))break}return this.expect("]","LIPS-E009"),{t:"arr",items:e}}if(this.eat("{")){let e=[];while(!this.at("}")&&this.peek().t!=="eof"){if(this.eat("..."))e.push({spread:!0,value:this.assign()});else{let r=this.next();if(r.t!=="id"&&r.t!=="str"&&r.t!=="num")return this.error("LIPS-E011","Invalid object key",r);if(this.eat(":"))e.push({key:String(r.value),value:this.assign(),at:r.start});else if(r.t==="id")e.push({key:r.value,value:{t:"id",name:r.value,at:r.start},at:r.start});else return this.error("LIPS-E011","Invalid shorthand property",r)}if(!this.eat(","))break}return this.expect("}","LIPS-E011"),{t:"obj",props:e}}return this.next(),this.error("LIPS-E012",t.t==="eof"?"Unexpected end of expression":`Unexpected token '${t.value}'`,t)}}function S(t){let e=[],r=z(t,e);return{ast:new C(r,e).parse(),diagnostics:e}}function A(t){let e=[],r=0,s=0;for(let f=0;f<t.length;f++){let m=t[f];if(m==="'"||m==='"'||m==="`"){f++;while(f<t.length&&t[f]!==m){if(t[f]==="\\")f++;f++}continue}if(m==="("||m==="["||m==="{")r++;else if(m===")"||m==="]"||m==="}")r--;else if(m===","&&r===0)e.push(t.slice(s,f)),s=f+1}return e.push(t.slice(s)),e.map((f)=>f.trim()).filter(Boolean)}var j=new Set(["if","else-if","else","for","switch","async","let","const","log","context","i18n"]),O=new Set(["case","default","then","catch","loading"]),L=new Set(["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","label","legend","li","link","main","map","mark","menu","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","slot","small","source","span","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr","svg","circle","clippath","defs","ellipse","foreignobject","g","image","line","lineargradient","marker","mask","path","pattern","polygon","polyline","radialgradient","rect","stop","symbol","text","tspan","use"]);var _=new WeakMap,M={clone(t){let e=_.get(t);if(!e)e=document.createElement("template"),e.innerHTML=t.html,_.set(t,e);return e.content.cloneNode(!0)},fragment:()=>document.createDocumentFragment(),element:(t)=>document.createElement(t),text:(t)=>document.createTextNode(t),marker:(t)=>document.createComment(t),child:(t,e)=>t.childNodes[e],next:(t)=>t.nextSibling,range(t,e){let r=[];for(let s=t;s;s=s.nextSibling)if(r.push(s),s===e)break;return r},insert:(t,e,r)=>{t.insertBefore(e,r)},insertAfter(t,e){let r=t.parentNode;if(!r)return;let s=t;for(let f of e)r.insertBefore(f,s.nextSibling),s=f},remove:(t)=>t.remove(),isElement:(t)=>t.nodeType===1,connected:(t)=>t.isConnected,precedes:(t,e)=>!!(t.compareDocumentPosition(e)&4),attr:(t,e,r)=>r===null?t.removeAttribute(e):t.setAttribute(e,r),setText:(t,e)=>{t.data=e},content:(t,e)=>{t.textContent=e},html:(t,e)=>{t.innerHTML=e},styleVar:(t,e,r)=>r===null?t.style.removeProperty(e):t.style.setProperty(e,r),scope:(t,e)=>{t.hasAttribute("rel")||t.setAttribute("rel",e)},listen(t,e,r){return t.addEventListener(e,r),()=>t.removeEventListener(e,r)},keepFocus(){let t=document.activeElement;return()=>{t&&t.isConnected&&t!==document.activeElement&&t.focus()}}};var J=Symbol.for("lips.self"),H=(t,e,r)=>{let s=t.slice(0,e).split(`
|
|
3
|
+
`);return{line:s.length,col:s[s.length-1].length+1,offset:e,length:r}},k=(t,e,r)=>({code:t,message:e,hint:r}),w=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),U=new Set(["constructor","__proto__","prototype","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","caller","callee"]),K=new Set(["script","iframe","frame","frameset","object","embed","applet","portal","fencedframe","base","link","meta","style","title","head","body","html","template","noscript","noembed","noframes","xmp","plaintext","animate","animatemotion","animatetransform","set"]),X=new Set(["href","src","action","formaction","xlink:href","poster","cite","background","longdesc","manifest","data","codebase","lowsrc","dynsrc","icon"]),Z=new Set(["http","https","mailto","tel"]),B={srcdoc:"It is a whole document, written into an attribute",is:"It makes the element one the page defined, running the page's code",form:"It joins a form of the host page by id"},W=new WeakSet,I=(t)=>(W.add(t),Object.freeze(t)),E=(t,e)=>Object.fromEntries(e.map((r)=>[r,t[r]])),P=(t,e={})=>I(Object.assign((...r)=>t(...r),e)),Y={Math:I(E(Math,Object.getOwnPropertyNames(Math))),JSON:I(E(JSON,["parse","stringify"])),Object:I(E(Object,["keys","values","entries","fromEntries"])),Array:I(E(Array,["isArray","from","of"])),String:P(String,E(String,["fromCharCode","fromCodePoint"])),Number:P(Number,E(Number,["isFinite","isInteger","isNaN","isSafeInteger","parseFloat","parseInt","EPSILON","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER"])),Boolean:P(Boolean),Date:P(Date,E(Date,["now","parse","UTC"])),parseInt,parseFloat,isNaN,isFinite,encodeURIComponent,decodeURIComponent,encodeURI,decodeURI};function Q(t){let e="",r=0;while(r<t.length){let s=t[r];if(s==='"'||s==="'"){let f=r+1;while(f<t.length&&t[f]!==s)f+=t[f]==="\\"?2:1;e+=t.slice(r,f+1),r=f+1;continue}if(s==="/"&&t[r+1]==="*"){let f=t.indexOf("*/",r+2);r=f<0?t.length:f+2;continue}e+=s,r++}return e.replace(/\\(?:([\da-f]{1,6})[ \t\n\r\f]?|([^\n\r\f\da-f])|[\n\r\f])/gi,(s,f,m)=>f?String.fromCodePoint(Math.min(parseInt(f,16),1114111)||65533):m??"")}var tt=(t)=>t===globalThis||t===globalThis.eval||typeof t==="function"&&/^(Async|AsyncGenerator|Generator)?Function$/.test(t.name)&&t.prototype?.constructor===t||typeof Node==="function"&&t instanceof Node||typeof Event==="function"&&t instanceof Event||typeof EventTarget==="function"&&t instanceof EventTarget||typeof t==="object"&&(("nodeType"in t)&&("ownerDocument"in t)||t.window===t),T={globals:Y,member(t,e,r){if(U.has(t))return k("LIPS-U002",`'${t}' leads to prototypes and constructors, not data`,"An untrusted template reads and writes data; prototype machinery is not reachable");if(r!=null&&W.has(r)&&(e||!w(r,t)))return k("LIPS-U003",e?`Globals are read-only — '${t}' cannot be written`:`'${t}' is not offered`,"Offered: Math, JSON, Object.keys/values/entries/fromEntries, Array.isArray/from/of, String, Number, Boolean, Date, parseInt, parseFloat, isNaN, isFinite and the URI codecs")},self(t,e){if(e)return k("LIPS-U005",`self is read-only — '${t}' cannot be written`,"Write state instead: state.x = …");if(U.has(t))return this.member(t,!1);if(t==="node")return k("LIPS-U005","self.node holds the component's DOM nodes","An untrusted template reaches the page only through the template language")},value(t){if(t!==null&&(typeof t==="object"||typeof t==="function")&&tt(t))return k("LIPS-U004","A DOM node, window, event or code constructor cannot be held by an untrusted template","Hand the template data, not the platform object it came from")},event(t){let e=(r)=>r&&{value:r.value,checked:r.checked,name:r.name,id:r.id,type:r.type,tagName:r.tagName,dataset:{...r.dataset}};return{type:t.type,key:t.key,code:t.code,data:t.data,inputType:t.inputType,altKey:t.altKey,ctrlKey:t.ctrlKey,metaKey:t.metaKey,shiftKey:t.shiftKey,repeat:t.repeat,button:t.button,buttons:t.buttons,clientX:t.clientX,clientY:t.clientY,deltaX:t.deltaX,deltaY:t.deltaY,target:e(t.target),currentTarget:e(t.currentTarget),preventDefault:()=>t.preventDefault(),stopPropagation:()=>t.stopPropagation()}},tag(t){let e=t.toLowerCase();if(K.has(e))return k("LIPS-U010",`<${e}> is refused in an untrusted template`,"It runs script, holds a document of its own, or acts on the whole page");if(e.includes("-"))return k("LIPS-U011",`<${e}> is a custom element`,"Custom elements run the page's own code — a Lips component the host registered renders instead")},component(t){if(t==="router")return k("LIPS-U012","<router> owns the page URL and window.navigate","Switch on state for pages — <switch( state.page )>; routing stays with the host")},attr(t,e,r){let s=e.toLowerCase();if(s.startsWith("on"))return k("LIPS-U020",`'${e}' is an event-handler attribute`,"Use the instruction form: on-click( … )");if(w(B,s))return k("LIPS-U021",`'${e}' is refused`,B[s]);if(r===void 0)return;if((s==="id"||s==="name")&&typeof document==="object"&&r in document)return k("LIPS-U022",`${s}="${r}" would shadow document.${r}`,"Choose another value");if(s==="style")return this.css(r);if(X.has(s))return this.url(r);if(s==="srcset"||s==="imagesrcset"||s==="ping")for(let f of r.split(s==="ping"?/\s+/:",")){let m=f.trim()?this.url(f.trim().split(/\s+/)[0]):void 0;if(m)return m}},url(t){let e=String(t).replace(/[\t\n\r]/g,"").replace(/^[\u0000- ]+/,""),r=/^([a-z][a-z\d+.-]*):/i.exec(e)?.[1].toLowerCase();if(!r||Z.has(r)||/^data:image\/(png|gif|jpe?g|webp|avif|bmp)[;,]/i.test(e))return;return k("LIPS-U030",`'${r}:' URLs are refused`,"Use a relative, http(s), mailto: or tel: URL — or a raster data:image")},css(t){let e=Q(t);if(/@import\b/i.test(e))return k("LIPS-U040","@import loads a stylesheet outside the component scope","Write the rules into the stylesheet itself");if(/(?:^|[^\w-])(?:-webkit-|-moz-)?(?:image-set|image|cross-fade|element)\(/i.test(e))return k("LIPS-U041","image-set(), image(), cross-fade() and element() load without url()","Use url( … ), which is held to the URL rule");for(let r of e.matchAll(/\b(?:url|src)\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*))/gi)){let s=this.url((r[1]??r[2]??r[3]).trim());if(s)return s}},report(t){console.warn("[lips:untrusted]",t)}},et=new Set(["state","input","context","static","self","arguments"]),rt=new Set([...j,...O,"macro"]),R=new Set;function V(t,e,r,s,f=!1){let{ast:m,diagnostics:g}=S(e);if(g.length)return!0;let d=!0,p=(n,a=0,c=1)=>{if(n)d=!1,s(n,a,c)},l=(n,a)=>a.has(n)||r.has(n)||et.has(n)||w(t.globals,n);if(f&&m.t==="id"&&!l(m.name,R))return p(t.self(m.name),m.at,m.name.length),d;let o=(n,a,c=!1)=>{switch(n.t){case"id":l(n.name,a)||p(k("LIPS-U001",`'${n.name}' is not provided to an untrusted template`,"Expressions read state, input, context, static, self, their scope, and the globals the policy offers"),n.at,n.name.length);return;case"member":{o(n.obj,a),n.computed&&o(n.prop,a);let h=n.prop,i=!n.computed?n.prop:h.t==="lit"&&(typeof h.v==="string"||typeof h.v==="number")?String(h.v):void 0;if(i===void 0)return;let u=n.obj.t==="id"&&!a.has(n.obj.name)&&!r.has(n.obj.name)?n.obj.name:"";p(u==="self"?t.self(i,c):u&&w(t.globals,u)?t.member(i,c,t.globals[u]):t.member(i,c),n.at,i.length);return}case"call":o(n.callee,a),n.args.forEach((h)=>o(h,a));return;case"unary":o(n.arg,a);return;case"update":o(n.arg,a,!0);return;case"bin":case"logic":o(n.l,a),o(n.r,a);return;case"cond":o(n.test,a),o(n.cons,a),o(n.alt,a);return;case"assign":o(n.target,a,!0),o(n.value,a);return;case"arrow":o(n.body,new Set([...a,...n.params]));return;case"arr":n.items.forEach((h)=>o(h.value,a));return;case"obj":for(let h of n.props)h.key!==void 0&&p(t.member(h.key,!0),h.at,h.key.length),o(h.value,a)}};return o(m,R),d}function q(t=T){return(e,r,s)=>{let f=new Set,m=(i,u,b=1)=>r.push({...i,severity:"error",loc:H(s,u,b)}),g=(i,u)=>{let b=s.indexOf(i,u);return b<0?u:b},d=(i,u,b=!1)=>V(t,i,f,(x,y,v)=>m(x,u+y,v),b),p=(i,u,b=!0)=>{let x=!0,y=0;return A(i).forEach((v,N)=>{y=i.indexOf(v,y),x=d(v,u+y,b&&N===0)&&x,y+=v.length}),x},l=(i)=>{for(let u of i)if(typeof u!=="string"&&!d(u.expr,g(u.expr,u.loc.offset)))u.expr="undefined"},o=(i)=>L.has(i)?t.tag(i):t.component(i),n=(i)=>{for(let u of i){if(u.t==="fragment")n(u.children);if(u.t!=="element")continue;for(let b of u.attrs)b.k==="args"?b.names.forEach((x)=>f.add(x)):(u.tag==="let"||u.tag==="const")&&("name"in b)&&f.add(b.name);n(u.children)}},a=(i,u)=>{let b=i.loc.offset;switch(i.k){case"args":return!0;case"event":return p(i.source,g(i.source,b));case"spread":case"fn":return d(i.source,g(i.source,b))}if(u&&!/^(@(?!html$)|i18n(-|$))/.test(i.name)){let x=t.attr(u,i.name,i.k==="literal"?i.value:i.k==="bool"?"":void 0);if(x)return m(x,b,i.name.length),!1}if(i.name==="@format"){let x=i.k==="literal"?i.value:i.k==="expr"?i.source:i.k==="interp"?i.parts.map((v)=>typeof v==="string"?v:`{${v.expr}}`).join(""):"",y=x.slice(x.indexOf(",")+1).trim();return!x.includes(",")||d(y,g(y,b))}if(i.k==="expr"&&!d(i.source,g(i.source,b)))i.source="undefined";if(i.k==="interp")l(i.parts);return!0},c=(i)=>{let{tag:u}=i;if(u==="#dynamic"){let x=i.dynamicTag,y=g(x.expr,x.loc.offset);if(!d(x.expr,y))x.expr="undefined";else{let{ast:v}=S(x.expr),N=v.t==="lit"&&typeof v.v==="string"?o(v.v.toLowerCase()):void 0;if(N)return m(N,y,x.expr.length),!1}}else if(!rt.has(u)){let x=o(u);if(x)return m(x,i.loc.offset,u.length+1),!1}if(i.head){let x=i.head,y=g(x.expr,x.loc.offset);(u==="log"?p(x.expr,y,!1):d(x.expr,y))||(x.expr="undefined")}let b=L.has(u)?u:null;return i.attrs=i.attrs.filter((x)=>a(x,b)),!0},h=(i)=>{for(let u=0;u<i.length;u++){let b=i[u];if(b.t==="fragment")h(b.children);else if(b.t==="interp")l(b.parts);else if(b.t==="element")c(b)?h(b.children):i.splice(u--,1)}};n(e),h(e)}}var D=(t)=>Object.assign(Error(t.message),{name:"PolicyError"},t),F={"+":(t,e)=>t+e,"-":(t,e)=>t-e,"*":(t,e)=>t*e,"/":(t,e)=>t/e,"%":(t,e)=>t%e,"<":(t,e)=>t<e,">":(t,e)=>t>e,"<=":(t,e)=>t<=e,">=":(t,e)=>t>=e,"==":(t,e)=>t==e,"!=":(t,e)=>t!=e,"===":(t,e)=>t===e,"!==":(t,e)=>t!==e};function st(t){let e=(m)=>{if(m)throw D(m)},r=(m)=>(e(t.value(m)),m),s=(m)=>{if(typeof m==="string")return m;if(typeof m==="number")return String(m);throw D(k("LIPS-U002","A computed member must be a string or a number"))},f=(m,g,d)=>e(m!=null&&typeof m==="object"&&m[J]?t.self(g,d):t.member(g,d,m));return(m,g)=>{let d=g.scope,p=(n,a)=>{for(let c of a)if(n in c)return c[n];if(d&&n in d)return r(d[n]);switch(n){case"state":return g.state;case"input":return g.input;case"context":return g.context;case"static":return g.static;case"self":return g.self;case"arguments":return g.arguments}return w(t.globals,n)?t.globals[n]:void 0},l=(n,a,c)=>{if(n.t==="id"){let h=c.find((i)=>(n.name in i))??d;h&&(h[n.name]=a)}else if(n.t==="member"){let h=o(n.obj,c),i=s(n.computed?o(n.prop,c):n.prop);if(f(h,i,!0),h!=null)h[i]=a}return a},o=(n,a)=>{switch(n.t){case"lit":return n.v;case"id":return p(n.name,a);case"member":{let c=o(n.obj,a);if(n.optional&&c==null)return;let h=s(n.computed?o(n.prop,a):n.prop);return f(c,h,!1),c==null?void 0:r(c[h])}case"call":{let c=n.callee,h,i;if(c.t==="member"){if(h=o(c.obj,a),(c.optional||n.optional)&&h==null)return;let u=s(c.computed?o(c.prop,a):c.prop);f(h,u,!1),i=h==null?void 0:r(h[u])}else i=o(c,a);if(n.optional&&i==null)return;return r(Reflect.apply(i,h,n.args.map((u)=>o(u,a))))}case"unary":{let c=o(n.arg,a);return n.op==="!"?!c:n.op==="-"?-c:+c}case"update":{let c=o(n.arg,a),h=n.op==="++"?c+1:c-1;return l(n.arg,h,a),n.prefix?h:c}case"bin":return F[n.op](o(n.l,a),o(n.r,a));case"logic":{let c=o(n.l,a);return n.op==="&&"?c&&o(n.r,a):n.op==="||"?c||o(n.r,a):c??o(n.r,a)}case"cond":return o(n.test,a)?o(n.cons,a):o(n.alt,a);case"assign":return l(n.target,n.op==="="?o(n.value,a):F[n.op[0]](o(n.target,a),o(n.value,a)),a);case"arrow":return(...c)=>{let h=Object.create(null);return n.params.forEach((i,u)=>h[i]=r(c[u])),o(n.body,[h,...a])};case"arr":{let c=[];for(let h of n.items)h.spread?c.push(...o(h.value,a)):c.push(o(h.value,a));return c}case"obj":{let c={},h=(i,u)=>{f(c,i,!0),c[i]=u};for(let i of n.props){let u=o(i.value,a);if(!i.spread)h(i.key,u);else if(u!=null)for(let b of Object.keys(u))h(b,r(u[b]))}return c}}};return o(m,[])}}function nt(t,e=M){let r=new WeakMap,s=(p)=>(p&&t.report(p),!!p),f=(p)=>p.localName.toLowerCase(),m=(p,l)=>{let o=p.createElement("template");return o.setAttribute("data-lips-refused",l),o},g=(p)=>{for(let l of[...p.querySelectorAll("*")]){let o=f(l);if(s(t.tag(o))){let a=m(l.ownerDocument,o);a.append(...l.childNodes),l.replaceWith(a);continue}let n=!1;for(let{name:a,value:c}of[...l.attributes])if(s(t.attr(o,a,c)))l.removeAttribute(a),n||=a.toLowerCase()==="is";if(n){let a=l.ownerDocument.createElementNS(l.namespaceURI,l.localName);for(let c of[...l.attributes])a.setAttribute(c.name,c.value);a.append(...l.childNodes),l.replaceWith(a)}}},d=(p)=>{let l=document.createElement("template");return l.innerHTML=p,g(l.content),l};return{...e,clone(p){let l=r.get(p);if(!l)r.set(p,l=d(p.html));return l.content.cloneNode(!0)},element:(p)=>s(t.tag(p.toLowerCase()))?m(document,p):e.element(p),attr(p,l,o){e.attr(p,l,o!==null&&s(t.attr(f(p),l,o))?null:o)},html(p,l){s(t.attr(f(p),"@html",l))?e.content(p,""):p.replaceChildren(d(l).content)},styleVar(p,l,o){e.styleVar(p,l,o!==null&&s(t.css(o))?null:o)},listen:(p,l,o)=>e.listen(p,l,(n)=>o(t.event(n)))}}var it={ir:{v:1,exprs:[],root:{html:"",scope:[],binds:[],blocks:[]}}};function ot(t=T){let e=st(t),r=new Map,s=nt(t),f=new Set,m={run(g){let d=r.get(g);if(!d)r.set(g,d=S(g).ast);return(p)=>e(d,p)},self:(g)=>t.self(g)};return{check:q(t),style:(g)=>(d,p)=>{let l=g(d,{...p,lint(c,h){let i=h!==void 0?t.css(h):c[0]==="@"?t.css(c):void 0;return i&&[{...i,severity:"error"}]}}),o=(c,h,i)=>l.diagnostics.push({...c,severity:"error",loc:H(d,Math.max(h,0),i)}),n=!l.diagnostics.some((c)=>c.code.startsWith("LIPS-U"));for(let c of l.ir.exprs){let h=d.indexOf(c);n=V(t,c,R,(i,u,b)=>o(i,h+u,b))&&n}let a=n?t.css(l.ir.css):void 0;if(a&&o(a,0,0),!n||a)return{...l,ir:{...l.ir,css:"",binds:[],props:void 0}};return f.add(l.ir.css),l},runtime(g){let{components:d,createStylesheet:p}=g;return{...g,guard:m,host:s,components:d&&new Proxy(d,{get:(l,o)=>at(t,o)?it:l[o]}),createStylesheet:p&&((l,o)=>{if(f.has(o))return p(l,o);return t.report(k("LIPS-U042",`A stylesheet Lips did not compile cannot be checked — <${l}> ships unstyled`,"Send the stylesheet source; precompiled sheets are trusted output")),{clear(){}}})}}}}var at=(t,e)=>{let r=typeof e==="string"?t.component(e):void 0;return r&&t.report(r),!!r};export{q as checkTemplate,ot as untrusted,T as untrustedPolicy};
|
|
4
|
+
|
|
5
|
+
//# debugId=DD4429B74F5A6C4F64756E2164756E21
|