@kosuke-ai/kosuke 1.0.81 → 1.0.83

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 (33) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/generated/commands/crons/create--personal.js +1 -1
  3. package/dist/generated/commands/crons/update--personal.js +1 -1
  4. package/dist/generated/commands/index.js +124 -118
  5. package/dist/generated/commands/projects/batch-merging-members-delete.js +7 -0
  6. package/dist/generated/commands/prototypes/create.js +32 -0
  7. package/dist/generated/commands/providers/default-model-set--personal.js +2 -9
  8. package/dist/generated/commands/providers/get--personal.js +1 -1
  9. package/dist/generated/commands/sensei/reels-activity-list.js +1 -1
  10. package/dist/generated/commands/sensei/reels-later-holds-create.js +43 -0
  11. package/dist/generated/commands/sensei/reels-later-holds-delete.js +29 -0
  12. package/dist/generated/commands/sensei/reels-later-holds-list.js +17 -0
  13. package/dist/generated/commands/sensei/widgets-get.js +1 -1
  14. package/dist/generated/commands/sessions/create.js +0 -14
  15. package/dist/generated/commands/sessions/prompt-update.js +0 -11
  16. package/dist/generated/commands/sessions/send.js +0 -18
  17. package/dist/generated/commands/sessions/update.js +3 -10
  18. package/dist/generated/commands/tasks/create--personal.js +0 -14
  19. package/dist/generated/commands/tasks/create.js +0 -14
  20. package/dist/generated/commands/tasks/update--personal.js +2 -9
  21. package/dist/generated/commands/tasks/update.js +2 -9
  22. package/dist/runtime/arguments.js +2 -0
  23. package/dist/runtime/attach.js +6 -12
  24. package/dist/runtime/option-parsers.js +14 -0
  25. package/dist/runtime/prototype-create.js +47 -0
  26. package/dist/runtime/prototype-styles-scope.js +342 -0
  27. package/dist/runtime/prototype-styles.js +166 -0
  28. package/dist/runtime/prototype-visual-browser.js +87 -0
  29. package/dist/runtime/prototype-visual-check.js +388 -0
  30. package/dist/runtime/prototype-visual-preview.js +159 -0
  31. package/dist/runtime/prototype-visual-scripts.js +174 -0
  32. package/openapi.json +237 -88
  33. package/package.json +5 -6
@@ -27,13 +27,6 @@ export const operation = {
27
27
  "required": false,
28
28
  "description": "A model, or kosuke-free for personal work. Workspace tasks never use Sensei free."
29
29
  },
