@hajimism/dek 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +92 -0
  2. package/README.ja.md +1 -1
  3. package/README.md +1 -1
  4. package/package.json +8 -7
  5. package/src/cli/address.ts +59 -15
  6. package/src/cli/commands.ts +47 -14
  7. package/src/cli/contract.ts +49 -3
  8. package/src/cli/files.ts +1 -0
  9. package/src/cli/format.ts +5 -4
  10. package/src/cli/goto.ts +41 -10
  11. package/src/cli/keep-alive.ts +12 -6
  12. package/src/cli/lint.ts +32 -13
  13. package/src/cli/ls.ts +5 -1
  14. package/src/cli/main.ts +48 -13
  15. package/src/cli/new.ts +14 -1
  16. package/src/cli/ref.ts +1 -0
  17. package/src/cli/result.ts +42 -4
  18. package/src/cli/scope.ts +40 -1
  19. package/src/cli/shot.ts +77 -6
  20. package/src/cli/show.ts +15 -2
  21. package/src/cli/text.ts +61 -9
  22. package/src/cli/theme.ts +50 -16
  23. package/src/cli/tty.ts +16 -2
  24. package/src/cli/voice.ts +11 -6
  25. package/src/core/assets.ts +18 -10
  26. package/src/core/attribute-value.ts +188 -0
  27. package/src/core/build.ts +3 -3
  28. package/src/core/css-scan.ts +173 -39
  29. package/src/core/css-transform.ts +57 -11
  30. package/src/core/css.ts +19 -13
  31. package/src/core/foreign-text.ts +138 -0
  32. package/src/core/github.ts +1 -0
  33. package/src/core/html-entities.ts +318 -0
  34. package/src/core/html-scan.ts +49 -27
  35. package/src/core/html.ts +21 -15
  36. package/src/core/lint/asset-refs.ts +44 -6
  37. package/src/core/lint/context.ts +2 -0
  38. package/src/core/lint/shared-styles.ts +26 -1
  39. package/src/core/lint/slide-html.ts +21 -18
  40. package/src/core/lint/theme-css.ts +64 -3
  41. package/src/core/lint.ts +15 -2
  42. package/src/core/mv.ts +28 -18
  43. package/src/core/order.ts +14 -0
  44. package/src/core/path.ts +8 -2
  45. package/src/core/playwright-module.d.ts +12 -1
  46. package/src/core/playwright-motion.ts +1 -0
  47. package/src/core/playwright-sheet.ts +1 -0
  48. package/src/core/playwright-visual.ts +27 -10
  49. package/src/core/playwright.ts +77 -19
  50. package/src/core/pptx.ts +1 -0
  51. package/src/core/ref-name.ts +8 -3
  52. package/src/core/ref.ts +145 -47
  53. package/src/core/resolve.ts +3 -2
  54. package/src/core/rumdl.ts +51 -25
  55. package/src/core/safe-fs.ts +19 -2
  56. package/src/core/sandbox.ts +217 -0
  57. package/src/core/shot-cache.ts +1 -0
  58. package/src/core/slide-eval-worker.ts +1 -0
  59. package/src/core/slide-measure.ts +1 -0
  60. package/src/core/slide-script-eval.ts +2 -0
  61. package/src/core/spawn.ts +136 -35
  62. package/src/core/sync.ts +3 -12
  63. package/src/core/tar.ts +315 -0
  64. package/src/core/text-contrast.ts +2 -0
  65. package/src/core/toml-keys.ts +116 -51
  66. package/src/core/url-attributes.ts +27 -9
  67. package/src/core/visual.ts +28 -9
  68. package/src/core/voice.ts +2 -1
  69. package/src/server/auth.ts +21 -0
  70. package/src/server/dev.ts +13 -5
  71. package/src/server/lock.ts +43 -13
  72. package/src/server/serial.ts +8 -2
  73. package/src/video/mux.ts +27 -3
  74. package/src/video/recorder.ts +3 -2
  75. package/src/video/worker.ts +1 -0
  76. package/src/voice/engine.ts +81 -18
  77. package/tsconfig.json +1 -1
