effect-atom-svelte-devtools 0.2.1 → 0.2.2

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.
@@ -65,10 +65,13 @@
65
65
  readonly plumbing: boolean;
66
66
  readonly expanded: boolean;
67
67
  readonly height: number;
68
- readonly shortcut: string;
68
+ /** Only one changed in the settings: otherwise the app's, which may change. */
69
+ readonly shortcut: string | undefined;
69
70
  readonly corner: Corner;
70
71
  readonly opacity: number;
71
72
  readonly scale: number;
73
+ /** Set from 0.2.2, whose `shortcut` is only one chosen in the settings; 0.2.1 saved the default. */
74
+ readonly shortcutChosen: true;
72
75
  }
73
76
  const storageKey = "effect-atom-svelte-devtools";
74
77
  const load = (): Partial<Saved> => {
@@ -120,7 +123,13 @@
120
123
  showPlumbing = saved.plumbing ?? false;
121
124
  expanded = saved.expanded ?? false;
122
125
  height = saved.height ?? 320;
123
- shortcut = saved.shortcut ?? appShortcut;
126
+ // Settings saved by 0.2.1, without `shortcutChosen`, hold the default even when nobody chose it,
127
+ // which would hide a shortcut the app sets: there the default counts as unset.
128
+ shortcut =
129
+ saved.shortcut === undefined ||
130
+ (saved.shortcutChosen !== true && saved.shortcut === defaultShortcut)
131
+ ? appShortcut
132
+ : saved.shortcut;
124
133
  corner = saved.corner ?? "bottom-right";
125
134
  opacity = saved.opacity ?? 1;
126
135
  scale = saved.scale ?? 1;
@@ -179,7 +188,8 @@
179
188
  open,
180
189
  plumbing: showPlumbing,
181
190
  scale,
182
- shortcut,
191
+ shortcut: shortcut === appShortcut ? undefined : shortcut,
192
+ shortcutChosen: true,
183
193
  tab,
184
194
  };
185
195
  try {
@@ -82,6 +82,9 @@
82
82
  };
83
83
 
