@sccharts-lab/embed 0.0.0-stage → 0.1.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.
@@ -0,0 +1,139 @@
1
+ // The options of an embedded chart: the query of /embed/ (`?example=learn/abro&view=sim&height=auto`) and the
2
+ // attributes of <sccharts-lab-chart>, which become that query. Pure and dependency-free.
3
+ //
4
+ // The chart itself comes as in the playground: `?example=<id>`, `#code=<lz-string>` (one file), `#project=` (several),
5
+ // `#run=` (a run to replay) and `&chart=` in the hash; or, with `source=parent`, from the page (postMessage).
6
+ export const VIEWS = ['diagram', 'sim', 'editor', 'full'];
7
+ export const DEFAULT_VIEW = 'sim';
8
+ /** What each view shows. */
9
+ export const VIEW_PARTS = {
10
+ diagram: { editor: false, sim: false },
11
+ sim: { editor: false, sim: true },
12
+ editor: { editor: true, sim: false },
13
+ full: { editor: true, sim: true },
14
+ };
15
+ export const MIN_HEIGHT = 120;
16
+ export const MAX_HEIGHT = 4000;
17
+ export const MAX_TICK = 1000;
18
+ export const DEFAULTS = { view: DEFAULT_VIEW, height: 'fill', tour: false, controls: true };
19
+ const IDENT = /^[A-Za-z_]\w{0,199}$/;
20
+ const EXAMPLE = /^[\w-]+(\/[\w.-]+)*$/;
21
+ const TRUE = new Set(['', '1', 'true', 'yes', 'on']);
22
+ const FALSE = new Set(['0', 'false', 'no', 'off', 'none']);
23
+ /** A flag: present and empty, or 1/true/yes/on; absent or anything else is `fallback`. */
24
+ export function parseFlag(value, fallback) {
25
+ if (value === null || value === undefined)
26
+ return fallback;
27
+ const v = value.trim().toLowerCase();
28
+ return TRUE.has(v) ? true : FALSE.has(v) ? false : fallback;
29
+ }
30
+ export function parseView(value) {
31
+ const v = value?.trim().toLowerCase();
32
+ return VIEWS.includes(v) ? v : DEFAULT_VIEW;
33
+ }
34
+ /** `auto`, `fill`, or a number of pixels (`480`, `480px`) between MIN_HEIGHT and MAX_HEIGHT; else `fallback`. */
35
+ export function parseHeight(value, fallback = 'fill') {
36
+ const v = value?.trim().toLowerCase();
37
+ if (!v)
38
+ return fallback;
39
+ if (v === 'auto' || v === 'fill')
40
+ return v;
41
+ const m = /^(\d{2,4})(px)?$/.exec(v);
42
+ if (!m)
43
+ return fallback;
44
+ return Math.max(MIN_HEIGHT, Math.min(MAX_HEIGHT, Number(m[1])));
45
+ }
46
+ /** A tick from 0 to MAX_TICK, or undefined. */
47
+ export function parseTick(value) {
48
+ const v = value?.trim();
49
+ if (!v || !/^\d{1,6}$/.test(v))
50
+ return undefined;
51
+ return Math.min(MAX_TICK, Number(v));
52
+ }
53
+ export function parseChartName(value) {
54
+ const v = value?.trim();
55
+ return v && IDENT.test(v) ? v : undefined;
56
+ }
57
+ /** A guide example's id as links write it (`learn/abro/abro`), or undefined. */
58
+ export function parseExample(value) {
59
+ const v = value?.trim().replace(/^\/+/, '').replace(/\.sctx$/, '');
60
+ return v && v.length <= 200 && EXAMPLE.test(v) && !v.split('/').includes('..') ? v : undefined;
61
+ }
62
+ /** The options in an embed address's query (`location.search`); anything unknown or malformed is left at its default. */
63
+ export function parseEmbedQuery(search) {
64
+ const q = typeof search === 'string' ? new URLSearchParams(search) : search;
65
+ const tick = parseTick(q.get('tick'));
66
+ const chart = parseChartName(q.get('chart'));
67
+ const example = parseExample(q.get('example'));
68
+ return {
69
+ view: parseView(q.get('view')),
70
+ height: parseHeight(q.get('height')),
71
+ tour: parseFlag(q.get('tour'), false),
72
+ controls: parseFlag(q.get('controls'), true),
73
+ ...(tick !== undefined ? { tick } : {}),
74
+ ...(chart ? { chart } : {}),
75
+ ...(q.get('source') === 'parent' ? { source: 'parent' } : {}),
76
+ ...(example ? { example } : {}),
77
+ };
78
+ }
79
+ /** The query for these options: only what differs from the defaults, in a fixed order. */
80
+ export function embedQuery(t) {
81
+ const parts = [];
82
+ const example = parseExample(t.example);
83
+ if (example)
84
+ parts.push(`example=${encodeURIComponent(example).replace(/%2F/g, '/')}`);
85
+ if (t.source === 'parent')
86
+ parts.push('source=parent');
87
+ if (t.view && t.view !== DEFAULT_VIEW)
88
+ parts.push(`view=${t.view}`);
89
+ if (t.height !== undefined && t.height !== 'fill')
90
+ parts.push(`height=${t.height}`);
91
+ if (t.tour)
92
+ parts.push('tour');
93
+ if (t.tick !== undefined && t.tick > 0)
94
+ parts.push(`tick=${Math.min(MAX_TICK, Math.floor(t.tick))}`);
95
+ if (t.controls === false)
96
+ parts.push('controls=0');
97
+ if (t.chart && IDENT.test(t.chart))
98
+ parts.push(`chart=${t.chart}`);
99
+ return parts.length ? `?${parts.join('&')}` : '';
100
+ }
101
+ /** The site an embed comes from (where /embed/ and /embed.js are). */
102
+ export const DEFAULT_BASE = 'https://sccharts.jmw.nz/';
103
+ /** The address of an embed: `<base>embed/?<options>#<hash>` (`hash`: a playground hash, `code=...`, without `#`). */
104
+ export function embedUrl(base, t, hash) {
105
+ const root = base.endsWith('/') ? base : `${base}/`;
106
+ const h = hash?.replace(/^#/, '');
107
+ return `${root}embed/${embedQuery(t)}${h ? `#${h}` : ''}`;
108
+ }
109
+ /** The options of a <sccharts-lab-chart> from its attributes (`get`: the attribute's value, null when absent). Its
110
+ * height is `auto` unless given: the element resizes its frame to the content. */
111
+ export function targetFromAttributes(get) {
112
+ const tick = parseTick(get('tick'));
113
+ const chart = parseChartName(get('chart'));
114
+ const example = parseExample(get('example'));
115
+ return {
116
+ view: parseView(get('view')),
117
+ height: parseHeight(get('height'), 'auto'),
118
+ tour: parseFlag(get('tour'), false),
119
+ controls: parseFlag(get('controls'), true),
120
+ ...(tick !== undefined ? { tick } : {}),
121
+ ...(chart ? { chart } : {}),
122
+ ...(example ? { example } : {}),
123
+ };
124
+ }
125
+ /** A first guess at an auto-sized embed's height, so the page moves little once it reports its own. */
126
+ export function estimateHeight(view, width = 640) {
127
+ const narrow = width < 640;
128
+ switch (view) {
129
+ case 'diagram':
130
+ return 340;
131
+ case 'sim':
132
+ return narrow ? 620 : 560;
133
+ case 'editor':
134
+ return narrow ? 640 : 380;
135
+ case 'full':
136
+ return narrow ? 960 : 720;
137
+ }
138
+ }
139
+ //# sourceMappingURL=options.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"options.js","sourceRoot":"","sources":["../src/options.ts"],"names":[],"mappings":"AAAA,8GAA8G;AAC9G,yFAAyF;AACzF,EAAE;AACF,uHAAuH;AACvH,8GAA8G;AAG9G,MAAM,CAAC,MAAM,KAAK,GAAyB,CAAC,SAAS,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAA;AAC/E,MAAM,CAAC,MAAM,YAAY,GAAc,KAAK,CAAA;AAE5C,4BAA4B;AAC5B,MAAM,CAAC,MAAM,UAAU,GAAyD;IAC5E,OAAO,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE;IACtC,GAAG,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE;IACjC,MAAM,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE;IACpC,IAAI,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE;CACpC,CAAA;AAKD,MAAM,CAAC,MAAM,UAAU,GAAG,GAAG,CAAA;AAC7B,MAAM,CAAC,MAAM,UAAU,GAAG,IAAI,CAAA;AAC9B,MAAM,CAAC,MAAM,QAAQ,GAAG,IAAI,CAAA;AAsB5B,MAAM,CAAC,MAAM,QAAQ,GAAiB,EAAE,IAAI,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAA;AAEzG,MAAM,KAAK,GAAG,sBAAsB,CAAA;AACpC,MAAM,OAAO,GAAG,sBAAsB,CAAA;AAEtC,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,CAAC,EAAE,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC,CAAA;AACpD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AC,CAAC,EAAE,CAAC;KAClC,CAAA;AACL,CAAC;AAED,uGAAuG;AACvG,MAAM,UAAU,cAAc,CAAC,IAAe,EAAE,KAAK,GAAG,GAAG;IACvD,MAAM,MAAM,GAAG,KAAK,GAAG,GAAG,CAAA;IAC1B,QAAQ,IAAI,EAAE,CAAC;QACX,KAAK,SAAS;YACV,OAAO,GAAG,CAAA;QACd,KAAK,KAAK;YACN,OAAO,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAA;QAC7B,KAAK,QAAQ;YACT,OAAO,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAA;QAC7B,KAAK,MAAM;YACP,OAAO,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAA;IACjC,CAAC;AACL,CAAC","sourcesContent":["// The options of an embedded chart: the query of /embed/ (`?example=learn/abro&view=sim&height=auto`) and the\n// attributes of <sccharts-lab-chart>, which become that query. Pure and dependency-free.\n//\n// The chart itself comes as in the playground: `?example=<id>`, `#code=<lz-string>` (one file), `#project=` (several),\n// `#run=` (a run to replay) and `&chart=` in the hash; or, with `source=parent`, from the page (postMessage).\n\nexport type EmbedView = 'diagram' | 'sim' | 'editor' | 'full'\nexport const VIEWS: readonly EmbedView[] = ['diagram', 'sim', 'editor', 'full']\nexport const DEFAULT_VIEW: EmbedView = 'sim'\n\n/** What each view shows. */\nexport const VIEW_PARTS: Record<EmbedView, { editor: boolean; sim: boolean }> = {\n diagram: { editor: false, sim: false },\n sim: { editor: false, sim: true },\n editor: { editor: true, sim: false },\n full: { editor: true, sim: true },\n}\n\n/** `fill`: the embed fills its frame (the iframe's height decides); `auto`: it takes the height its content needs and\n * reports it (`resize`); a number: it is that many pixels tall. */\nexport type EmbedHeight = 'fill' | 'auto' | number\nexport const MIN_HEIGHT = 120\nexport const MAX_HEIGHT = 4000\nexport const MAX_TICK = 1000\n\nexport interface EmbedOptions {\n view: EmbedView\n height: EmbedHeight\n /** Start at this tick: of the shared run, of the guided tour, or stepped with the inputs as they are. */\n tick?: number\n /** Start in the example's guided tour (its scripted inputs, with notes). */\n tour: boolean\n /** The simulation's controls and the diagram's tools are shown (off: the page drives it with postMessage). */\n controls: boolean\n /** The chart of the file to show and simulate, when not its first. */\n chart?: string\n /** The chart comes from the page (postMessage `setSource` or `setFiles`), not from the address. */\n source?: 'parent'\n}\n\nexport interface EmbedTarget extends Partial<EmbedOptions> {\n /** A guide example (`learn/abro/abro`, `showcase/abro`). */\n example?: string\n}\n\nexport const DEFAULTS: EmbedOptions = { view: DEFAULT_VIEW, height: 'fill', tour: false, controls: true }\n\nconst IDENT = /^[A-Za-z_]\\w{0,199}$/\nconst EXAMPLE = /^[\\w-]+(\\/[\\w.-]+)*$/\n\nconst TRUE = new Set(['', '1', 'true', 'yes', 'on'])\nconst FALSE = new Set(['0', 'false', 'no', 'off', 'none'])\n\n/** A flag: present and empty, or 1/true/yes/on; absent or anything else is `fallback`. */\nexport function parseFlag(value: string | null | undefined, fallback: boolean): boolean {\n if (value === null || value === undefined) return fallback\n const v = value.trim().toLowerCase()\n return TRUE.has(v) ? true : FALSE.has(v) ? false : fallback\n}\n\nexport function parseView(value: string | null | undefined): EmbedView {\n const v = value?.trim().toLowerCase()\n return VIEWS.includes(v as EmbedView) ? (v as EmbedView) : DEFAULT_VIEW\n}\n\n/** `auto`, `fill`, or a number of pixels (`480`, `480px`) between MIN_HEIGHT and MAX_HEIGHT; else `fallback`. */\nexport function parseHeight(value: string | null | undefined, fallback: EmbedHeight = 'fill'): EmbedHeight {\n const v = value?.trim().toLowerCase()\n if (!v) return fallback\n if (v === 'auto' || v === 'fill') return v\n const m = /^(\\d{2,4})(px)?$/.exec(v)\n if (!m) return fallback\n return Math.max(MIN_HEIGHT, Math.min(MAX_HEIGHT, Number(m[1])))\n}\n\n/** A tick from 0 to MAX_TICK, or undefined. */\nexport function parseTick(value: string | null | undefined): number | undefined {\n const v = value?.trim()\n if (!v || !/^\\d{1,6}$/.test(v)) return undefined\n return Math.min(MAX_TICK, Number(v))\n}\n\nexport function parseChartName(value: string | null | undefined): string | undefined {\n const v = value?.trim()\n return v && IDENT.test(v) ? v : undefined\n}\n\n/** A guide example's id as links write it (`learn/abro/abro`), or undefined. */\nexport function parseExample(value: string | null | undefined): string | undefined {\n const v = value?.trim().replace(/^\\/+/, '').replace(/\\.sctx$/, '')\n return v && v.length <= 200 && EXAMPLE.test(v) && !v.split('/').includes('..') ? v : undefined\n}\n\n/** The options in an embed address's query (`location.search`); anything unknown or malformed is left at its default. */\nexport function parseEmbedQuery(search: string | URLSearchParams): EmbedOptions & { example?: string } {\n const q = typeof search === 'string' ? new URLSearchParams(search) : search\n const tick = parseTick(q.get('tick'))\n const chart = parseChartName(q.get('chart'))\n const example = parseExample(q.get('example'))\n return {\n view: parseView(q.get('view')),\n height: parseHeight(q.get('height')),\n tour: parseFlag(q.get('tour'), false),\n controls: parseFlag(q.get('controls'), true),\n ...(tick !== undefined ? { tick } : {}),\n ...(chart ? { chart } : {}),\n ...(q.get('source') === 'parent' ? { source: 'parent' as const } : {}),\n ...(example ? { example } : {}),\n }\n}\n\n/** The query for these options: only what differs from the defaults, in a fixed order. */\nexport function embedQuery(t: EmbedTarget): string {\n const parts: string[] = []\n const example = parseExample(t.example)\n if (example) parts.push(`example=${encodeURIComponent(example).replace(/%2F/g, '/')}`)\n if (t.source === 'parent') parts.push('source=parent')\n if (t.view && t.view !== DEFAULT_VIEW) parts.push(`view=${t.view}`)\n if (t.height !== undefined && t.height !== 'fill') parts.push(`height=${t.height}`)\n if (t.tour) parts.push('tour')\n if (t.tick !== undefined && t.tick > 0) parts.push(`tick=${Math.min(MAX_TICK, Math.floor(t.tick))}`)\n if (t.controls === false) parts.push('controls=0')\n if (t.chart && IDENT.test(t.chart)) parts.push(`chart=${t.chart}`)\n return parts.length ? `?${parts.join('&')}` : ''\n}\n\n/** The site an embed comes from (where /embed/ and /embed.js are). */\nexport const DEFAULT_BASE = 'https://sccharts.jmw.nz/'\n\n/** The address of an embed: `<base>embed/?<options>#<hash>` (`hash`: a playground hash, `code=...`, without `#`). */\nexport function embedUrl(base: string, t: EmbedTarget, hash?: string): string {\n const root = base.endsWith('/') ? base : `${base}/`\n const h = hash?.replace(/^#/, '')\n return `${root}embed/${embedQuery(t)}${h ? `#${h}` : ''}`\n}\n\n/** The options of a <sccharts-lab-chart> from its attributes (`get`: the attribute's value, null when absent). Its\n * height is `auto` unless given: the element resizes its frame to the content. */\nexport function targetFromAttributes(get: (name: string) => string | null): EmbedTarget {\n const tick = parseTick(get('tick'))\n const chart = parseChartName(get('chart'))\n const example = parseExample(get('example'))\n return {\n view: parseView(get('view')),\n height: parseHeight(get('height'), 'auto'),\n tour: parseFlag(get('tour'), false),\n controls: parseFlag(get('controls'), true),\n ...(tick !== undefined ? { tick } : {}),\n ...(chart ? { chart } : {}),\n ...(example ? { example } : {}),\n }\n}\n\n/** A first guess at an auto-sized embed's height, so the page moves little once it reports its own. */\nexport function estimateHeight(view: EmbedView, width = 640): number {\n const narrow = width < 640\n switch (view) {\n case 'diagram':\n return 340\n case 'sim':\n return narrow ? 620 : 560\n case 'editor':\n return narrow ? 640 : 380\n case 'full':\n return narrow ? 960 : 720\n }\n}\n"]}
@@ -0,0 +1,183 @@
1
+ export declare const PROTOCOL = "sccharts-lab";
2
+ export declare const VERSION = 1;
3
+ /** A value of the chart's data pool (KIELER's names: a valued signal `V` is `V`, its presence, and `V_val`). */
4
+ export type Value = boolean | number | string | null | Value[];
5
+ export type Inputs = Record<string, Value>;
6
+ export type EmbedCommand =
7
+ /** Replaces the text of the file shown (one file: the chart). The simulation starts again on it. */
8
+ {
9
+ command: 'setSource';
10
+ source: string;
11
+ }
12
+ /** Opens a project of several files (`active`: the one shown and simulated, else the first). */
13
+ | {
14
+ command: 'setFiles';
15
+ files: Record<string, string>;
16
+ active?: string;
17
+ name?: string;
18
+ }
19
+ /** Shows and simulates another chart of the file (a file with several `scchart`s). */
20
+ | {
21
+ command: 'selectChart';
22
+ chart: string;
23
+ }
24
+ /** Sets these inputs (they keep their values afterwards, as in KIELER) and runs one tick. */
25
+ | {
26
+ command: 'step';
27
+ inputs?: Inputs;
28
+ }
29
+ /** Sets these inputs for the next tick without running it. */
30
+ | {
31
+ command: 'setInputs';
32
+ inputs: Inputs;
33
+ }
34
+ /** Back to tick 0 (the ticks computed are dropped). */
35
+ | {
36
+ command: 'reset';
37
+ }
38
+ /** Shows tick `tick` of the ticks computed (0: before the first); the later ones stay and Step replays them. */
39
+ | {
40
+ command: 'rewind';
41
+ tick: number;
42
+ }
43
+ /** Answers with the chart's compile and the tick shown (a `reply` with `result: { compiled, tick }`). */
44
+ | {
45
+ command: 'getState';
46
+ };
47
+ export type CommandName = EmbedCommand['command'];
48
+ export declare const COMMANDS: readonly CommandName[];
49
+ export type CommandId = string | number;
50
+ export type CommandMessage = EmbedCommand & {
51
+ type: typeof PROTOCOL;
52
+ version: typeof VERSION;
53
+ id?: CommandId;
54
+ };
55
+ export interface DiagnosticInfo {
56
+ severity: 'error' | 'warning' | 'info';
57
+ message: string;
58
+ code?: string;
59
+ hint?: string;
60
+ /** 1-based, where the source has a place for it. */
61
+ line?: number;
62
+ column?: number;
63
+ endLine?: number;
64
+ endColumn?: number;
65
+ }
66
+ export interface VariableInfo {
67
+ name: string;
68
+ /** `pure` (a signal without a value), `bool`, `int`, `float`, `string`, ... */
69
+ type: string;
70
+ signal: boolean;
71
+ valued: boolean;
72
+ /** Array dimensions (empty for scalars). */
73
+ dims: number[];
74
+ }
75
+ export interface CompiledInfo {
76
+ /** KIELER would accept the chart (no errors). */
77
+ ok: boolean;
78
+ /** The file compiled. */
79
+ file: string;
80
+ /** The chart shown and simulated. */
81
+ chart?: string;
82
+ /** Every chart of the file. */
83
+ charts: string[];
84
+ diagnostics: DiagnosticInfo[];
85
+ inputs: VariableInfo[];
86
+ outputs: VariableInfo[];
87
+ }
88
+ export interface TickInfo {
89
+ /** The tick shown: 0 before the first. */
90
+ tick: number;
91
+ /** Ticks computed (after `rewind`, more than `tick`). */
92
+ ticks: number;
93
+ /** The guided tour (or a shared run) is in control. */
94
+ tour: boolean;
95
+ /** KIELER's data pool after the tick: inputs, outputs and the chart's variables. Empty at tick 0. */
96
+ values: Record<string, Value>;
97
+ /** Signal presence in the tick. */
98
+ present: Record<string, boolean>;
99
+ /** Ids of the states active at the end of the tick (`ABRO.ABO.WaitAB.WaitA`, with their ancestors). */
100
+ active: string[];
101
+ /** States entered, transitions taken (`ABRO.ABO.WaitAB.WaitB->1`, in firing order). */
102
+ entered: string[];
103
+ taken: string[];
104
+ /** What the chart printed in the tick (`print(...)`). */
105
+ printed: string[];
106
+ terminated: boolean;
107
+ /** A run-time error stopped the simulation in this tick. */
108
+ error?: string;
109
+ }
110
+ export interface ReadyInfo {
111
+ view: string;
112
+ compiled?: CompiledInfo;
113
+ tick: TickInfo;
114
+ }
115
+ export type EmbedEvent = ({
116
+ event: 'ready';
117
+ } & ReadyInfo) | ({
118
+ event: 'compiled';
119
+ } & CompiledInfo) | ({
120
+ event: 'tick';
121
+ } & TickInfo) | {
122
+ event: 'resize';
123
+ height: number;
124
+ } | {
125
+ event: 'error';
126
+ message: string;
127
+ command?: string;
128
+ } | {
129
+ event: 'reply';
130
+ id: CommandId;
131
+ ok: boolean;
132
+ error?: string;
133
+ result?: unknown;
134
+ };
135
+ export type EventName = EmbedEvent['event'];
136
+ export type EventMessage = EmbedEvent & {
137
+ type: typeof PROTOCOL;
138
+ version: typeof VERSION;
139
+ };
140
+ /** Wraps an event (or a command) in the envelope. */
141
+ export declare function envelope<T extends object>(body: T): T & {
142
+ type: typeof PROTOCOL;
143
+ version: typeof VERSION;
144
+ };
145
+ /** Limits that keep a message from a page cheap to check and to run. */
146
+ export declare const LIMITS: {
147
+ source: number;
148
+ files: number;
149
+ path: number;
150
+ inputs: number;
151
+ array: number;
152
+ depth: number;
153
+ id: number;
154
+ };
155
+ export type Parsed = {
156
+ kind: 'command';
157
+ message: CommandMessage;
158
+ }
159
+ /** In the envelope, but not a command this embed can run: answer with an error. */
160
+ | {
161
+ kind: 'invalid';
162
+ error: string;
163
+ id?: CommandId;
164
+ command?: string;
165
+ }
166
+ /** Not for us (another protocol, an event, not an object): ignore it. */
167
+ | {
168
+ kind: 'ignore';
169
+ };
170
+ /** A value a chart can take (finite numbers, nested arrays up to LIMITS.depth). */
171
+ export declare function isValue(v: unknown, depth?: number): v is Value;
172
+ /** Inputs by name: an object of identifiers to values; the reason it is not, else undefined. */
173
+ export declare function checkInputs(v: unknown): string | undefined;
174
+ /** A project file's path: relative, `.sctx`, no `..`. */
175
+ export declare function checkPath(p: unknown): string | undefined;
176
+ /**
177
+ * Reads a message sent to the embed. Only objects in the envelope with a `command` are commands; everything else is
178
+ * ignored. A command in the envelope that cannot run (another version, an unknown command, a wrong argument) is
179
+ * `invalid`, with the reason. The command returned is a fresh copy holding only the fields it uses.
180
+ */
181
+ export declare function parseCommand(data: unknown): Parsed;
182
+ /** Reads a message sent by the embed: an event in the envelope, else undefined. */
183
+ export declare function parseEvent(data: unknown): EventMessage | undefined;
@@ -0,0 +1,149 @@
1
+ // The postMessage protocol between a page and an embedded SCCharts Lab chart (/embed/ in an iframe). Every message,
2
+ // both ways, is a plain object in one envelope: `{ type: 'sccharts-lab', version: 1, ... }`. The page sends commands
3
+ // (`command`), the embed answers with events (`event`). A command may carry an `id`; the embed then answers it with a
4
+ // `reply` event of the same id. Anything that is not such an object is ignored; nothing is ever evaluated.
5
+ //
6
+ // Pure and dependency-free: the custom element (element.ts) and the site's embed page (src/components/embed) both
7
+ // use it.
8
+ export const PROTOCOL = 'sccharts-lab';
9
+ export const VERSION = 1;
10
+ export const COMMANDS = ['setSource', 'setFiles', 'selectChart', 'step', 'setInputs', 'reset', 'rewind', 'getState'];
11
+ /** Wraps an event (or a command) in the envelope. */
12
+ export function envelope(body) {
13
+ return { type: PROTOCOL, version: VERSION, ...body };
14
+ }
15
+ // ----- Validation ---------------------------------------------------------------------------------------------------
16
+ /** Limits that keep a message from a page cheap to check and to run. */
17
+ export const LIMITS = { source: 1_000_000, files: 200, path: 200, inputs: 500, array: 10_000, depth: 4, id: 200 };
18
+ const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
19
+ const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
20
+ const FORBIDDEN = new Set(['__proto__', 'constructor', 'prototype']);
21
+ const NAME = /^[A-Za-z_]\w{0,199}$/;
22
+ /** A value a chart can take (finite numbers, nested arrays up to LIMITS.depth). */
23
+ export function isValue(v, depth = 0) {
24
+ if (v === null || typeof v === 'boolean' || typeof v === 'string')
25
+ return true;
26
+ if (typeof v === 'number')
27
+ return Number.isFinite(v);
28
+ if (Array.isArray(v))
29
+ return depth < LIMITS.depth && v.length <= LIMITS.array && v.every(x => isValue(x, depth + 1));
30
+ return false;
31
+ }
32
+ /** Inputs by name: an object of identifiers to values; the reason it is not, else undefined. */
33
+ export function checkInputs(v) {
34
+ if (!isObject(v))
35
+ return '`inputs` must be an object of input names to values.';
36
+ const keys = Object.keys(v);
37
+ if (keys.length > LIMITS.inputs)
38
+ return `At most ${LIMITS.inputs} inputs at once.`;
39
+ for (const k of keys) {
40
+ if (!NAME.test(k) || FORBIDDEN.has(k))
41
+ return `\`${k.slice(0, 40)}\` is not an input name.`;
42
+ if (!isValue(v[k]))
43
+ return `The value of \`${k}\` is not a boolean, a number, a string, null or an array of them.`;
44
+ }
45
+ return undefined;
46
+ }
47
+ /** A project file's path: relative, `.sctx`, no `..`. */
48
+ export function checkPath(p) {
49
+ if (typeof p !== 'string' || !p || p.length > LIMITS.path)
50
+ return 'A file name must be a short string.';
51
+ if (!/^[\w ./+-]+\.sctx$/i.test(p) || p.startsWith('/') || p.split('/').some(s => s === '..' || s === '.' || s === ''))
52
+ return `\`${p.slice(0, 60)}\` is not a file name like \`main.sctx\` or \`lib/beep.sctx\`.`;
53
+ return undefined;
54
+ }
55
+ const copyInputs = (v) => Object.fromEntries(Object.keys(v).map(k => [k, v[k]]));
56
+ /**
57
+ * Reads a message sent to the embed. Only objects in the envelope with a `command` are commands; everything else is
58
+ * ignored. A command in the envelope that cannot run (another version, an unknown command, a wrong argument) is
59
+ * `invalid`, with the reason. The command returned is a fresh copy holding only the fields it uses.
60
+ */
61
+ export function parseCommand(data) {
62
+ if (!isObject(data) || data.type !== PROTOCOL || typeof data.command !== 'string')
63
+ return { kind: 'ignore' };
64
+ const rawId = data.id;
65
+ const id = (typeof rawId === 'string' && rawId.length <= LIMITS.id) || (typeof rawId === 'number' && Number.isFinite(rawId)) ? rawId : undefined;
66
+ const command = data.command.slice(0, 40);
67
+ const bad = (error) => ({ kind: 'invalid', error, id, command });
68
+ if (data.version !== VERSION)
69
+ return bad(`This embed speaks version ${VERSION} of the protocol, not ${String(data.version).slice(0, 20)}.`);
70
+ const base = { type: PROTOCOL, version: VERSION, ...(id !== undefined ? { id } : {}) };
71
+ switch (data.command) {
72
+ case 'setSource': {
73
+ if (typeof data.source !== 'string')
74
+ return bad('`source` must be a string.');
75
+ if (data.source.length > LIMITS.source)
76
+ return bad('The source is too long.');
77
+ return { kind: 'command', message: { ...base, command: 'setSource', source: data.source } };
78
+ }
79
+ case 'setFiles': {
80
+ if (!isObject(data.files))
81
+ return bad('`files` must be an object of file names to texts.');
82
+ const paths = Object.keys(data.files);
83
+ if (!paths.length)
84
+ return bad('`files` has no file.');
85
+ if (paths.length > LIMITS.files)
86
+ return bad(`At most ${LIMITS.files} files.`);
87
+ let size = 0;
88
+ const files = {};
89
+ for (const p of paths) {
90
+ const why = checkPath(p);
91
+ if (why)
92
+ return bad(why);
93
+ const text = data.files[p];
94
+ if (typeof text !== 'string')
95
+ return bad(`The text of \`${p}\` must be a string.`);
96
+ size += text.length;
97
+ files[p] = text;
98
+ }
99
+ if (size > LIMITS.source)
100
+ return bad('The files are too long.');
101
+ if (own(data, 'active') && data.active !== undefined && (typeof data.active !== 'string' || !own(files, data.active)))
102
+ return bad('`active` must name one of the files.');
103
+ if (own(data, 'name') && data.name !== undefined && (typeof data.name !== 'string' || data.name.length > LIMITS.path))
104
+ return bad('`name` must be a short string.');
105
+ return {
106
+ kind: 'command',
107
+ message: { ...base, command: 'setFiles', files, ...(typeof data.active === 'string' ? { active: data.active } : {}), ...(typeof data.name === 'string' && data.name.trim() ? { name: data.name.trim() } : {}) },
108
+ };
109
+ }
110
+ case 'selectChart': {
111
+ if (typeof data.chart !== 'string' || !NAME.test(data.chart))
112
+ return bad('`chart` must be the name of a chart.');
113
+ return { kind: 'command', message: { ...base, command: 'selectChart', chart: data.chart } };
114
+ }
115
+ case 'step': {
116
+ if (data.inputs === undefined)
117
+ return { kind: 'command', message: { ...base, command: 'step' } };
118
+ const why = checkInputs(data.inputs);
119
+ if (why)
120
+ return bad(why);
121
+ return { kind: 'command', message: { ...base, command: 'step', inputs: copyInputs(data.inputs) } };
122
+ }
123
+ case 'setInputs': {
124
+ const why = checkInputs(data.inputs);
125
+ if (why)
126
+ return bad(why);
127
+ return { kind: 'command', message: { ...base, command: 'setInputs', inputs: copyInputs(data.inputs) } };
128
+ }
129
+ case 'reset':
130
+ return { kind: 'command', message: { ...base, command: 'reset' } };
131
+ case 'rewind': {
132
+ const t = data.tick;
133
+ if (typeof t !== 'number' || !Number.isInteger(t) || t < 0)
134
+ return bad('`tick` must be a whole number, 0 or more.');
135
+ return { kind: 'command', message: { ...base, command: 'rewind', tick: t } };
136
+ }
137
+ case 'getState':
138
+ return { kind: 'command', message: { ...base, command: 'getState' } };
139
+ default:
140
+ return bad(`There is no command \`${command}\`. The commands are ${COMMANDS.join(', ')}.`);
141
+ }
142
+ }
143
+ /** Reads a message sent by the embed: an event in the envelope, else undefined. */
144
+ export function parseEvent(data) {
145
+ if (!isObject(data) || data.type !== PROTOCOL || data.version !== VERSION || typeof data.event !== 'string')
146
+ return undefined;
147
+ return data;
148
+ }
149
+ //# sourceMappingURL=protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.js","sourceRo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I,EAAE,OAAO,EAAE,UAAU,EAAE,EAAE,CAAA;QACzE;YACI,OAAO,GAAG,CAAC,yBAAyB,OAAO,wBAAwB,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;IAClG,CAAC;AACL,CAAC;AAED,mFAAmF;AACnF,MAAM,UAAU,UAAU,CAAC,IAAa;IACpC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,OAAO,KAAK,OAAO,IAAI,OAAO,IAAI,CAAC,KAAK,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAA;IAC7H,OAAO,IAA+B,CAAA;AAC1C,CAAC","sourcesContent":["// The postMessage protocol between a page and an embedded SCCharts Lab chart (/embed/ in an iframe). Every message,\n// both ways, is a plain object in one envelope: `{ type: 'sccharts-lab', version: 1, ... }`. The page sends commands\n// (`command`), the embed answers with events (`event`). A command may carry an `id`; the embed then answers it with a\n// `reply` event of the same id. Anything that is not such an object is ignored; nothing is ever evaluated.\n//\n// Pure and dependency-free: the custom element (element.ts) and the site's embed page (src/components/embed) both\n// use it.\n\nexport const PROTOCOL = 'sccharts-lab'\nexport const VERSION = 1\n\n/** A value of the chart's data pool (KIELER's names: a valued signal `V` is `V`, its presence, and `V_val`). */\nexport type Value = boolean | number | string | null | Value[]\nexport type Inputs = Record<string, Value>\n\n// ----- Commands (page to embed) -----------------------------------------------------------------------------------\n\nexport type EmbedCommand =\n /** Replaces the text of the file shown (one file: the chart). The simulation starts again on it. */\n | { command: 'setSource'; source: string }\n /** Opens a project of several files (`active`: the one shown and simulated, else the first). */\n | { command: 'setFiles'; files: Record<string, string>; active?: string; name?: string }\n /** Shows and simulates another chart of the file (a file with several `scchart`s). */\n | { command: 'selectChart'; chart: string }\n /** Sets these inputs (they keep their values afterwards, as in KIELER) and runs one tick. */\n | { command: 'step'; inputs?: Inputs }\n /** Sets these inputs for the next tick without running it. */\n | { command: 'setInputs'; inputs: Inputs }\n /** Back to tick 0 (the ticks computed are dropped). */\n | { command: 'reset' }\n /** Shows tick `tick` of the ticks computed (0: before the first); the later ones stay and Step replays them. */\n | { command: 'rewind'; tick: number }\n /** Answers with the chart's compile and the tick shown (a `reply` with `result: { compiled, tick }`). */\n | { command: 'getState' }\n\nexport type CommandName = EmbedCommand['command']\nexport const COMMANDS: readonly CommandName[] = ['setSource', 'setFiles', 'selectChart', 'step', 'setInputs', 'reset', 'rewind', 'getState']\n\nexport type CommandId = string | number\nexport type CommandMessage = EmbedCommand & { type: typeof PROTOCOL; version: typeof VERSION; id?: CommandId }\n\n// ----- Events (embed to page) -------------------------------------------------------------------------------------\n\nexport interface DiagnosticInfo {\n severity: 'error' | 'warning' | 'info'\n message: string\n code?: string\n hint?: string\n /** 1-based, where the source has a place for it. */\n line?: number\n column?: number\n endLine?: number\n endColumn?: number\n}\n\nexport interface VariableInfo {\n name: string\n /** `pure` (a signal without a value), `bool`, `int`, `float`, `string`, ... */\n type: string\n signal: boolean\n valued: boolean\n /** Array dimensions (empty for scalars). */\n dims: number[]\n}\n\nexport interface CompiledInfo {\n /** KIELER would accept the chart (no errors). */\n ok: boolean\n /** The file compiled. */\n file: string\n /** The chart shown and simulated. */\n chart?: string\n /** Every chart of the file. */\n charts: string[]\n diagnostics: DiagnosticInfo[]\n inputs: VariableInfo[]\n outputs: VariableInfo[]\n}\n\nexport interface TickInfo {\n /** The tick shown: 0 before the first. */\n tick: number\n /** Ticks computed (after `rewind`, more than `tick`). */\n ticks: number\n /** The guided tour (or a shared run) is in control. */\n tour: boolean\n /** KIELER's data pool after the tick: inputs, outputs and the chart's variables. Empty at tick 0. */\n values: Record<string, Value>\n /** Signal presence in the tick. */\n present: Record<string, boolean>\n /** Ids of the states active at the end of the tick (`ABRO.ABO.WaitAB.WaitA`, with their ancestors). */\n active: string[]\n /** States entered, transitions taken (`ABRO.ABO.WaitAB.WaitB->1`, in firing order). */\n entered: string[]\n taken: string[]\n /** What the chart printed in the tick (`print(...)`). */\n printed: string[]\n terminated: boolean\n /** A run-time error stopped the simulation in this tick. */\n error?: string\n}\n\nexport interface ReadyInfo {\n view: string\n compiled?: CompiledInfo\n tick: TickInfo\n}\n\nexport type EmbedEvent =\n | ({ event: 'ready' } & ReadyInfo)\n | ({ event: 'compiled' } & CompiledInfo)\n | ({ event: 'tick' } & TickInfo)\n | { event: 'resize'; height: number }\n | { event: 'error'; message: string; command?: string }\n | { event: 'reply'; id: CommandId; ok: boolean; error?: string; result?: unknown }\n\nexport type EventName = EmbedEvent['event']\nexport type EventMessage = EmbedEvent & { type: typeof PROTOCOL; version: typeof VERSION }\n\n/** Wraps an event (or a command) in the envelope. */\nexport function envelope<T extends object>(body: T): T & { type: typeof PROTOCOL; version: typeof VERSION } {\n return { type: PROTOCOL, version: VERSION, ...body }\n}\n\n// ----- Validation ---------------------------------------------------------------------------------------------------\n\n/** Limits that keep a message from a page cheap to check and to run. */\nexport const LIMITS = { source: 1_000_000, files: 200, path: 200, inputs: 500, array: 10_000, depth: 4, id: 200 }\n\nexport type Parsed =\n | { kind: 'command'; message: CommandMessage }\n /** In the envelope, but not a command this embed can run: answer with an error. */\n | { kind: 'invalid'; error: string; id?: CommandId; command?: string }\n /** Not for us (another protocol, an event, not an object): ignore it. */\n | { kind: 'ignore' }\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)\nconst own = (o: Record<string, unknown>, k: string) => Object.prototype.hasOwnProperty.call(o, k)\nconst FORBIDDEN = new Set(['__proto__', 'constructor', 'prototype'])\nconst NAME = /^[A-Za-z_]\\w{0,199}$/\n\n/** A value a chart can take (finite numbers, nested arrays up to LIMITS.depth). */\nexport function isValue(v: unknown, depth = 0): v is Value {\n if (v === null || typeof v === 'boolean' || typeof v === 'string') return true\n if (typeof v === 'number') return Number.isFinite(v)\n if (Array.isArray(v)) return depth < LIMITS.depth && v.length <= LIMITS.array && v.every(x => isValue(x, depth + 1))\n return false\n}\n\n/** Inputs by name: an object of identifiers to values; the reason it is not, else undefined. */\nexport function checkInputs(v: unknown): string | undefined {\n if (!isObject(v)) return '`inputs` must be an object of input names to values.'\n const keys = Object.keys(v)\n if (keys.length > LIMITS.inputs) return `At most ${LIMITS.inputs} inputs at once.`\n for (const k of keys) {\n if (!NAME.test(k) || FORBIDDEN.has(k)) return `\\`${k.slice(0, 40)}\\` is not an input name.`\n if (!isValue(v[k])) return `The value of \\`${k}\\` is not a boolean, a number, a string, null or an array of them.`\n }\n return undefined\n}\n\n/** A project file's path: relative, `.sctx`, no `..`. */\nexport function checkPath(p: unknown): string | undefined {\n if (typeof p !== 'string' || !p || p.length > LIMITS.path) return 'A file name must be a short string.'\n if (!/^[\\w ./+-]+\\.sctx$/i.test(p) || p.startsWith('/') || p.split('/').some(s => s === '..' || s === '.' || s === '')) return `\\`${p.slice(0, 60)}\\` is not a file name like \\`main.sctx\\` or \\`lib/beep.sctx\\`.`\n return undefined\n}\n\nconst copyInputs = (v: Record<string, unknown>): Inputs => Object.fromEntries(Object.keys(v).map(k => [k, v[k] as Value]))\n\n/**\n * Reads a message sent to the embed. Only objects in the envelope with a `command` are commands; everything else is\n * ignored. A command in the envelope that cannot run (another version, an unknown command, a wrong argument) is\n * `invalid`, with the reason. The command returned is a fresh copy holding only the fields it uses.\n */\nexport function parseCommand(data: unknown): Parsed {\n if (!isObject(data) || data.type !== PROTOCOL || typeof data.command !== 'string') return { kind: 'ignore' }\n const rawId = data.id\n const id = (typeof rawId === 'string' && rawId.length <= LIMITS.id) || (typeof rawId === 'number' && Number.isFinite(rawId)) ? rawId : undefined\n const command = data.command.slice(0, 40)\n const bad = (error: string): Parsed => ({ kind: 'invalid', error, id, command })\n if (data.version !== VERSION) return bad(`This embed speaks version ${VERSION} of the protocol, not ${String(data.version).slice(0, 20)}.`)\n const base = { type: PROTOCOL, version: VERSION, ...(id !== undefined ? { id } : {}) } as const\n switch (data.command) {\n case 'setSource': {\n if (typeof data.source !== 'string') return bad('`source` must be a string.')\n if (data.source.length > LIMITS.source) return bad('The source is too long.')\n return { kind: 'command', message: { ...base, command: 'setSource', source: data.source } }\n }\n case 'setFiles': {\n if (!isObject(data.files)) return bad('`files` must be an object of file names to texts.')\n const paths = Object.keys(data.files)\n if (!paths.length) return bad('`files` has no file.')\n if (paths.length > LIMITS.files) return bad(`At most ${LIMITS.files} files.`)\n let size = 0\n const files: Record<string, string> = {}\n for (const p of paths) {\n const why = checkPath(p)\n if (why) return bad(why)\n const text = data.files[p]\n if (typeof text !== 'string') return bad(`The text of \\`${p}\\` must be a string.`)\n size += text.length\n files[p] = text\n }\n if (size > LIMITS.source) return bad('The files are too long.')\n if (own(data, 'active') && data.active !== undefined && (typeof data.active !== 'string' || !own(files, data.active))) return bad('`active` must name one of the files.')\n if (own(data, 'name') && data.name !== undefined && (typeof data.name !== 'string' || data.name.length > LIMITS.path)) return bad('`name` must be a short string.')\n return {\n kind: 'command',\n message: { ...base, command: 'setFiles', files, ...(typeof data.active === 'string' ? { active: data.active } : {}), ...(typeof data.name === 'string' && data.name.trim() ? { name: data.name.trim() } : {}) },\n }\n }\n case 'selectChart': {\n if (typeof data.chart !== 'string' || !NAME.test(data.chart)) return bad('`chart` must be the name of a chart.')\n return { kind: 'command', message: { ...base, command: 'selectChart', chart: data.chart } }\n }\n case 'step': {\n if (data.inputs === undefined) return { kind: 'command', message: { ...base, command: 'step' } }\n const why = checkInputs(data.inputs)\n if (why) return bad(why)\n return { kind: 'command', message: { ...base, command: 'step', inputs: copyInputs(data.inputs as Record<string, unknown>) } }\n }\n case 'setInputs': {\n const why = checkInputs(data.inputs)\n if (why) return bad(why)\n return { kind: 'command', message: { ...base, command: 'setInputs', inputs: copyInputs(data.inputs as Record<string, unknown>) } }\n }\n case 'reset':\n return { kind: 'command', message: { ...base, command: 'reset' } }\n case 'rewind': {\n const t = data.tick\n if (typeof t !== 'number' || !Number.isInteger(t) || t < 0) return bad('`tick` must be a whole number, 0 or more.')\n return { kind: 'command', message: { ...base, command: 'rewind', tick: t } }\n }\n case 'getState':\n return { kind: 'command', message: { ...base, command: 'getState' } }\n default:\n return bad(`There is no command \\`${command}\\`. The commands are ${COMMANDS.join(', ')}.`)\n }\n}\n\n/** Reads a message sent by the embed: an event in the envelope, else undefined. */\nexport function parseEvent(data: unknown): EventMessage | undefined {\n if (!isObject(data) || data.type !== PROTOCOL || data.version !== VERSION || typeof data.event !== 'string') return undefined\n return data as unknown as EventMessage\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "@sccharts-lab/embed",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Live SCCharts charts on any page: the <sccharts-lab-chart> element, the embed's options and its postMessage protocol, as a module and as one script tag",
5
+ "keywords": [
6
+ "sccharts",
7
+ "kieler",
8
+ "embed",
9
+ "web-component",
10
+ "custom-element",
11
+ "iframe",
12
+ "postmessage",
13
+ "statecharts",
14
+ "simulation"
15
+ ],
16
+ "homepage": "https://sccharts.jmw.nz/reference/embed/",
17
+ "bugs": "https://github.com/Fallstop/sccharts-lab/issues",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/Fallstop/sccharts-lab.git",
21
+ "directory": "site/packages/embed"
22
+ },
23
+ "license": "EPL-2.0",
24
+ "type": "module",
25
+ "sideEffects": [
26
+ "./src/loader.ts",
27
+ "./dist/loader.js",
28
+ "./dist/embed.min.js"
29
+ ],
30
+ "engines": {
31
+ "node": ">=20"
32
+ },
33
+ "exports": {
34
+ ".": {
35
+ "types": "./dist/index.d.ts",
36
+ "default": "./dist/index.js"
37
+ },
38
+ "./protocol": {
39
+ "types": "./dist/protocol.d.ts",
40
+ "default": "./dist/protocol.js"
41
+ },
42
+ "./options": {
43
+ "types": "./dist/options.d.ts",
44
+ "default": "./dist/options.js"
45
+ },
46
+ "./loader": {
47
+ "types": "./dist/loader.d.ts",
48
+ "default": "./dist/loader.js"
49
+ },
50
+ "./embed.min.js": "./dist/embed.min.js",
51
+ "./package.json": "./package.json"
52
+ },
53
+ "jsdelivr": "./dist/embed.min.js",
54
+ "unpkg": "./dist/embed.min.js",
55
+ "files": [
56
+ "dist"
57
+ ],
58
+ "publishConfig": {
59
+ "access": "public"
60
+ },
61
+ "main": "./dist/index.js",
62
+ "types": "./dist/index.d.ts"
6
63
  }