@@ -0,0 +1,188 @@
1
+ /**
2
+ * An attribute's value as the browser reads it. Bun's HTMLRewriter gives each value as written,
3
+ * character references and all, so `assets/Q&A.png` would name a file the page never loads.
4
+ * Every value lint or the build reads off the rewriter goes through here first; a value written
5
+ * back into the markup is written from the one as written, never from this.
6
+ */
7
+ import { LEGACY_REFERENCES, NAMED_REFERENCES } from "./html-entities.ts";
8
+
9
+ /** A decoded value, and where in the value as written each of its UTF-16 units comes from. */
10
+ export type DecodedAttribute = {
11
+ value: string;
12
+ /** The offset in the written value of the unit at `index`; `value.length` maps past the end. */
13
+ writtenAt(index: number): number;
14
+ };
15
+
16
+ /** The value of `name` on a rewriter's element as the browser reads it, or null when absent. */
17
+ export function attributeOf(
18
+ element: { getAttribute(name: string): string | null },
19
+ name: string,
20
+ ): string | null {
21
+ const written = element.getAttribute(name);
22
+ return written === null ? null : decodeAttribute(written).value;
23
+ }
24
+
25
+ /**
26
+ * Whether `char` is ASCII whitespace, the only whitespace HTML splits a list of tokens on or trims
27
+ * a value of. A no-break space, written as itself or as ` `, is part of the value.
28
+ */
29
+ export function isAsciiWhitespace(char: string | undefined): boolean {
30
+ return char === " " || char === "\t" || char === "\n" || char === "\f" || char === "\r";
31
+ }
32
+
33
+ /** The tokens of a value such as `class` or `role`, split on ASCII whitespace as HTML splits it. */
34
+ export function attributeTokens(value: string | null | undefined): string[] {
35
+ return (value ?? "").split(/[\t\n\f\r ]+/).filter(Boolean);
36
+ }
37
+
38
+ /** `value` without the ASCII whitespace at its ends, as HTML trims a keyword or a name. */
39
+ export function trimAsciiWhitespace(value: string): string {
40
+ return value.replace(/^[\t\n\f\r ]+|[\t\n\f\r ]+$/g, "");
41
+ }
42
+
43
+ /**
44
+ * `written` read the way the HTML standard reads an attribute value: every numeric and named
45
+ * character reference decoded, a carriage return read as a line feed, and a NUL as U+FFFD. A
46
+ * name the standard allows without its `;` stays as written when a letter, a digit, or `=`
47
+ * follows it, so the `&copy` of `?a=1&copy=2` is left alone, as the browser leaves it.
48
+ */
49
+ export function decodeAttribute(written: string): DecodedAttribute {
50
+ // Each replacement, where it is in the decoded value and where in the written one, in order.
51
+ const spans: Array<{ start: number; end: number; writtenStart: number; writtenEnd: number }> = [];
52
+ let shift = 0;
53
+ const value = written.replace(
54
+ REFERENCE_RE,
55
+ (match: string, hex?: string, decimal?: string, name?: string, semicolon?: string, at = 0) => {
56
+ const text = replacement(written, match, at, { hex, decimal, name, semicolon });
57
+ if (text !== match) {
58
+ const start = at - shift;
59
+ spans.push({
60
+ start,
61
+ end: start + text.length,
62
+ writtenStart: at,
63
+ writtenEnd: at + match.length,
64
+ });
65
+ shift += match.length - text.length;
66
+ }
67
+ return text;
68
+ },
69
+ );
70
+ return {
71
+ value,
72
+ writtenAt(index) {
73
+ let offset = index;
74
+ for (const span of spans) {
75
+ if (index < span.start) {
76
+ break;
77
+ }
78
+ if (index < span.end) {
79
+ return span.writtenStart;
80
+ }
81
+ offset = span.writtenEnd + (index - span.end);
82
+ }
83
+ return offset;
84
+ },
85
+ };
86
+ }
87
+
88
+ /**
89
+ * A character reference, with its parts as groups; a carriage return, which the input stream reads
90
+ * as a line feed; or a NUL, which the tokenizer reads as U+FFFD in a value.
91
+ */
92
+ const REFERENCE_RE = /&(?:#(?:[xX]([0-9a-fA-F]+)|([0-9]+));?|([A-Za-z0-9]+)(;?))|\r\n?|\0/g;
93
+
94
+ /** What one match of REFERENCE_RE reads as: itself, when the standard leaves it as written. */
95
+ function replacement(
96
+ written: string,
97
+ match: string,
98
+ at: number,
99
+ parts: { hex?: string; decimal?: string; name?: string; semicolon?: string },
100
+ ): string {
101
+ if (match === "\0") {
102
+ return "\uFFFD";
103
+ }
104
+ if (match.startsWith("\r")) {
105
+ return "\n";
106
+ }
107
+ if (parts.hex !== undefined || parts.decimal !== undefined) {
108
+ return numericReference(
109
+ parts.hex === undefined
110
+ ? Number.parseInt(parts.decimal ?? "", 10)
111
+ : Number.parseInt(parts.hex, 16),
112
+ );
113
+ }
114
+ const name = parts.name ?? "";
115
+ if (parts.semicolon) {
116
+ return namedReferences().get(name) ?? match;
117
+ }
118
+ // The browser takes the longest name it knows. A legacy name shorter than the run of letters
119
+ // and digits is followed by one of them, which keeps it as written, so only the whole run can.
120
+ if (legacyReferences().has(name) && written[at + match.length] !== "=") {
121
+ return namedReferences().get(name) ?? match;
122
+ }
123
+ return match;
124
+ }
125
+
126
+ /**
127
+ * The character a numeric reference stands for: U+FFFD for NUL, a surrogate, or a number past
128
+ * Unicode, and for 0x80 to 0x9F the Windows-1252 character the standard reads it as.
129
+ */
130
+ function numericReference(number: number): string {
131
+ if (number === 0 || number > 0x10ffff || (number >= 0xd800 && number <= 0xdfff)) {
132
+ return "\uFFFD";
133
+ }
134
+ return String.fromCodePoint(C1_REPLACEMENTS.get(number) ?? number);
135
+ }
136
+
137
+ /** The HTML standard's table for a numeric reference to a C1 control. */
138
+ const C1_REPLACEMENTS: ReadonlyMap<number, number> = new Map([
139
+ [0x80, 0x20ac],
140
+ [0x82, 0x201a],
141
+ [0x83, 0x0192],
142
+ [0x84, 0x201e],
143
+ [0x85, 0x2026],
144
+ [0x86, 0x2020],
145
+ [0x87, 0x2021],
146
+ [0x88, 0x02c6],
147
+ [0x89, 0x2030],
148
+ [0x8a, 0x0160],
149
+ [0x8b, 0x2039],
150
+ [0x8c, 0x0152],
151
+ [0x8e, 0x017d],
152
+ [0x91, 0x2018],
153
+ [0x92, 0x2019],
154
+ [0x93, 0x201c],
155
+ [0x94, 0x201d],
156
+ [0x95, 0x2022],
157
+ [0x96, 0x2013],
158
+ [0x97, 0x2014],
159
+ [0x98, 0x02dc],
160
+ [0x99, 0x2122],
161
+ [0x9a, 0x0161],
162
+ [0x9b, 0x203a],
163
+ [0x9c, 0x0153],
164
+ [0x9e, 0x017e],
165
+ [0x9f, 0x0178],
166
+ ]);
167
+
168
+ let named: Map<string, string> | undefined;
169
+ let legacy: Set<string> | undefined;
170
+
171
+ /** Each named reference, without its `;`, and the characters it stands for; read once. */
172
+ function namedReferences(): Map<string, string> {
173
+ named ??= new Map(
174
+ NAMED_REFERENCES.split(" ").map((entry) => {
175
+ const [name = "", points = ""] = entry.split(":");
176
+ return [
177
+ name,
178
+ String.fromCodePoint(...points.split("+").map((point) => Number.parseInt(point, 16))),
179
+ ];
180
+ }),
181
+ );
182
+ return named;
183
+ }
184
+
185
+ function legacyReferences(): Set<string> {
186
+ legacy ??= new Set(LEGACY_REFERENCES.split(" "));
187
+ return legacy;
188
+ }
package/src/core/build.ts CHANGED
@@ -1,11 +1,11 @@
1
- import { copyFileSync } from "node:fs";
1
+ import { readFileSync } from "node:fs";
2
2
  import { basename } from "node:path";
3
3
  import { loadConfig } from "./config.ts";
4
4
  import { renderDeckDocument } from "./document.ts";
5
5
  import { type DistOptions, distFile } from "./path.ts";
6
6
  import type { PlaywrightRunner } from "./playwright.ts";
7
7
  import { asResolvedDeck, type ResolvedDeck } from "./resolve.ts";
8
- import { outputPath, removeInside, writeInside } from "./safe-fs.ts";
8
+ import { removeInside, writeInside } from "./safe-fs.ts";
9
9
  import { coverShot } from "./shot/still.ts";
10
10
  import { logicalSize } from "./size.ts";
11
11
 
@@ -43,7 +43,7 @@ export async function buildDeck(
43
43
  const shot = baseUrl ? await coverShot(deck, options.runner) : undefined;
44
44
 
45
45
  if (shot) {
46
- copyFileSync(shot, outputPath(imagePath, project.root));
46
+ writeInside(imagePath, readFileSync(shot), project.root);
47
47
  } else {
48
48
  // An image from an earlier build would outlive the tag that pointed at it.
49
49
  removeInside(imagePath, project.root);
@@ -1,9 +1,52 @@
1
1
  /**
2
- * The one way dek steps through CSS text: strings and comments are opaque, and a newline ends an
3
- * unclosed string, as the CSS tokenizer reads it. Every scanner in css.ts and lint/tokens.ts is built on
4
- * these, so none of them can disagree about where a string or a block ends.
2
+ * The one way dek steps through CSS text, as the CSS tokenizer reads it: strings, comments, and
3
+ * an unquoted `url()` are opaque, CR, FF, and CRLF are newlines as LF is, and a newline ends an
4
+ * unclosed string. Every scanner in css.ts, css-transform.ts, and theme-excerpt.ts is built on
5
+ * these, so none of them can disagree about where a string or a block ends. Nothing is rewritten
6
+ * before it is read, so every index still points into the text as written.
5
7
  */
6
8
 
9
+ /** A newline as CSS preprocesses its input: LF, CR, or FF; CRLF is one, read at its CR. */
10
+ function isNewline(ch: string | undefined): boolean {
11
+ return ch === "\n" || ch === "\r" || ch === "\f";
12
+ }
13
+
14
+ function isWhitespace(ch: string | undefined): boolean {
15
+ return ch === " " || ch === "\t" || isNewline(ch);
16
+ }
17
+
18
+ /** The index just past the whitespace at `i`, taking CRLF whole. */
19
+ function whitespaceEnd(source: string, i: number, end: number): number {
20
+ return Math.min(source[i] === "\r" && source[i + 1] === "\n" ? i + 2 : i + 1, end);
21
+ }
22
+
23
+ function skipWhitespace(source: string, i: number, end: number): number {
24
+ let j = i;
25
+ while (j < end && isWhitespace(source[j])) {
26
+ j++;
27
+ }
28
+ return j;
29
+ }
30
+
31
+ /** Whether a `\` at `i` escapes what follows: anything but a newline, the end included. */
32
+ function startsEscape(source: string, i: number, end: number): boolean {
33
+ return source[i] === "\\" && (i + 1 >= end || !isNewline(source[i + 1]));
34
+ }
35
+
36
+ const HEX_RE = /[0-9a-fA-F]/;
37
+
38
+ /** The index just past the escape at `i`: one code point, or up to six hex digits and a space. */
39
+ function consumeEscape(source: string, i: number, end: number): number {
40
+ let j = i + 1;
41
+ if (j >= end || !HEX_RE.test(source[j] ?? "")) {
42
+ return Math.min(j + 1, end);
43
+ }
44
+ while (j < end && j < i + 7 && HEX_RE.test(source[j] ?? "")) {
45
+ j++;
46
+ }
47
+ return j < end && isWhitespace(source[j]) ? whitespaceEnd(source, j, end) : j;
48
+ }
49
+
7
50
  /** The index just past the string that opens at `start`, or the newline that cuts it short. */
8
51
  export function consumeString(source: string, start: number, end = source.length): number {
9
52
  const quote = source[start];
@@ -11,13 +54,16 @@ export function consumeString(source: string, start: number, end = source.length
11
54
  while (i < end) {
12
55
  const ch = source[i];
13
56
  if (ch === "\\") {
14
- i += 2;
57
+ // A `\` before a newline carries the string on to the next line.
58
+ i = startsEscape(source, i, end)
59
+ ? consumeEscape(source, i, end)
60
+ : whitespaceEnd(source, i + 1, end);
15
61
  continue;
16
62
  }
17
63
  if (ch === quote) {
18
64
  return i + 1;
19
65
  }
20
- if (ch === "\n") {
66
+ if (isNewline(ch)) {
21
67
  return i;
22
68
  }
23
69
  i++;
@@ -35,27 +81,122 @@ function isCommentStart(source: string, i: number): boolean {
35
81
  return source[i] === "/" && source[i + 1] === "*";
36
82
  }
37
83
 
84
+ const NAME_RE = /[-\w\u0080-\uffff]/;
85
+
86
+ /** A code point of a name: a letter, a digit, `-`, `_`, non-ASCII, or NUL, which CSS reads as U+FFFD. */
87
+ function isNameChar(ch: string | undefined): boolean {
88
+ return ch === "\0" || NAME_RE.test(ch ?? "");
89
+ }
90
+
91
+ /** The index just past the name at `i`: letters, digits, `-`, `_`, non-ASCII, and escapes. */
92
+ function consumeName(source: string, i: number, end: number): number {
93
+ let j = i;
94
+ while (j < end) {
95
+ if (startsEscape(source, j, end)) {
96
+ j = consumeEscape(source, j, end);
97
+ } else if (isNameChar(source[j])) {
98
+ j++;
99
+ } else {
100
+ break;
101
+ }
102
+ }
103
+ return j;
104
+ }
105
+
106
+ /** Whether a name reads `url` once its escapes are resolved, as `URL` or `u\72l` does. */
107
+ function isUrlName(name: string): boolean {
108
+ const read = name.includes("\\")
109
+ ? name.replace(/\\(?:([0-9a-fA-F]{1,6})(?:\r\n|[ \t\n\r\f])?|([\s\S]))/g, (_, hex, ch) => {
110
+ const code = hex === undefined ? -1 : Number.parseInt(hex, 16);
111
+ return code < 0 ? ch : code > 0x10ffff ? "\ufffd" : String.fromCodePoint(code);
112
+ })
113
+ : name;
114
+ return read.toLowerCase() === "url";
115
+ }
116
+
117
+ function isNonPrintable(ch: string): boolean {
118
+ const code = ch.charCodeAt(0);
119
+ // NUL is no control character here: CSS reads it as U+FFFD.
120
+ return (
121
+ (code >= 0x01 && code <= 0x08) ||
122
+ code === 0x0b ||
123
+ (code >= 0x0e && code <= 0x1f) ||
124
+ code === 0x7f
125
+ );
126
+ }
127
+
38
128
  /**
39
- * The first index from `start` whose character is one of `stops` outside strings, comments, and
40
- * `()`/`[]`; `end` when there is none. An opening brace counts only when `{` is a stop.
129
+ * The index just past an unquoted `url()` whose address starts at `start`, after its `(`; none
130
+ * when the address is quoted, which makes it a function holding a string. A broken one, with a
131
+ * space, a quote, a `(`, or a control character in its address, still runs to its `)`.
41
132
  */
42
- export function scanTopLevel(source: string, start: number, end: number, stops: string): number {
43
- let depth = 0;
44
- let i = start;
133
+ function consumeUrl(source: string, start: number, end: number): number | undefined {
134
+ let i = skipWhitespace(source, start, end);
135
+ if (i < end && (source[i] === '"' || source[i] === "'")) {
136
+ return undefined;
137
+ }
138
+ let broken = false;
45
139
  while (i < end) {
46
140
  const ch = source[i] ?? "";
47
- if (ch === '"' || ch === "'") {
48
- i = consumeString(source, i, end);
49
- continue;
141
+ if (ch === ")") {
142
+ return i + 1;
50
143
  }
51
- if (isCommentStart(source, i)) {
52
- i = consumeComment(source, i, end);
144
+ if (startsEscape(source, i, end)) {
145
+ i = consumeEscape(source, i, end);
53
146
  continue;
54
147
  }
55
- if (ch === "\\") {
56
- i += 2;
148
+ if (!broken && isWhitespace(ch)) {
149
+ i = skipWhitespace(source, i, end);
150
+ broken = i < end && source[i] !== ")";
57
151
  continue;
58
152
  }
153
+ broken ||= ch === '"' || ch === "'" || ch === "(" || ch === "\\" || isNonPrintable(ch);
154
+ i++;
155
+ }
156
+ return end;
157
+ }
158
+
159
+ /**
160
+ * The index just past the token that starts at `i`, as far as dek tells tokens apart: a string,
161
+ * a comment, an unquoted `url()`, or a name with its escapes, so the `url` of `myurl(` or
162
+ * `10url(` opens nothing. Any other code point is a token of its own. A `\` before a newline,
163
+ * which escapes nothing, takes the newline with it, so no rewrite can make an escape of the two.
164
+ */
165
+ export function consumeToken(source: string, i: number, end = source.length): number {
166
+ const ch = source[i];
167
+ if (ch === '"' || ch === "'") {
168
+ return consumeString(source, i, end);
169
+ }
170
+ if (isCommentStart(source, i)) {
171
+ return consumeComment(source, i, end);
172
+ }
173
+ if (ch === "\\" && !startsEscape(source, i, end)) {
174
+ return whitespaceEnd(source, i + 1, end);
175
+ }
176
+ if (!startsEscape(source, i, end) && !isNameChar(ch)) {
177
+ return i + 1;
178
+ }
179
+ const nameEnd = consumeName(source, i, end);
180
+ // `#url(` is a hash and `@url(` an at-rule's name, not a url().
181
+ const url =
182
+ nameEnd < end &&
183
+ source[nameEnd] === "(" &&
184
+ source[i - 1] !== "#" &&
185
+ source[i - 1] !== "@" &&
186
+ isUrlName(source.slice(i, nameEnd));
187
+ return (url && consumeUrl(source, nameEnd + 1, end)) || nameEnd;
188
+ }
189
+
190
+ /**
191
+ * The first index from `start` whose character is one of `stops` outside strings, comments,
192
+ * `url()`s, and `()`/`[]`; `end` when there is none. An opening brace counts only when `{` is a
193
+ * stop. Stops are punctuation, which no name holds.
194
+ */
195
+ export function scanTopLevel(source: string, start: number, end: number, stops: string): number {
196
+ let depth = 0;
197
+ let i = start;
198
+ while (i < end) {
199
+ const ch = source[i] ?? "";
59
200
  if (depth === 0 && stops.includes(ch)) {
60
201
  return i;
61
202
  }
@@ -64,7 +205,7 @@ export function scanTopLevel(source: string, start: number, end: number, stops:
64
205
  } else if ((ch === ")" || ch === "]") && depth > 0) {
65
206
  depth--;
66
207
  }
67
- i++;
208
+ i = consumeToken(source, i, end);
68
209
  }
69
210
  return end;
70
211
  }
@@ -88,17 +229,17 @@ export function matchBrace(source: string, open: number, end = source.length): n
88
229
  return end;
89
230
  }
90
231
 
91
- /** The text with each comment removed, strings kept byte for byte. */
232
+ /** The text with each comment removed, strings and `url()`s kept byte for byte. */
92
233
  export function stripComments(source: string): string {
93
234
  return replaceOpaque(source, { comment: () => "" });
94
235
  }
95
236
 
96
237
  /**
97
238
  * The text with each string and comment blanked to spaces, newlines kept, so only CSS syntax is
98
- * left and every offset still points where it did.
239
+ * left and every offset still points where it did. A `url()` is left as written.
99
240
  */
100
241
  export function blankStringsAndComments(source: string): string {
101
- const blank = (text: string) => text.replace(/[^\n]/g, " ");
242
+ const blank = (text: string) => text.replace(/[^\n\r\f]/g, " ");
102
243
  return replaceOpaque(source, { comment: blank, string: blank });
103
244
  }
104
245
 
@@ -110,26 +251,19 @@ function replaceOpaque(
110
251
  let from = 0;
111
252
  let i = 0;
112
253
  while (i < source.length) {
254
+ const next = consumeToken(source, i);
113
255
  const ch = source[i];
114
- if (ch === '"' || ch === "'") {
115
- const end = consumeString(source, i);
116
- if (replace.string) {
117
- out += source.slice(from, i) + replace.string(source.slice(i, end));
118
- from = end;
119
- }
120
- i = end;
121
- continue;
122
- }
123
- if (isCommentStart(source, i)) {
124
- const end = consumeComment(source, i);
125
- if (replace.comment) {
126
- out += source.slice(from, i) + replace.comment(source.slice(i, end));
127
- from = end;
128
- }
129
- i = end;
130
- continue;
256
+ const replacer =
257
+ ch === '"' || ch === "'"
258
+ ? replace.string
259
+ : isCommentStart(source, i)
260
+ ? replace.comment
261
+ : undefined;
262
+ if (replacer) {
263
+ out += source.slice(from, i) + replacer(source.slice(i, next));
264
+ from = next;
131
265
  }
132
- i += ch === "\\" ? 2 : 1;
266
+ i = next;
133
267
  }
134
268
  return out + source.slice(from);
135
269
  }
@@ -1,5 +1,5 @@
1
1
  import { outermostStyleRules, type Stylesheet, splitSelectorList, startsAtSlide } from "./css.ts";
2
- import { consumeComment, consumeString, cssIdents } from "./css-scan.ts";
2
+ import { consumeComment, consumeToken, cssIdents } from "./css-scan.ts";
3
3
 
4
4
  /** Text to put in place of `[start, end)` of the stylesheet as it was read. */
5
5
  type CssEdit = { start: number; end: number; text: string };
@@ -108,32 +108,78 @@ export function replaceUrls(replace: (value: string) => string | undefined): Css
108
108
 
109
109
  /** Whitespace as CSS defines it. U+3000 and NBSP are content, not whitespace. */
110
110
  const CSS_WHITESPACE = new Set([" ", "\t", "\n", "\r", "\f"]);
111
+ const CSS_NEWLINES = new Set(["\n", "\r", "\f"]);
112
+
113
+ /** A token that runs on into the next with nothing between: a name, a number, or `#@.+/`. */
114
+ const RUNS_ON_RE = /^[-\w\u0080-\uffff\0\\#@.+/]/;
115
+ /** What such a token runs on into: a name, a number, `(`, `%`, or the `*` that opens a comment. */
116
+ const RUNS_INTO_RE = /^[-\w\u0080-\uffff\0\\.+(%*]/;
111
117
 
112
118
  /**
113
- * Drops comments and collapses whitespace to one space, leaving strings byte for byte, so
114
- * `content: "a b"` or `" "` renders in the build as it does on the dev server.
119
+ * Whether the token `last` and the one that starts with `next` would read as one with nothing
120
+ * between them: `x` and `url(` as `xurl(`, `/` and `*` as a comment, or `--` and `>`, `<` and
121
+ * `!`, `!` and `--` as the `-->` and `<!--` a stylesheet skips.
122
+ */
123
+ function runTogether(last: string, next: string): boolean {
124
+ return (
125
+ (RUNS_ON_RE.test(last) && RUNS_INTO_RE.test(next)) ||
126
+ (last.endsWith("--") && next === ">") ||
127
+ (last === "<" && next === "!") ||
128
+ (last === "!" && next === "-")
129
+ );
130
+ }
131
+
132
+ /** A hex escape at the end of a token, which takes one whitespace after it as its own. */
133
+ const HEX_ESCAPE_END_RE = /\\[0-9a-fA-F]{1,6}$/;
134
+
135
+ /**
136
+ * Drops comments and collapses whitespace to one space, leaving strings and `url()`s byte for
137
+ * byte, so `content: "a b"` or `" "` renders in the build as it does on the dev server. The
138
+ * result reads as the source does: a newline after a string stays one, since it is what ends a
139
+ * string cut short, and a comment between two tokens that would run into one, as `x` and `url(`
140
+ * into `xurl(`, stays as an empty one, since a space would make `div` and `p` two selectors. A
141
+ * hex escape that a comment ends, such as `\41` before a comment and ` x`, is followed by two
142
+ * spaces, since it takes one as its own.
115
143
  */
116
144
  export function minifyCss(css: string): string {
117
145
  let out = "";
118
- let space = false;
146
+ let last = "";
147
+ // What parts the last token written from the next: "", "comment", a space, or the newline that
148
+ // ends a string.
149
+ let gap = "";
119
150
  let i = 0;
120
151
  while (i < css.length) {
121
152
  const ch = css[i] ?? "";
122
153
  if (ch === "/" && css[i + 1] === "*") {
123
154
  i = consumeComment(css, i);
155
+ gap ||= "comment";
124
156
  continue;
125
157
  }
126
158
  if (CSS_WHITESPACE.has(ch)) {
127
- space = true;
128
- i++;
159
+ const whitespace = ch === "\r" && css[i + 1] === "\n" ? "\r\n" : ch;
160
+ if (gap === "" && CSS_NEWLINES.has(ch) && (last[0] === '"' || last[0] === "'")) {
161
+ // One LF, unless the string ends on a CR it escapes, which an LF would join into a CRLF.
162
+ gap = last.endsWith("\r") ? whitespace : "\n";
163
+ } else if (gap === "" || gap === "comment") {
164
+ gap = " ";
165
+ }
166
+ i += whitespace.length;
129
167
  continue;
130
168
  }
131
- if (space && out !== "") {
132
- out += " ";
169
+ if (out !== "") {
170
+ out +=
171
+ gap === "comment"
172
+ ? runTogether(last, ch)
173
+ ? "/**/"
174
+ : ""
175
+ : gap === " " && HEX_ESCAPE_END_RE.test(last)
176
+ ? " "
177
+ : gap;
133
178
  }
134
- space = false;
135
- const end = ch === '"' || ch === "'" ? consumeString(css, i) : ch === "\\" ? i + 2 : i + 1;
136
- out += css.slice(i, end);
179
+ gap = "";
180
+ const end = consumeToken(css, i);
181
+ last = css.slice(i, end);
182
+ out += last;
137
183
  i = end;
138
184
  }
139
185
  return out;
package/src/core/css.ts CHANGED
@@ -2,6 +2,7 @@ import {
2
2
  blankStringsAndComments,
3
3
  consumeComment,
4
4
  consumeString,
5
+ consumeToken,
5
6
  matchBrace,
6
7
  scanTopLevel,
7
8
  splitTopLevel,
@@ -131,16 +132,11 @@ class SheetReader {
131
132
  const { source } = this;
132
133
  let i = 0;
133
134
  while (i < source.length) {
134
- const ch = source[i];
135
- if (ch === '"' || ch === "'") {
136
- i = consumeString(source, i);
137
- } else if (ch === "/" && source[i + 1] === "*") {
138
- const close = consumeComment(source, i);
139
- this.comments.push([i, close]);
140
- i = close;
141
- } else {
142
- i += ch === "\\" ? 2 : 1;
135
+ const next = consumeToken(source, i);
136
+ if (source[i] === "/" && source[i + 1] === "*") {
137
+ this.comments.push([i, next]);
143
138
  }
139
+ i = next;
144
140
  }
145
141
  const locate = lineLocator(sheet.source);
146
142
  this.lineOf = (offset) => locate(offset).line;
@@ -181,13 +177,23 @@ class SheetReader {
181
177
  return i;
182
178
  }
183
179
 
184
- /** A prelude's span with its trailing spaces trimmed off. */
180
+ /**
181
+ * A prelude's span with the spaces and comments at its end trimmed off; a string it ends on,
182
+ * such as the name of `@keyframes "pop"`, stays.
183
+ */
185
184
  trimEnd(start: number, end: number): number {
186
185
  let j = end;
187
- while (j > start && WHITESPACE_RE.test(this.blank[j - 1] ?? "")) {
188
- j--;
186
+ while (j > start) {
187
+ const comment = this.comments.find(([, close]) => close === j);
188
+ if (comment) {
189
+ j = comment[0];
190
+ } else if (WHITESPACE_RE.test(this.source[j - 1] ?? "")) {
191
+ j--;
192
+ } else {
193
+ break;
194
+ }
189
195
  }
190
- return j;
196
+ return Math.max(j, start);
191
197
  }
192
198
 
193
199
  atRule(start: number, end: number, scope: Scope): number {