30
- {
31
- "name": "auto",
32
- "flag": "auto",
33
- "kind": "boolean",
34
- "required": false,
35
- "description": "True starts the session on Auto: the platform picks the Model and Provider of each Turn. False keeps it off. Absent follows your Default Model."
36
- },
37
30
  {
38
31
  "name": "kosukeFree",
39
32
  "flag": "kosuke-free",
@@ -172,13 +165,6 @@ export const operation = {
172
165
  "required": false,
173
166
  "description": "A model, or kosuke-free for personal work. Workspace tasks never use Sensei free."
174
167
  },
175
- {
176
- "name": "auto",
177
- "flag": "auto",
178
- "kind": "boolean",
179
- "required": false,
180
- "description": "True starts the session on Auto: the platform picks the Model and Provider of each Turn. False keeps it off. Absent follows your Default Model."
181
- },
182
168
  {
183
169
  "name": "kosukeFree",
184
170
  "flag": "kosuke-free",
@@ -25,13 +25,6 @@ export const operation = {
25
25
  "required": false,
26
26
  "description": "A model, or kosuke-free for personal work. Workspace tasks never use Sensei free."
27
27
  },
28
- {
29
- "name": "auto",
30
- "flag": "auto",
31
- "kind": "boolean",
32
- "required": false,
33
- "description": "True starts the session on Auto: the platform picks the Model and Provider of each Turn. False keeps it off. Absent follows your Default Model."
34
- },
35
28
  {
36
29
  "name": "kosukeFree",
37
30
  "flag": "kosuke-free",
@@ -170,13 +163,6 @@ export const operation = {
170
163
  "required": false,
171
164
  "description": "A model, or kosuke-free for personal work. Workspace tasks never use Sensei free."
172
165
  },
173
- {
174
- "name": "auto",
175
- "flag": "auto",
176
- "kind": "boolean",
177
- "required": false,
178
- "description": "True starts the session on Auto: the platform picks the Model and Provider of each Turn. False keeps it off. Absent follows your Default Model."
179
- },
180
166
  {
181
167
  "name": "kosukeFree",
182
168
  "flag": "kosuke-free",
@@ -35,13 +35,6 @@ export const operation = {
35
35
  "required": false,
36
36
  "description": "A model, or kosuke-free for personal work. Workspace tasks never use Sensei free."
37
37
  },
38
- {
39
- "name": "auto",
40
- "flag": "auto",
41
- "kind": "boolean",
42
- "required": false,
43
- "description": "True puts the session on Auto, from its next Turn. False takes it off; send it with model when choosing a Model. Absent leaves it as it is."
44
- },
45
38
  {
46
39
  "name": "kosukeFree",
47
40
  "flag": "kosuke-free",
@@ -54,8 +47,8 @@ export const operation = {
54
47
  "flag": "next-turn",
55
48
  "kind": "json",
56
49
  "required": false,
57
- "description": "Active or Under review only: the Model, Auto, or {kosukeFree:true} in personal scope, the session's next Turn runs on, whether or not a Turn is running now. The next Turn applies it once and clears it. null, or the Model and Auto state the session already has, clears it. Send it on its own.",
58
- "shape": "{model: string} | {auto: boolean} | {kosukeFree: boolean} | null"
50
+ "description": "Active or Under review only: the Model or {kosukeFree:true} in personal scope, the session's next Turn runs on, whether or not a Turn is running now. The next Turn applies it once and clears it. null, or the Model and source the session already has, clears it. Send it on its own.",
51
+ "shape": "{model: string} | {kosukeFree: boolean} | null"
59
52
  },
60
53
  {
61
54
  "name": "ownerId",
@@ -32,13 +32,6 @@ export const operation = {
32
32
  "required": false,
33
33
  "description": "A model, or kosuke-free for personal work. Workspace tasks never use Sensei free."
34
34
  },
35
- {
36
- "name": "auto",
37
- "flag": "auto",
38
- "kind": "boolean",
39
- "required": false,
40
- "description": "True puts the session on Auto, from its next Turn. False takes it off; send it with model when choosing a Model. Absent leaves it as it is."
41
- },
42
35
  {
43
36
  "name": "kosukeFree",
44
37
  "flag": "kosuke-free",
@@ -51,8 +44,8 @@ export const operation = {
51
44
  "flag": "next-turn",
52
45
  "kind": "json",
53
46
  "required": false,
54
- "description": "Active or Under review only: the Model, Auto, or {kosukeFree:true} in personal scope, the session's next Turn runs on, whether or not a Turn is running now. The next Turn applies it once and clears it. null, or the Model and Auto state the session already has, clears it. Send it on its own.",
55
- "shape": "{model: string} | {auto: boolean} | {kosukeFree: boolean} | null"
47
+ "description": "Active or Under review only: the Model or {kosukeFree:true} in personal scope, the session's next Turn runs on, whether or not a Turn is running now. The next Turn applies it once and clears it. null, or the Model and source the session already has, clears it. Send it on its own.",
48
+ "shape": "{model: string} | {kosukeFree: boolean} | null"
56
49
  },
57
50
  {
58
51
  "name": "ownerId",
@@ -31,6 +31,8 @@ export const CLI_ONLY_FLAGS = {
31
31
  'crons list': ['--all'],
32
32
  'activity list': ['--all'],
33
33
  'sensei threads list': ['--all'],
34
+ // Read by `./prototype-create.ts` before it sends; a flag with `<value>` takes one.
35
+ 'prototypes create': ['--project-dir <path>', '--preview-url <url>', '--skip-visual-check'],
34
36
  };
35
37
  export const SESSION_ID_FLAG = 'session-id';
36
38
  function fieldsOf(form) {
@@ -3,11 +3,13 @@ import { Argument, Command, InvalidArgumentError, Option } from 'commander';
3
3
  import { addsSessionIdFlag, CLI_ONLY_FLAGS, omitsProject, SESSION_ID_FLAG, sessionIdField, } from './arguments.js';
4
4
  import { setAfterHelp, setOptionShape, shortSummary, usageError } from './help.js';
5
5
  import { buildRequest, execute, readWholeBody, UsageError } from './invoke.js';
6
+ import { collect, jsonParser } from './option-parsers.js';
6
7
  import { withMemberTimeZone } from './member-time-zone.js';
7
8
  import { isOwnerRepo, ownerRepoParser } from './owner-repo.js';
8
9
  import { PERSONAL_SPACE_PARAM } from './personal-space.js';
9
10
  import { refusedBeforeSending } from './prototype-check.js';
10
11
  import { personalSpaceId } from './personal-space-id.js';
12
+ import { PROTOTYPE_CREATE_HELP, prepareOperationInput } from './prototype-create.js';
11
13
  import { threadView, TOOLS_FLAG_HELP } from './thread-text.js';
12
14
  import { fieldsOf, formLabel, formUsage, leafShape, pathParamsFor, PERSONAL, scopeOf, selectForm, } from './variants.js';
13
15
  /**
@@ -117,7 +119,9 @@ const ALL_FLAG_HELP = 'Every row, as a list prints now. Scripts pass it to stay
117
119
  function addCliOnlyOptions(leaf, operation) {
118
120
  const command = operation.command.join(' ');
119
121
  for (const flag of CLI_ONLY_FLAGS[command] ?? []) {
120
- leaf.addOption(new Option(flag, VIEWS[command]?.flags[flag] ?? (flag === '--all' ? ALL_FLAG_HELP : '')));
122
+ leaf.addOption(new Option(flag, VIEWS[command]?.flags[flag] ??
123
+ PROTOTYPE_CREATE_HELP[flag] ??
124
+ (flag === '--all' ? ALL_FLAG_HELP : '')));
121
125
  }
122
126
  }
123
127
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -314,6 +318,7 @@ function attachForms(root, forms, runtime, reachable) {
314
318
  }
315
319
  /** Build, send and print; a usage error is commander's, so it prints as one. */
316
320
  async function run(leaf, runtime, operation, input, options = {}) {
321
+ input = await prepareOperationInput(runtime, operation, input, options);
317
322
  let request;
318
323
  try {
319
324
  request = buildRequest(operation, input);
@@ -515,17 +520,6 @@ function readFieldFile(path) {
515
520
  throw new UsageError(`Could not read ${path}: ${error instanceof Error ? error.message : String(error)}`);
516
521
  }
517
522
  }
518
- function jsonParser(raw) {
519
- try {
520
- return JSON.parse(raw);
521
- }
522
- catch {
523
- throw new InvalidArgumentError('Expected JSON.');
524
- }
525
- }
526
- function collect(value, previous) {
527
- return [...(previous ?? []), value];
528
- }
529
523
  /**
530
524
  * commander stores `--exclude-archived` as `excludeArchived`.
531
525
  * @internal
@@ -0,0 +1,14 @@
1
+ import { InvalidArgumentError } from 'commander';
2
+ /** A JSON flag's value, or commander's usage error. */
3
+ export function jsonParser(raw) {
4
+ try {
5
+ return JSON.parse(raw);
6
+ }
7
+ catch {
8
+ throw new InvalidArgumentError('Expected JSON.');
9
+ }
10
+ }
11
+ /** A repeated flag's values, in the order given. */
12
+ export function collect(value, previous) {
13
+ return [...(previous ?? []), value];
14
+ }
@@ -0,0 +1,47 @@
1
+ import { buildPrototypeStyles } from './prototype-styles.js';
2
+ import { runVisualCheck } from './prototype-visual-check.js';
3
+ /** The command this prepares; every other command passes through unchanged. */
4
+ const COMMAND = 'prototypes create';
5
+ /** The help of its CLI-only flags (`CLI_ONLY_FLAGS` in `./arguments.ts`), read here and never sent. */
6
+ export const PROTOTYPE_CREATE_HELP = {
7
+ '--project-dir <path>': "The project's clone, whose Tailwind entry the styles are built from. Default: the nearest folder up from here with a package.json that depends on tailwindcss.",
8
+ '--preview-url <url>': "The running app's address the baseline state is compared with. Default: this session's app preview.",
9
+ '--skip-visual-check': 'Skip the comparison with the real screen; the save says not compared.',
10
+ };
11
+ /**
12
+ * Before `kosuke prototypes create` sends its three files, where the project's clone is:
13
+ * 1. builds CSS from the project's own Tailwind entry for the class names content.js uses, and
14
+ * sends it as `generatedStyles` (`./prototype-styles.ts`);
15
+ * 2. when prototype.json declares a `baseline` and a browser and the app preview are reachable,
16
+ * renders the page without saving it (`dryRun`), screenshots its baseline state and the real
17
+ * screen at the same width and theme, and sends the result as `visualCheck`
18
+ * (`./prototype-visual-check.ts`).
19
+ * Notices go to stderr; the answer stays the server's.
20
+ */
21
+ export async function prepareOperationInput(runtime, operation, input, options) {
22
+ if (operation.command.join(' ') !== COMMAND || input.wholeBody !== undefined)
23
+ return input;
24
+ const styles = await buildPrototypeStyles({
25
+ attachments: input.attachments,
26
+ projectDir: typeof options.projectDir === 'string' ? options.projectDir : undefined,
27
+ });
28
+ if (styles.notice)
29
+ runtime.notice?.(styles.notice);
30
+ let fields = { ...input.fields };
31
+ if (styles.css)
32
+ fields.generatedStyles = styles.css;
33
+ // A dry run saves nothing, so it publishes no comparison picture either.
34
+ if (options.skipVisualCheck !== true && fields.dryRun !== 'true') {
35
+ const check = await runVisualCheck({
36
+ runtime,
37
+ operation,
38
+ input: { ...input, fields },
39
+ previewUrl: typeof options.previewUrl === 'string' ? options.previewUrl : undefined,
40
+ });
41
+ if (check.notice)
42
+ runtime.notice?.(check.notice);
43
+ if (check.result)
44
+ fields = { ...fields, visualCheck: JSON.stringify(check.result) };
45
+ }
46
+ return { ...input, fields };
47
+ }
@@ -0,0 +1,342 @@
1
+ /**
2
+ * Scopes a Tailwind build to a prototype's canvas: the page root becomes `.pt-canvas`, the dark
3
+ * theme `.pt-canvas.dark`, every other selector a descendant of the canvas, and `@media` width
4
+ * rules `@container canvas` rules, so the Device control applies them. What could load, leak out
5
+ * of the canvas or the server refuses is dropped, as are the entry's plain rules for classes the
6
+ * prototype never names. The result passes the server's `generatedStyleIssues`
7
+ * (src/lib/prototypes/content-checks.ts).
8
+ */
9
+ const CANVAS = '.pt-canvas';
10
+ /** At-rules whose body is a list of rules, kept and scoped. */
11
+ const GROUPS = new Set(['layer', 'media', 'supports', 'container', 'starting-style']);
12
+ /** At-rules whose body holds descriptors or keyframe steps, kept as written. */
13
+ const OPAQUE = new Set(['keyframes', '-webkit-keyframes', 'property', 'font-face']);
14
+ const EXTERNAL_URL = /url\(\s*(?!["']?\s*data:)/i;
15
+ const REFUSED_TEXT = /<\/style|--pt-/i;
16
+ /** The `@media` features the server refuses: the canvas, not the window, sets them. */
17
+ const SIZE_FEATURE = /\b(?:min-|max-)?(?:width|height|aspect-ratio|orientation)\b/i;
18
+ /** Splits `css` into its top-level statements and blocks, strings and brackets kept whole. */
19
+ function parse(css) {
20
+ const nodes = [];
21
+ let index = 0;
22
+ while (index < css.length) {
23
+ let cursor = index;
24
+ let quote = null;
25
+ let parens = 0;
26
+ for (; cursor < css.length; cursor++) {
27
+ const char = css[cursor];
28
+ if (quote) {
29
+ if (char === '\\')
30
+ cursor++;
31
+ else if (char === quote)
32
+ quote = null;
33
+ }
34
+ else if (char === '"' || char === "'")
35
+ quote = char;
36
+ else if (char === '(')
37
+ parens++;
38
+ else if (char === ')')
39
+ parens--;
40
+ else if (char === '{' || char === '}' || (char === ';' && parens <= 0))
41
+ break;
42
+ }
43
+ const prelude = css.slice(index, cursor).trim();
44
+ if (cursor >= css.length || css[cursor] === '}') {
45
+ // A rule's last declaration may go without its semicolon; past a stray close nothing more
46
+ // can be read safely.
47
+ if (cursor >= css.length && prelude)
48
+ nodes.push({ kind: 'statement', text: prelude });
49
+ return nodes;
50
+ }
51
+ if (css[cursor] === ';') {
52
+ if (prelude)
53
+ nodes.push({ kind: 'statement', text: prelude });
54
+ index = cursor + 1;
55
+ continue;
56
+ }
57
+ let depth = 1;
58
+ let end = cursor + 1;
59
+ quote = null;
60
+ for (; end < css.length && depth > 0; end++) {
61
+ const char = css[end];
62
+ if (quote) {
63
+ if (char === '\\')
64
+ end++;
65
+ else if (char === quote)
66
+ quote = null;
67
+ }
68
+ else if (char === '"' || char === "'")
69
+ quote = char;
70
+ else if (char === '{')
71
+ depth++;
72
+ else if (char === '}')
73
+ depth--;
74
+ }
75
+ if (depth > 0)
76
+ return nodes;
77
+ nodes.push({ kind: 'rule', prelude, body: css.slice(cursor + 1, end - 1) });
78
+ index = end;
79
+ }
80
+ return nodes;
81
+ }
82
+ /** Splits at the top-level occurrences of `separator`, outside strings, brackets and parens. */
83
+ function splitTop(text, separator) {
84
+ const parts = [];
85
+ let depth = 0;
86
+ let quote = null;
87
+ let start = 0;
88
+ for (let index = 0; index < text.length; index++) {
89
+ const char = text[index];
90
+ if (quote) {
91
+ if (char === '\\')
92
+ index++;
93
+ else if (char === quote)
94
+ quote = null;
95
+ }
96
+ else if (char === '"' || char === "'")
97
+ quote = char;
98
+ else if (char === '(' || char === '[')
99
+ depth++;
100
+ else if (char === ')' || char === ']')
101
+ depth--;
102
+ else if (char === separator && depth === 0) {
103
+ parts.push(text.slice(start, index));
104
+ start = index + 1;
105
+ }
106
+ }
107
+ parts.push(text.slice(start));
108
+ return parts.map((part) => part.trim()).filter(Boolean);
109
+ }
110
+ function stripComments(css) {
111
+ let out = '';
112
+ let quote = null;
113
+ for (let index = 0; index < css.length; index++) {
114
+ const char = css[index];
115
+ if (quote) {
116
+ out += char;
117
+ if (char === '\\')
118
+ out += css[++index] ?? '';
119
+ else if (char === quote)
120
+ quote = null;
121
+ }
122
+ else if (char === '/' && css[index + 1] === '*') {
123
+ const close = css.indexOf('*/', index + 2);
124
+ if (close < 0)
125
+ break;
126
+ index = close + 1;
127
+ }
128
+ else {
129
+ if (char === '"' || char === "'")
130
+ quote = char;
131
+ out += char;
132
+ }
133
+ }
134
+ return out;
135
+ }
136
+ const squash = (text) => text.replace(/\s+/g, ' ').trim();
137
+ /** The compound selectors of `selector` at its top level, with the combinators between them. */
138
+ function compounds(selector) {
139
+ const parts = [];
140
+ let depth = 0;
141
+ let quote = null;
142
+ let current = '';
143
+ for (let index = 0; index < selector.length; index++) {
144
+ const char = selector[index];
145
+ if (quote) {
146
+ current += char;
147
+ if (char === '\\')
148
+ current += selector[++index] ?? '';
149
+ else if (char === quote)
150
+ quote = null;
151
+ continue;
152
+ }
153
+ if (char === '\\') {
154
+ current += char + (selector[++index] ?? '');
155
+ continue;
156
+ }
157
+ if (char === '"' || char === "'")
158
+ quote = char;
159
+ else if (char === '(' || char === '[')
160
+ depth++;
161
+ else if (char === ')' || char === ']')
162
+ depth--;
163
+ else if (depth === 0 && /[\s>+~]/.test(char)) {
164
+ if (current)
165
+ parts.push(current);
166
+ current = '';
167
+ continue;
168
+ }
169
+ current += char;
170
+ }
171
+ if (current)
172
+ parts.push(current);
173
+ return parts;
174
+ }
175
+ const unescapeIdent = (ident) => ident.replace(/\\([0-9a-f]{1,6}\s?|[\s\S])/gi, (_, escaped) => /^[0-9a-f]{1,6}\s?$/i.test(escaped)
176
+ ? String.fromCodePoint(parseInt(escaped.trim(), 16))
177
+ : escaped);
178
+ /** The class names a selector names, anywhere in it, unescaped. */
179
+ function classNames(selector) {
180
+ const withoutStrings = selector.replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/g, '""');
181
+ return [
182
+ ...withoutStrings.matchAll(/\.((?:[\w-]|\\[0-9a-f]{1,6}\s?|\\[\s\S]|[^\x00-\x7f])+)/gi),
183
+ ].map((match) => unescapeIdent(match[1]));
184
+ }
185
+ const ROOT_COMPOUND = /^(?::root|:host|html|body)(?![\w-]|\()/i;
186
+ const ROOT_PSEUDO = /:(?:root|host)(?![\w-])/i;
187
+ const DARK_COMPOUND = /^\.dark(?![\w-]|\\)/;
188
+ /** Whether the server reads `selector` as inside the canvas (content-checks.ts `styleIssues`). */
189
+ const staysInCanvas = (selector) => /^\.pt-canvas(?![\w-])/.test(selector) &&
190
+ !/^\.pt-canvas(?:[.:#[][^\s>~+]*)?\s*[~+]/.test(selector);
191
+ /** `selector` on the canvas: none when it cannot be, two for a leading `.dark` theme class. */
192
+ function scopeSelector(selector) {
193
+ if (/^\.pt-canvas(?![\w-])/.test(selector))
194
+ return [selector];
195
+ const [first, ...rest] = compounds(selector);
196
+ if (!first)
197
+ return [];
198
+ const restText = selector.slice(selector.indexOf(first) + first.length);
199
+ // The page root, later in a selector (`html body`, `[dir] :root`), has no place in the canvas.
200
+ if (rest.some((part) => /^(?:html|body)(?![\w-])/i.test(part) || ROOT_PSEUDO.test(part)))
201
+ return [];
202
+ const root = first.match(ROOT_COMPOUND);
203
+ if (root)
204
+ return [`${CANVAS}${first.slice(root[0].length)}${restText}`];
205
+ // The dark theme is a class on the canvas (`pt-canvas dark`), or on a part inside it.
206
+ if (DARK_COMPOUND.test(first))
207
+ return [`${CANVAS}${selector}`, `${CANVAS} ${selector}`];
208
+ return [`${CANVAS} ${selector}`];
209
+ }
210
+ /** A rule's declarations without those that load, set the shell tokens or close the style. */
211
+ function cleanDeclarations(body) {
212
+ const kept = splitTop(body, ';')
213
+ .filter((declaration) => !EXTERNAL_URL.test(declaration) && !REFUSED_TEXT.test(declaration))
214
+ .map((declaration) => declaration.replace(/\s*\n\s*/g, ' '));
215
+ return kept.length ? kept.join(';') : null;
216
+ }
217
+ /** `@media` queries on the window's width as `@container canvas` ones; null when they cannot be. */
218
+ function mediaToContainer(query) {
219
+ const parts = splitTop(query, ',').map((part) => part.replace(/^(?:only\s+)?(?:screen|all)\s+and\s+/i, '').trim());
220
+ const conditions = [];
221
+ for (const part of parts) {
222
+ const features = part.split(/\s+and\s+/i);
223
+ const widthOnly = features.every((feature) => /^\(\s*(?:(?:min-|max-)?width\s*:[^()]*|[^()]*\bwidth\s*[<>=][^()]*)\)$/i.test(feature));
224
+ if (!widthOnly)
225
+ return null;
226
+ conditions.push(features.length > 1 && parts.length > 1 ? `(${part})` : part);
227
+ }
228
+ return conditions.length ? `canvas ${conditions.join(' or ')}` : null;
229
+ }
230
+ /**
231
+ * A style rule with nested blocks, flat: its own declarations, then each nested at-rule around
232
+ * the rule's selector and each nested rule with its selector resolved, in order, so the
233
+ * cascade is unchanged. Tailwind nests its `@supports` colour fallbacks this way.
234
+ */
235
+ function flattenRule(prelude, body) {
236
+ const items = parse(body);
237
+ const declarations = items.flatMap((item) => (item.kind === 'statement' ? [item.text] : []));
238
+ const parents = splitTop(prelude, ',');
239
+ const nodes = declarations.length
240
+ ? [{ kind: 'rule', prelude, body: declarations.join(';') }]
241
+ : [];
242
+ for (const item of items) {
243
+ if (item.kind !== 'rule')
244
+ continue;
245
+ if (item.prelude.startsWith('@'))
246
+ nodes.push({ kind: 'rule', prelude: item.prelude, body: `${prelude}{${item.body}}` });
247
+ else {
248
+ const selectors = splitTop(item.prelude, ',').flatMap((child) => parents.map((parent) => child.includes('&') ? child.replaceAll('&', `:is(${parent})`) : `${parent} ${child}`));
249
+ nodes.push(...flattenRule(selectors.join(','), item.body));
250
+ }
251
+ }
252
+ return nodes;
253
+ }
254
+ function scopeNodes(nodes, scope) {
255
+ const out = [];
256
+ for (const node of nodes) {
257
+ if (node.kind === 'statement') {
258
+ // Only the layer order statement stays; @import, @charset, @source and the like go.
259
+ if (/^@layer\s+[\w-]+(?:\s*,\s*[\w-]+)*$/i.test(node.text))
260
+ out.push(`${squash(node.text)};`);
261
+ continue;
262
+ }
263
+ const { prelude, body } = node;
264
+ if (prelude.startsWith('@')) {
265
+ const name = prelude
266
+ .slice(1)
267
+ .split(/[\s({]/)[0]
268
+ .toLowerCase();
269
+ const params = prelude.slice(name.length + 1).trim();
270
+ if (OPAQUE.has(name)) {
271
+ if (EXTERNAL_URL.test(prelude + body) || REFUSED_TEXT.test(prelude + body))
272
+ continue;
273
+ out.push(`${squash(prelude)}{${squash(body)}}`);
274
+ continue;
275
+ }
276
+ if (!GROUPS.has(name))
277
+ continue;
278
+ let head = squash(prelude);
279
+ if (name === 'media') {
280
+ if (/^(?:only\s+)?print\b/i.test(params))
281
+ continue;
282
+ if (SIZE_FEATURE.test(params)) {
283
+ const container = mediaToContainer(params);
284
+ if (!container)
285
+ continue;
286
+ head = `@container ${container}`;
287
+ }
288
+ }
289
+ if (EXTERNAL_URL.test(head) || REFUSED_TEXT.test(head))
290
+ continue;
291
+ const inner = scopeNodes(parse(body), {
292
+ ...scope,
293
+ utilities: scope.utilities || (name === 'layer' && params === 'utilities'),
294
+ });
295
+ if (inner.length)
296
+ out.push(`${head}{${inner.join('')}}`);
297
+ continue;
298
+ }
299
+ if (body.includes('{')) {
300
+ out.push(...scopeNodes(flattenRule(prelude, body), scope));
301
+ continue;
302
+ }
303
+ const declarations = cleanDeclarations(body);
304
+ if (!declarations)
305
+ continue;
306
+ const selectors = new Set();
307
+ for (const selector of splitTop(squash(prelude), ',')) {
308
+ if (REFUSED_TEXT.test(selector))
309
+ continue;
310
+ if (!scope.utilities &&
311
+ classNames(selector).some((name) => name !== 'dark' && !scope.known.has(name)))
312
+ continue;
313
+ for (const scoped of scopeSelector(selector))
314
+ if (staysInCanvas(scoped))
315
+ selectors.add(scoped);
316
+ }
317
+ if (selectors.size)
318
+ out.push(`${[...selectors].join(',')}{${declarations}}`);
319
+ }
320
+ return out;
321
+ }
322
+ /** Drops the top-level `@keyframes` that nothing kept names. */
323
+ function dropUnusedKeyframes(blocks) {
324
+ const keyframes = /^@(?:-webkit-)?keyframes\s+([^\s{]+)/i;
325
+ const used = blocks.filter((block) => !keyframes.test(block)).join('\n');
326
+ return blocks.filter((block) => {
327
+ const name = block.match(keyframes)?.[1]?.replace(/^["']|["']$/g, '');
328
+ if (!name)
329
+ return true;
330
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
331
+ return new RegExp(`(?:^|[^\\w-])${escaped}(?![\\w-])`).test(used);
332
+ });
333
+ }
334
+ /**
335
+ * The CSS of a Tailwind build, scoped to the canvas, with only the entry's plain rules whose
336
+ * classes are all among `candidates` (the class-like tokens of content.js).
337
+ */
338
+ export function scopeToCanvas(css, candidates) {
339
+ const known = new Set(candidates);
340
+ const blocks = scopeNodes(parse(stripComments(css)), { known, utilities: false });
341
+ return dropUnusedKeyframes(blocks).join('\n') + '\n';
342
+ }