84
84
  $effect(() => {
85
+ // Again after each new layout: a node whose kind or side changes has its classes written over,
86
+ // and a node drawn later has none.
87
+ void layout;
85
88
  for (const element of host?.querySelectorAll("[data-node].selected") ?? []) {
86
89
  element.classList.remove("selected");
87
90
  }
@@ -100,6 +100,9 @@ const depthsOf = (atoms, parents) => {
100
100
  seen.add(id);
101
101
  const from = (parents.get(id) ?? []).filter((parent) => !seen.has(parent));
102
102
  const value = from.length === 0 ? 0 : 1 + Math.max(...from.map((p) => depth(p, seen)));
103
+ // Only the atoms on the path here are skipped: another child's path may reach this atom's
104
+ // parents too, as in a diamond.
105
+ seen.delete(id);
103
106
  depths.set(id, value);
104
107
  return value;
105
108
  };
@@ -9,6 +9,12 @@ export type ValueState = {
9
9
  export declare const valueState: (value: unknown) => ValueState;
10
10
  /** A short description of the state: `Success, waiting`. */
11
11
  export declare const stateText: (state: ValueState) => string;
12
+ /**
13
+ * What a failure failed with, from its first reason: a typed error by its name (`CityNotFound`),
14
+ * or with its fields, each written by `write`, when given; a defect as `defect: TypeError`; an
15
+ * interruption as `interrupted`.
16
+ */
17
+ export declare const failureText: (cause: Cause.Cause<unknown>, write?: (field: unknown) => string) => string;
12
18
  /**
13
19
  * Turns a value into plain data to print: an `AsyncResult` as its tag and contents, a failure's
14
20
  * cause pretty-printed, Effect's data types through their own `toJSON`, maps and sets as entries,
@@ -17,11 +23,5 @@ export declare const stateText: (state: ValueState) => string;
17
23
  export declare const plain: (value: unknown, depth?: number, seen?: Set<object>) => unknown;
18
24
  /** The value written out in full, for its sheet. */
19
25
  export declare const detail: (value: unknown) => string;
20
- /**
21
- * What a failure failed with, from its first reason: a typed error by its name (`CityNotFound`),
22
- * or with its fields when `full`; a defect as `defect: TypeError`; an interruption as
23
- * `interrupted`.
24
- */
25
- export declare const failureText: (cause: Cause.Cause<unknown>, full?: boolean) => string;
26
26
  /** The value on one line, cut to `length` characters. */
27
27
  export declare const preview: (value: unknown, length?: number) => string;
@@ -15,6 +15,59 @@ const hasToJSON = (value) => typeof value.toJSON === "function";
15
15
  // How much of a value is written out: deeper or longer parts are cut short.
16
16
  const maxDepth = 5;
17
17
  const maxItems = 50;
18
+ // Values JSON has no words for, written out bare: `NaN`, `Infinity`, `undefined`.
19
+ const bare = (text) => `\u0000${text}\u0000`;
20
+ const json = (data, indent) => (typeof data === "string"
21
+ ? JSON.stringify(data)
22
+ : (JSON.stringify(data, undefined, indent) ?? String(data))).replaceAll(/"\\u0000(?<text>.*?)\\u0000"/gu, "$<text>");
23
+ /** An error's name: a tagged error's `_tag`, an `Error`'s `name`, or the value as a string. */
24
+ const errorName = (error) => {
25
+ if (typeof error === "object" && error !== null) {
26
+ if ("_tag" in error && typeof error._tag === "string") {
27
+ return error._tag;
28
+ }
29
+ if (error instanceof Error) {
30
+ return error.name;
31
+ }
32
+ }
33
+ return String(error);
34
+ };
35
+ /**
36
+ * An error with its fields, each written by `write`, as `CityNotFound { city: "Atlantis" }`, or
37
+ * its message if it has one.
38
+ */
39
+ const errorText = (error, write) => {
40
+ const name = errorName(error);
41
+ if (typeof error !== "object" || error === null) {
42
+ return name;
43
+ }
44
+ if ("message" in error &&
45
+ typeof error.message === "string" &&
46
+ error.message !== "") {
47
+ return `${name}: ${error.message}`;
48
+ }
49
+ const fields = Object.entries(error).filter(([key]) => key !== "_tag");
50
+ const body = fields.map(([key, field]) => `${key}: ${write(field)}`);
51
+ return body.length > 0 ? `${name} { ${body.join(", ")} }` : name;
52
+ };
53
+ /**
54
+ * What a failure failed with, from its first reason: a typed error by its name (`CityNotFound`),
55
+ * or with its fields, each written by `write`, when given; a defect as `defect: TypeError`; an
56
+ * interruption as `interrupted`.
57
+ */
58
+ export const failureText = (cause, write) => {
59
+ const [reason] = cause.reasons;
60
+ if (reason === undefined) {
61
+ return "empty cause";
62
+ }
63
+ if (Cause.isFailReason(reason)) {
64
+ return write ? errorText(reason.error, write) : errorName(reason.error);
65
+ }
66
+ if (Cause.isDieReason(reason)) {
67
+ return `defect: ${write ? errorText(reason.defect, write) : errorName(reason.defect)}`;
68
+ }
69
+ return "interrupted";
70
+ };
18
71
  const plainResult = (result, inner) => {
19
72
  switch (result._tag) {
20
73
  case "Initial": {
@@ -28,14 +81,27 @@ const plainResult = (result, inner) => {
28
81
  };
29
82
  }
30
83
  default: {
84
+ // What it failed with, fields and all, as the graph's note promises; then the whole cause.
85
+ // oxlint-disable-next-line eslint/sort-keys -- what it failed with reads before the whole cause
31
86
  return {
32
87
  _tag: "Failure",
88
+ error: failureText(result.cause, (field) => json(inner(field))),
33
89
  cause: Cause.pretty(result.cause),
34
90
  waiting: result.waiting,
35
91
  };
36
92
  }
37
93
  }
38
94
  };
95
+ /** The first `maxItems` items, and how many more there are. */
96
+ const listed = (items, inner) => {
97
+ const shown = items.slice(0, maxItems).map(inner);
98
+ return items.length > maxItems
99
+ ? [...shown, `… ${items.length - maxItems} more`]
100
+ : shown;
101
+ };
102
+ /** An object cut to `maxItems` entries, saying how many more there are. */
103
+ const withMore = (object, count) => count > maxItems ? { ...object, "…": `${count - maxItems} more` } : object;
104
+ const isPrimitive = (value) => value === null || (typeof value !== "object" && typeof value !== "function");
39
105
  const plainObject = (value, inner) => {
40
106
  if (AsyncResult.isAsyncResult(value)) {
41
107
  return plainResult(value, inner);
@@ -44,31 +110,36 @@ const plainObject = (value, inner) => {
44
110
  return value.toISOString();
45
111
  }
46
112
  if (value instanceof Error) {
47
- return `${value.name}: ${value.message}`;
113
+ // A tagged error's fields, as `CityNotFound { city: "Atlantis" }`.
114
+ return errorText(value, (field) => json(inner(field)));
48
115
  }
49
116
  if (value instanceof Map) {
50
- return Object.fromEntries([...value]
51
- .slice(0, maxItems)
52
- .map(([key, entry]) => [String(key), inner(entry)]));
117
+ const entries = [...value];
118
+ // Primitive keys that stay distinct as strings make an object; any other keys would collide
119
+ // or lose themselves as strings, so those maps are written as `[key, value]` pairs.
120
+ const keys = entries.map(([key]) => key);
121
+ if (keys.every((key) => isPrimitive(key)) &&
122
+ new Set(keys.map(String)).size === keys.length) {
123
+ return withMore(Object.fromEntries(entries
124
+ .slice(0, maxItems)
125
+ .map(([key, entry]) => [String(key), inner(entry)])), entries.length);
126
+ }
127
+ return listed(entries, ([key, entry]) => [inner(key), inner(entry)]);
53
128
  }
54
129
  if (value instanceof Set) {
55
- return [...value].slice(0, maxItems).map(inner);
130
+ return listed([...value], inner);
56
131
  }
57
132
  if (Array.isArray(value)) {
58
- const items = value.slice(0, maxItems).map(inner);
59
- return value.length > maxItems
60
- ? [...items, `… ${value.length - maxItems} more`]
61
- : items;
133
+ return listed(value, inner);
62
134
  }
63
135
  if (hasToJSON(value)) {
64
- const json = value.toJSON();
65
- if (json !== value) {
66
- return inner(json);
136
+ const data = value.toJSON();
137
+ if (data !== value) {
138
+ return inner(data);
67
139
  }
68
140
  }
69
- return Object.fromEntries(Object.entries(value)
70
- .slice(0, maxItems)
71
- .map(([key, entry]) => [key, inner(entry)]));
141
+ const entries = Object.entries(value);
142
+ return withMore(Object.fromEntries(entries.slice(0, maxItems).map(([key, entry]) => [key, inner(entry)])), entries.length);
72
143
  };
73
144
  /**
74
145
  * Turns a value into plain data to print: an `AsyncResult` as its tag and contents, a failure's
@@ -86,6 +157,12 @@ export const plain = (value, depth = 0, seen = new Set()) => {
86
157
  case "symbol": {
87
158
  return value.toString();
88
159
  }
160
+ case "number": {
161
+ return Number.isFinite(value) ? value : bare(String(value));
162
+ }
163
+ case "undefined": {
164
+ return depth === 0 ? value : bare("undefined");
165
+ }
89
166
  case "object": {
90
167
  break;
91
168
  }
@@ -113,56 +190,8 @@ export const plain = (value, depth = 0, seen = new Set()) => {
113
190
  seen.delete(value);
114
191
  }
115
192
  };
116
- const json = (data, indent) => typeof data === "string"
117
- ? JSON.stringify(data)
118
- : (JSON.stringify(data, undefined, indent) ?? String(data));
119
193
  /** The value written out in full, for its sheet. */
120
194
  export const detail = (value) => json(plain(value), 2);
121
- /** An error's name: a tagged error's `_tag`, an `Error`'s `name`, or the value as a string. */
122
- const errorName = (error) => {
123
- if (typeof error === "object" && error !== null) {
124
- if ("_tag" in error && typeof error._tag === "string") {
125
- return error._tag;
126
- }
127
- if (error instanceof Error) {
128
- return error.name;
129
- }
130
- }
131
- return String(error);
132
- };
133
- /** An error with its fields, as `CityNotFound { city: "Atlantis" }`, or its message if it has one. */
134
- const errorText = (error) => {
135
- const name = errorName(error);
136
- if (typeof error !== "object" || error === null) {
137
- return name;
138
- }
139
- if ("message" in error &&
140
- typeof error.message === "string" &&
141
- error.message !== "") {
142
- return `${name}: ${error.message}`;
143
- }
144
- const fields = Object.entries(error).filter(([key]) => key !== "_tag");
145
- const body = fields.map(([key, field]) => `${key}: ${json(plain(field))}`);
146
- return body.length > 0 ? `${name} { ${body.join(", ")} }` : name;
147
- };
148
- /**
149
- * What a failure failed with, from its first reason: a typed error by its name (`CityNotFound`),
150
- * or with its fields when `full`; a defect as `defect: TypeError`; an interruption as
151
- * `interrupted`.
152
- */
153
- export const failureText = (cause, full = false) => {
154
- const [reason] = cause.reasons;
155
- if (reason === undefined) {
156
- return "empty cause";
157
- }
158
- if (Cause.isFailReason(reason)) {
159
- return full ? errorText(reason.error) : errorName(reason.error);
160
- }
161
- if (Cause.isDieReason(reason)) {
162
- return `defect: ${full ? errorText(reason.defect) : errorName(reason.defect)}`;
163
- }
164
- return "interrupted";
165
- };
166
195
  /** An `AsyncResult` on one line: its value, through `inner`, or what it failed with. */
167
196
  const resultText = (result, inner) => {
168
197
  let text = "Initial";
@@ -170,7 +199,7 @@ const resultText = (result, inner) => {
170
199
  text = inner(result.value);
171
200
  }
172
201
  else if (result._tag === "Failure") {
173
- text = failureText(result.cause, true);
202
+ text = failureText(result.cause, (field) => json(plain(field)));
174
203
  }
175
204
  return result.waiting ? `${text}, waiting` : text;
176
205
  };
@@ -91,6 +91,8 @@ export class Model {
91
91
  }
92
92
  clearTimeline() {
93
93
  this.#log = [];
94
+ // Paused too: clearing is asked of the timeline on screen.
95
+ this.timeline = [];
94
96
  this.#schedule();
95
97
  }
96
98
  #entry(atom) {
@@ -17,7 +17,7 @@ export interface Identity {
17
17
  * The place a stack frame points at. The plugin's frames hold the file as the dev server addresses
18
18
  * it; `Atom.withLabel`'s are the browser's, a URL with the dev server's origin and a query.
19
19
  */
20
- export declare const parseFrame: (frame: string) => Place | undefined;
20
+ export declare const parseFrame: (frame: string, name?: string) => Place | undefined;
21
21
  export declare const identify: (atom: Atom.Atom<unknown>) => Identity;
22
22
  /** The file's name without its folders, for a short reference: `todos.ts:12`. */
23
23
  export declare const shortPlace: (place: Place) => string;
@@ -2,12 +2,29 @@
2
2
  import { Atom } from "effect/reactivity";
3
3
  // The last `file:line:column` in a stack frame, with or without parentheses around it.
4
4
  const framePattern = /(?<file>[^\s()]+):(?<line>\d+):(?<column>\d+)\)?\s*$/u;
5
+ // A place as the plugin writes it, `/src/lib/todos.ts:4:14`, whatever the file's name holds.
6
+ const ownPattern = /^(?<file>.+):(?<line>\d+):(?<column>\d+)$/u;
7
+ // A browser frame's URL, which may hold parentheses, as a SvelteKit route group's folder does.
8
+ const urlPattern = /(?<file>[a-z][\w+.-]*:\/\/\S+?):(?<line>\d+):(?<column>\d+)\)?\s*$/iu;
5
9
  /**
6
10
  * The place a stack frame points at. The plugin's frames hold the file as the dev server addresses
7
11
  * it; `Atom.withLabel`'s are the browser's, a URL with the dev server's origin and a query.
8
12
  */
9
- export const parseFrame = (frame) => {
10
- const groups = framePattern.exec(frame)?.groups;
13
+ export const parseFrame = (frame, name) => {
14
+ // The plugin's own frame, `at ${name} (${place})`: its place is all inside the parentheses, which
15
+ // a SvelteKit route group, as in `/src/routes/(app)/+page.svelte`, has some of.
16
+ const prefix = name === undefined ? undefined : `at ${name} (`;
17
+ const own = prefix !== undefined && frame.startsWith(prefix) && frame.endsWith(")")
18
+ ? ownPattern.exec(frame.slice(prefix.length, -1))?.groups
19
+ : undefined;
20
+ if (own?.file !== undefined) {
21
+ return {
22
+ column: Number(own.column),
23
+ file: own.file,
24
+ line: Number(own.line),
25
+ };
26
+ }
27
+ const groups = (urlPattern.exec(frame) ?? framePattern.exec(frame))?.groups;
11
28
  if (groups?.file === undefined) {
12
29
  return undefined;
13
30
  }
@@ -28,7 +45,7 @@ export const identify = (atom) => {
28
45
  return {
29
46
  key,
30
47
  name,
31
- place: frame === undefined ? undefined : parseFrame(frame),
48
+ place: frame === undefined ? undefined : parseFrame(frame, name),
32
49
  };
33
50
  };
34
51
  /** The file's name without its folders, for a short reference: `todos.ts:12`. */
@@ -13,7 +13,10 @@ export declare const parseShortcut: (text: string) => Shortcut | undefined;
13
13
  export declare const stringifyShortcut: (shortcut: Shortcut) => string;
14
14
  /** For display: "Alt Shift A", or "⌘ ⇧ A" on a Mac. */
15
15
  export declare const formatShortcut: (shortcut: Shortcut, mac: boolean) => string;
16
- /** Whether a key press is the shortcut, with exactly its modifiers. */
16
+ /**
17
+ * Whether a key press is the shortcut, with exactly its modifiers. The code is compared without
18
+ * case: the settings save it in lower case, and a code such as `ArrowUp` doesn't read back as it was.
19
+ */
17
20
  export declare const matchesShortcut: (event: KeyboardEvent, shortcut: Shortcut) => boolean;
18
21
  /**
19
22
  * The shortcut a key press makes, when recording a new one: `undefined` for a modifier on its own,
@@ -12,6 +12,10 @@ const modifierCodes = new Set([
12
12
  "ShiftLeft",
13
13
  "ShiftRight",
14
14
  ]);
15
+ // The first words of codes with two words, so a code saved in lower case reads back as the key's
16
+ // code does: "arrowup" is `ArrowUp`, "pagedown" is `PageDown`, "bracketleft" is `BracketLeft`.
17
+ const twoWordCode = /^(?<first>arrow|bracket|caps|context|numpad|num|page|print|scroll)(?<second>[a-z]+)$/iu;
18
+ const capitalise = (word) => word.charAt(0).toUpperCase() + word.slice(1);
15
19
  /** The code a key's name stands for: `a` is `KeyA`, `1` is `Digit1`, and anything else as it is. */
16
20
  const codeOf = (key) => {
17
21
  if (/^[a-z]$/iu.test(key)) {
@@ -20,7 +24,11 @@ const codeOf = (key) => {
20
24
  if (/^\d$/u.test(key)) {
21
25
  return `Digit${key}`;
22
26
  }
23
- return key.length > 1 ? key.charAt(0).toUpperCase() + key.slice(1) : key;
27
+ const { first, second } = twoWordCode.exec(key)?.groups ?? {};
28
+ if (first !== undefined && second !== undefined) {
29
+ return capitalise(first.toLowerCase()) + capitalise(second.toLowerCase());
30
+ }
31
+ return key.length > 1 ? capitalise(key) : key;
24
32
  };
25
33
  /** Reads "alt+shift+a" (or "Ctrl+Shift+F2", "meta+k"); `undefined` when there is no key. */
26
34
  export const parseShortcut = (text) => {
@@ -63,8 +71,11 @@ export const formatShortcut = (shortcut, mac) => [
63
71
  ]
64
72
  .filter(Boolean)
65
73
  .join(" ");
66
- /** Whether a key press is the shortcut, with exactly its modifiers. */
67
- export const matchesShortcut = (event, shortcut) => event.code === shortcut.code &&
74
+ /**
75
+ * Whether a key press is the shortcut, with exactly its modifiers. The code is compared without
76
+ * case: the settings save it in lower case, and a code such as `ArrowUp` doesn't read back as it was.
77
+ */
78
+ export const matchesShortcut = (event, shortcut) => event.code.toLowerCase() === shortcut.code.toLowerCase() &&
68
79
  event.altKey === shortcut.alt &&
69
80
  event.ctrlKey === shortcut.ctrl &&
70
81
  event.metaKey === shortcut.meta &&
@@ -50,8 +50,13 @@
50
50
  updated: true,
51
51
  });
52
52
  let search = $state("");
53
- // An atom picked from the list: its rows only.
54
- let only = $state<number>();
53
+ // An atom picked from the list: its rows only. Ids are the model's, so a pick lasts only as long
54
+ // as the model it was made in: another registry's model has its own.
55
+ let picked = $state.raw<{ readonly model: Model; readonly id: number }>();
56
+ const only = $derived(picked?.model === model ? picked.id : undefined);
57
+ const pick = (id: number | undefined) => {
58
+ picked = id === undefined ? undefined : { id, model };
59
+ };
55
60
 
56
61
  const byId = $derived(new Map(model.atoms.map((view) => [view.id, view])));
57
62
  const nameOf = (id: number) => byId.get(id)?.name ?? `atom #${id}`;
@@ -93,7 +98,7 @@
93
98
  {/each}
94
99
  <span class="spacer"></span>
95
100
  {#if only !== undefined}
96
- <button class="tool" onclick={() => (only = undefined)} type="button">
101
+ <button class="tool" onclick={() => pick(undefined)} type="button">
97
102
  only {nameOf(only)} ✕
98
103
  </button>
99
104
  {/if}
@@ -111,14 +116,14 @@
111
116
  <li class="row {kinds[entry.tag]}" class:alert={entry.tag === "Interrupted"}>
112
117
  <span class="when">{time(entry)}</span>
113
118
  <span class="what">{verbs[entry.tag]}</span>
114
- <button class="atom" class:plumbing={byId.get(entry.atom)?.plumbing} onclick={() => (only = entry.atom)} ondblclick={() => onselect(entry.atom)} title="Click: only this atom's rows. Double-click: its sheet." type="button">
119
+ <button class="atom" class:plumbing={byId.get(entry.atom)?.plumbing} onclick={() => pick(entry.atom)} ondblclick={() => onselect(entry.atom)} title="Click: only this atom's rows. Double-click: its sheet." type="button">
115
120
  {nameOf(entry.atom)}
116
121
  </button>
117
122
  <span class="detail">
118
123
  {#if entry.tag === "Built" && entry.related.length > 0}
119
124
  because
120
125
  {#each entry.related as id, index (id)}{#if index > 0},{/if}
121
- <button class="atom inline" onclick={() => (only = id)} type="button">{nameOf(id)}</button>{/each}
126
+ <button class="atom inline" onclick={() => pick(id)} type="button">{nameOf(id)}</button>{/each}
122
127
  changed
123
128
  {:else if entry.tag === "Built"}
124
129
  {entry.detail === "first read" ? "first read" : `because it was ${entry.detail}`}
@@ -11,6 +11,7 @@ import path from "node:path";
11
11
  import { tsPlugin } from "@sveltejs/acorn-typescript";
12
12
  import { Parser } from "acorn";
13
13
  import MagicString from "magic-string";
14
+ import { parse as parseComponent } from "svelte/compiler";
14
15
  /** The id the transformed code imports `label` from; the plugin resolves it to ./label.ts. */
15
16
  export const labelModule = "virtual:effect-atom-svelte-devtools/label";
16
17
  const labelBinding = "__effectAtomSvelteLabel";
@@ -77,6 +78,30 @@ const plainValues = new Set([
77
78
  "ArrayExpression",
78
79
  "UnaryExpression",
79
80
  ]);
81
+ // What a state atom can be piped through and stay one: what is written to it is still what it
82
+ // reads. `Atom.map` and the like write through to their source, so their value can't be written
83
+ // back.
84
+ const stateKeeping = new Set([
85
+ "keepAlive",
86
+ "autoDispose",
87
+ "setIdleTTL",
88
+ "setLazy",
89
+ "withEquality",
90
+ "withLabel",
91
+ "serializable",
92
+ "withServerValue",
93
+ "withServerValueInitial",
94
+ ]);
95
+ /** Whether `Atom.keepAlive`, `Atom.setIdleTTL(...)` or the like: one of `stateKeeping`. */
96
+ const keepsState = (argument) => {
97
+ const node = unwrap(argument);
98
+ const callee = node.type === "CallExpression" ? unwrap(node.callee) : node;
99
+ return (callee.type === "MemberExpression" &&
100
+ !callee.computed &&
101
+ callee.object.type === "Identifier" &&
102
+ callee.object.name === "Atom" &&
103
+ stateKeeping.has(String(callee.property.name)));
104
+ };
80
105
  /**
81
106
  * Whether the call makes a state atom, such as `Atom.make(0)` or `Atom.make([]).pipe(...)`: one
82
107
  * that holds what is written to it, which a hot reload can carry over.
@@ -89,7 +114,9 @@ const isState = (node) => {
89
114
  const object = callee.object;
90
115
  const property = callee.property;
91
116
  if (property.type === "Identifier" && property.name === "pipe") {
92
- return object.type === "CallExpression" && isState(object);
117
+ return (object.type === "CallExpression" &&
118
+ isState(object) &&
119
+ node.arguments.every(keepsState));
93
120
  }
94
121
  const [argument] = node.arguments;
95
122
  return (object.type === "Identifier" &&
@@ -243,19 +270,67 @@ const parse = (code) => parser.parse(code, {
243
270
  });
244
271
  // Svelte's own pattern for finding scripts to preprocess (svelte/src/compiler/preprocess).
245
272
  const scriptPattern = /<!--[^]*?-->|<script(?<attributes>(?:\s+[^=>'"/\s]+=(?:"[^"]*"|'[^']*'|[^>\s]+)|\s+[^=>'"/\s]+)*\s*)(?:\/>|>(?<code>[\S\s]*?)<\/script>)/gu;
273
+ /** Text blanked out, keeping its offsets (an astral character is two UTF-16 units) and lines. */
274
+ const blank = (text) => text.replaceAll(/[^\n]/gu, (character) => " ".repeat(character.length));
275
+ /** The component with each script and style's content blanked out, so only its markup is left. */
276
+ const markupOf = (source, matches) => {
277
+ let markup = source;
278
+ for (const match of matches) {
279
+ const { code } = match.groups ?? {};
280
+ if (code !== undefined) {
281
+ const from = match.index + match[0].length - "</script>".length - code.length;
282
+ markup =
283
+ markup.slice(0, from) + blank(code) + markup.slice(from + code.length);
284
+ }
285
+ }
286
+ return markup.replaceAll(/(?<open><style(?:\s[^>]*)?>)(?<css>[^]*?)<\/style>/gu, (_, open, css) => `${open}${blank(css)}</style>`);
287
+ };
288
+ /**
289
+ * Where the component's own scripts (its instance and module scripts) start, as Svelte's parser
290
+ * sees them: a script nested in the markup (in an element, a block or <svelte:head>) is page HTML.
291
+ * Takes the blanked markup, so a script or style that needs a preprocessor doesn't matter.
292
+ * `undefined` if the markup doesn't parse either.
293
+ */
294
+ const topLevel = (markup) => {
295
+ try {
296
+ const ast = parseComponent(markup, { modern: true });
297
+ // Svelte drops a byte order mark before parsing, so its offsets are one short of the source's.
298
+ const shift = markup.startsWith("\uFEFF") ? 1 : 0;
299
+ return new Set([ast.instance?.start, ast.module?.start]
300
+ .filter((start) => start !== undefined)
301
+ .map((start) => start + shift));
302
+ }
303
+ catch {
304
+ return undefined;
305
+ }
306
+ };
246
307
  /** The scripts of a component: where each one's code starts, the code, and if it is the module script. */
247
308
  const scripts = (source) => {
248
309
  const found = [];
249
- for (const match of source.matchAll(scriptPattern)) {
250
- const [whole] = match;
310
+ const matches = [...source.matchAll(scriptPattern)];
311
+ const markup = markupOf(source, matches);
312
+ const top = topLevel(markup);
313
+ // The fallback when the markup doesn't parse. HTML comments are matched too, and scripts and
314
+ // styles are blanked, so neither kind of comment that mentions <svelte:head> starts a head.
315
+ const heads = [
316
+ ...markup.matchAll(/<!--[^]*?-->|<svelte:head\b[^]*?<\/svelte:head>/gu),
317
+ ]
318
+ .filter((m) => m[0].startsWith("<svelte:head"))
319
+ .map((m) => [m.index, m.index + m[0].length]);
320
+ for (const match of matches) {
251
321
  const { attributes, code } = match.groups ?? {};
252
322
  if (attributes === undefined || code === undefined) {
253
323
  continue;
254
324
  }
325
+ if (top
326
+ ? !top.has(match.index)
327
+ : heads.some(([from, to]) => match.index > from && match.index < to)) {
328
+ continue;
329
+ }
255
330
  found.push({
256
331
  code,
257
332
  module: /\bmodule\b/u.test(attributes),
258
- start: match.index + whole.indexOf(">") + 1,
333
+ start: match.index + "<script".length + attributes.length + 1,
259
334
  });
260
335
  }
261
336
  return found;
package/dist/vite.js CHANGED
@@ -72,8 +72,10 @@ export const atomLabels = (options = {}) => {
72
72
  catch {
73
73
  // The app can't resolve the library, so there is none of its code to skip.
74
74
  }
75
+ // The plugin that compiles components, among the plugins as Vite runs them: "vite-plugin-svelte"
76
+ // up to version 6, "vite-plugin-svelte:compile" from 7, which runs after every "pre" plugin.
75
77
  const names = config.plugins.map((plugin) => plugin.name);
76
- const svelte = names.findIndex((name) => name.startsWith("vite-plugin-svelte"));
78
+ const svelte = names.findIndex((name) => name === "vite-plugin-svelte" || name === "vite-plugin-svelte:compile");
77
79
  if (svelte !== -1 &&
78
80
  svelte < names.indexOf("effect-atom-svelte-devtools:labels")) {
79
81
  config.logger.warn("effect-atom-svelte-devtools: atomLabels() comes after the Svelte plugin, so atoms declared in components aren't labelled. Put it before sveltekit() or svelte().");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "effect-atom-svelte-devtools",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "Developer tools for effect-atom-svelte: atom names from your source, and a live view of the registry",
5
5
  "keywords": [
6
6
  "devtools",
@@ -68,7 +68,7 @@
68
68
  },
69
69
  "peerDependencies": {
70
70
  "effect": "~4.0.0",
71
- "effect-atom-svelte": "^0.2.0",
71
+ "effect-atom-svelte": "^0.3.0",
72
72
  "svelte": "^5.57.2",
73
73
  "vite": ">=5.0.0"
74
74
  },