pi-pocket 0.26.0 → 0.27.0-beta.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.
Files changed (186) hide show
  1. package/CONTRIBUTING.md +1 -1
  2. package/docs/design/design-system.md +165 -0
  3. package/docs/design/ds-notes-b.md +61 -0
  4. package/docs/design/ds-notes-g.md +170 -0
  5. package/docs/design/ds-notes-t.md +303 -0
  6. package/docs/design/ds-notes-u.md +220 -0
  7. package/docs/design/ds-notes-v.md +186 -0
  8. package/docs/design/ds-rounds.md +160 -0
  9. package/docs/design/ds-u-bridge.patch +732 -0
  10. package/docs/examples/design-system/README.md +15 -0
  11. package/docs/examples/design-system/pocket/.pi/design/components/badge.html +112 -0
  12. package/docs/examples/design-system/pocket/.pi/design/components/button.html +203 -0
  13. package/docs/examples/design-system/pocket/.pi/design/components/card.html +125 -0
  14. package/docs/examples/design-system/pocket/.pi/design/components/code-block.html +155 -0
  15. package/docs/examples/design-system/pocket/.pi/design/components/input.html +156 -0
  16. package/docs/examples/design-system/pocket/.pi/design/components/menu-row.html +167 -0
  17. package/docs/examples/design-system/pocket/.pi/design/components/notice.html +171 -0
  18. package/docs/examples/design-system/pocket/.pi/design/components/segmented.html +120 -0
  19. package/docs/examples/design-system/pocket/.pi/design/components/switch.html +117 -0
  20. package/docs/examples/design-system/pocket/.pi/design/components/tool-step.html +163 -0
  21. package/docs/examples/design-system/pocket/.pi/design/dist/components.css +730 -0
  22. package/docs/examples/design-system/pocket/.pi/design/dist/names.md +495 -0
  23. package/docs/examples/design-system/pocket/.pi/design/dist/tailwind.css +1132 -0
  24. package/docs/examples/design-system/pocket/.pi/design/dist/tokens.css +1126 -0
  25. package/docs/examples/design-system/pocket/.pi/design/dist/tokens.dark.resolved.json +2022 -0
  26. package/docs/examples/design-system/pocket/.pi/design/dist/tokens.high-contrast.resolved.json +2022 -0
  27. package/docs/examples/design-system/pocket/.pi/design/dist/tokens.light.resolved.json +2022 -0
  28. package/docs/examples/design-system/pocket/.pi/design/dist/tokens.resolved.json +371 -0
  29. package/docs/examples/design-system/pocket/.pi/design/dist/tokens.studio.json +5915 -0
  30. package/docs/examples/design-system/pocket/.pi/design/guidelines.md +81 -0
  31. package/docs/examples/design-system/pocket/.pi/design/tokens.dark.json +182 -0
  32. package/docs/examples/design-system/pocket/.pi/design/tokens.high-contrast.json +185 -0
  33. package/docs/examples/design-system/pocket/.pi/design/tokens.json +2034 -0
  34. package/docs/features.md +6 -2
  35. package/docs/index.md +1 -0
  36. package/docs/map.md +34 -25
  37. package/docs/release-notes.md +1 -1
  38. package/docs/releases.md +45 -0
  39. package/package.json +2 -1
  40. package/src/server/design/check-cli.ts +283 -0
  41. package/src/server/design/color.ts +654 -0
  42. package/src/server/design/components.ts +328 -0
  43. package/src/server/design/docsite-assets.ts +29 -0
  44. package/src/server/design/docsite-color-section.ts +366 -0
  45. package/src/server/design/docsite-color.ts +303 -0
  46. package/src/server/design/docsite-components.ts +89 -0
  47. package/src/server/design/docsite-core.ts +634 -0
  48. package/src/server/design/docsite-css-base.ts +397 -0
  49. package/src/server/design/docsite-css-content.ts +477 -0
  50. package/src/server/design/docsite-css-phone.ts +251 -0
  51. package/src/server/design/docsite-css-reference.ts +374 -0
  52. package/src/server/design/docsite-css-specimens.ts +465 -0
  53. package/src/server/design/docsite-js-code.ts +96 -0
  54. package/src/server/design/docsite-js-core.ts +72 -0
  55. package/src/server/design/docsite-js-demos.ts +24 -0
  56. package/src/server/design/docsite-js-links.ts +25 -0
  57. package/src/server/design/docsite-js-nav.ts +73 -0
  58. package/src/server/design/docsite-js-stages.ts +81 -0
  59. package/src/server/design/docsite-js-table.ts +81 -0
  60. package/src/server/design/docsite-markdown.ts +221 -0
  61. package/src/server/design/docsite-motion.ts +110 -0
  62. package/src/server/design/docsite-reference.ts +269 -0
  63. package/src/server/design/docsite-sanitize.ts +193 -0
  64. package/src/server/design/docsite-shadows.ts +45 -0
  65. package/src/server/design/docsite-space.ts +289 -0
  66. package/src/server/design/docsite-type.ts +167 -0
  67. package/src/server/design/docsite.ts +508 -0
  68. package/src/server/design/export.ts +86 -9
  69. package/src/server/design/fix.ts +666 -0
  70. package/src/server/design/guide.ts +137 -22
  71. package/src/server/design/index.ts +368 -15
  72. package/src/server/design/lint-color.ts +293 -0
  73. package/src/server/design/lint-page-checks.ts +204 -0
  74. package/src/server/design/lint-page-elements.ts +252 -0
  75. package/src/server/design/lint-page-focus.ts +165 -0
  76. package/src/server/design/lint-page-literals.ts +293 -0
  77. package/src/server/design/lint-page-setup.ts +102 -0
  78. package/src/server/design/lint-page-states.ts +121 -0
  79. package/src/server/design/lint-page-values.ts +329 -0
  80. package/src/server/design/lint-page.ts +101 -0
  81. package/src/server/design/lint-suggest.ts +340 -0
  82. package/src/server/design/lint.ts +1136 -0
  83. package/src/server/design/render.ts +369 -18
  84. package/src/server/design/scan-braces.ts +115 -0
  85. package/src/server/design/scan-categorize.ts +187 -0
  86. package/src/server/design/scan-channels.ts +113 -0
  87. package/src/server/design/scan-color-base.ts +209 -0
  88. package/src/server/design/scan-color-names.ts +403 -0
  89. package/src/server/design/scan-color-palette.ts +91 -0
  90. package/src/server/design/scan-color-roles.ts +565 -0
  91. package/src/server/design/scan-colors.ts +22 -0
  92. package/src/server/design/scan-facts-antd.ts +171 -0
  93. package/src/server/design/scan-facts-files.ts +300 -0
  94. package/src/server/design/scan-facts-lists.ts +538 -0
  95. package/src/server/design/scan-facts-sass.ts +113 -0
  96. package/src/server/design/scan-facts-theme.ts +400 -0
  97. package/src/server/design/scan-facts-use.ts +674 -0
  98. package/src/server/design/scan-facts-wordpress.ts +374 -0
  99. package/src/server/design/scan-facts.ts +285 -0
  100. package/src/server/design/scan-files.ts +384 -0
  101. package/src/server/design/scan-import-convert.ts +277 -0
  102. package/src/server/design/scan-import-eval.ts +583 -0
  103. package/src/server/design/scan-import-material.ts +745 -0
  104. package/src/server/design/scan-import-sd-config.ts +370 -0
  105. package/src/server/design/scan-import-sd.ts +381 -0
  106. package/src/server/design/scan-import-studio.ts +242 -0
  107. package/src/server/design/scan-import.ts +336 -0
  108. package/src/server/design/scan-infer.ts +313 -0
  109. package/src/server/design/scan-js-eval.ts +1267 -0
  110. package/src/server/design/scan-palette.ts +485 -0
  111. package/src/server/design/scan-parse.ts +1134 -0
  112. package/src/server/design/scan-prepare.ts +402 -0
  113. package/src/server/design/scan-render-pages.ts +367 -0
  114. package/src/server/design/scan-render-probe.ts +229 -0
  115. package/src/server/design/scan-render.ts +524 -0
  116. package/src/server/design/scan-review.ts +54 -0
  117. package/src/server/design/scan-roles.ts +259 -0
  118. package/src/server/design/scan-sass-colors.ts +275 -0
  119. package/src/server/design/scan-sass-eval.ts +269 -0
  120. package/src/server/design/scan-sass-expr.ts +911 -0
  121. package/src/server/design/scan-sass-modules.ts +353 -0
  122. package/src/server/design/scan-sass-run.ts +1003 -0
  123. package/src/server/design/scan-sass-stmt.ts +256 -0
  124. package/src/server/design/scan-sass-values.ts +886 -0
  125. package/src/server/design/scan-scales.ts +983 -0
  126. package/src/server/design/scan-tailwind.ts +34 -0
  127. package/src/server/design/scan-theme-shapes.ts +579 -0
  128. package/src/server/design/scan-tree.ts +290 -0
  129. package/src/server/design/scan-util.ts +44 -0
  130. package/src/server/design/scan-variables.ts +470 -0
  131. package/src/server/design/scan.ts +703 -0
  132. package/src/server/design/system-schema.ts +68 -0
  133. package/src/server/design/system-types.ts +279 -0
  134. package/src/server/design/system.ts +510 -82
  135. package/src/server/design/tokens-base.ts +123 -0
  136. package/src/server/design/tokens-compile.ts +440 -0
  137. package/src/server/design/tokens-dtcg.ts +354 -0
  138. package/src/server/design/tokens-io.ts +417 -0
  139. package/src/server/design/tokens-model.ts +1163 -0
  140. package/src/server/design/tokens-names.ts +112 -0
  141. package/src/server/design/tokens-ramps.ts +112 -0
  142. package/src/server/design/tokens-summary.ts +317 -0
  143. package/src/server/design/tokens-tailwind.ts +324 -0
  144. package/src/server/design/tokens-values.ts +921 -0
  145. package/src/server/design/tokens.ts +533 -0
  146. package/src/server/docs.ts +8 -0
  147. package/src/server/extensions/artifacts.ts +87 -2
  148. package/src/server/extensions/design/app.js +280 -0
  149. package/src/server/extensions/design/canvas.js +142 -17
  150. package/src/server/extensions/design/check.js +656 -0
  151. package/src/server/extensions/design/color.js +383 -0
  152. package/src/server/extensions/design/data.js +102 -7
  153. package/src/server/extensions/design/devices.js +26 -0
  154. package/src/server/extensions/design/docks.js +117 -3
  155. package/src/server/extensions/design/index.js +171 -219
  156. package/src/server/extensions/design/messages.js +49 -0
  157. package/src/server/extensions/design/parts.js +15 -1
  158. package/src/server/extensions/design/paths.js +4 -0
  159. package/src/server/extensions/design/picker.js +123 -0
  160. package/src/server/extensions/design/specimen.js +55 -0
  161. package/src/server/extensions/design/state.js +72 -7
  162. package/src/server/extensions/design/style.css +546 -0
  163. package/src/server/extensions/design/system-actions.js +214 -0
  164. package/src/server/extensions/design/system-api.ts +62 -0
  165. package/src/server/extensions/design/system-data.js +315 -0
  166. package/src/server/extensions/design/system-preview.js +41 -0
  167. package/src/server/extensions/design/system-routes.ts +1122 -0
  168. package/src/server/extensions/design/system-sections.js +1344 -0
  169. package/src/server/extensions/design/system-ui.js +32 -0
  170. package/src/server/extensions/design/system-view.js +1196 -0
  171. package/src/server/extensions/design/system-widgets.js +942 -0
  172. package/src/server/extensions/design/system.css +2313 -0
  173. package/src/server/extensions/design/system.js +1479 -0
  174. package/src/server/extensions/design/unsaved.js +20 -0
  175. package/src/server/extensions/design/views.js +2 -2
  176. package/src/server/extensions/design/workspace.js +200 -105
  177. package/src/server/extensions/design.ts +89 -6
  178. package/src/server/extensions/updates/index.js +31 -9
  179. package/src/server/extensions/updates/style.css +11 -0
  180. package/src/server/extensions/updates.ts +29 -1
  181. package/src/server/host.ts +4 -1
  182. package/src/server/http/artifact-inspect.ts +338 -24
  183. package/src/server/updates.ts +235 -53
  184. package/src/server/versions.ts +71 -0
  185. package/web/artifact-bridge.js +34 -1
  186. package/npm-shrinkwrap.json +0 -3162
@@ -0,0 +1,384 @@
1
+ /**
2
+ * The file walk of the design system scan (stream T): finds the style files of a project, ranks them by how likely they
3
+ * are to hold the design (a stylesheet called `theme.css` before a deep component file), and reads each one bounded.
4
+ * The walk never follows a symlink, so a project cannot lead it out of the folder.
5
+ */
6
+ import {
7
+ SD_CONFIG_NAME,
8
+ type SdConfig,
9
+ sdConfigOfJson,
10
+ sdConfigsIn,
11
+ } from "./scan-import-sd-config.ts";
12
+ import { isObject } from "./scan-import-convert.ts";
13
+ import { closeSync, constants, fstatSync, openSync, readdirSync, readSync } from "node:fs";
14
+ import { extname, join, relative, sep } from "node:path";
15
+
16
+ /** Folders that hold other people's code or build output, not the project's own styles. */
17
+ const SKIP = new Set([
18
+ "node_modules",
19
+ ".git",
20
+ "dist",
21
+ "build",
22
+ "out",
23
+ "coverage",
24
+ ".next",
25
+ ".nuxt",
26
+ ".svelte-kit",
27
+ ".cache",
28
+ ".turbo",
29
+ ".parcel-cache",
30
+ ".output",
31
+ ".vercel",
32
+ ".netlify",
33
+ ".yarn",
34
+ ".pnpm-store",
35
+ ".venv",
36
+ "venv",
37
+ "__pycache__",
38
+ "target",
39
+ "vendor",
40
+ "vendors",
41
+ "third_party",
42
+ "third-party",
43
+ "thirdparty",
44
+ "bower_components",
45
+ "exports",
46
+ "storybook-static",
47
+ ".pi",
48
+ ".idea",
49
+ ".vscode",
50
+ ".github",
51
+ ".husky",
52
+ ]);
53
+
54
+ /** Why a folder is not walked, for the report: the first match of its name. Dot folders (`.git`) are not reported. */
55
+ const FOLDER_WHY: [RegExp, string][] = [
56
+ [/^(?:node_modules|vendors?|bower_components|third[-_]?party)$/i, "vendored code"],
57
+ [/^(?:dist|build|out|coverage|target|exports|storybook-static)$/i, "build output"],
58
+ ];
59
+
60
+ /** A file or folder that the scan did not read, and why. */
61
+ export interface Skipped {
62
+ path: string;
63
+ why: string;
64
+ }
65
+
66
+ /** Dot folders that hold a project's styles. */
67
+ const DOT_STYLE_FOLDERS = new Set([".storybook", ".vitepress", ".vuepress", ".docusaurus"]);
68
+
69
+ const STYLE =
70
+ /\.(?:css|scss|sass|less|styl|stylus|pcss|postcss|html?|vue|svelte|astro|mdx|tsx|jsx|ts|js|mjs|cjs|mts|cts)$/i;
71
+ const TOKEN_JSON =
72
+ /(?:^|\/)(?:design-?tokens?|tokens?|properties|brands?|themes?|style-?dictionary|dictionary)\/(?:[^/]+\/)*[^/]+\.json$|(?:^|\/)(?:config|[\w.-]*config|[\w.-]*[.-]config[.-][\w-]+|config[.-][\w-]+|\.styledictionaryrc)\.json$|(?:^|\/)(?:[^/]*tokens?[^/]*|[^/]*theme[^/]*|[^/]*(?:figma|studio|design-?system|material|m3)[^/]*)\.json$|(?:^|\/)(?:design-)?tokens\/[^/]+\.json$|(?:^|\/)styles\/[^/]+\.json$|(?:^|\/)\$(?:themes|metadata)\.json$/i;
73
+
74
+ export const LIMITS = {
75
+ /** Files read. */
76
+ files: 400,
77
+ /** Candidate files kept for ranking. */
78
+ candidates: 3000,
79
+ /** Entries looked at in the walk. */
80
+ entries: 20_000,
81
+ depth: 8,
82
+ /** Bytes read from one file. */
83
+ fileBytes: 200_000,
84
+ /** Bytes read from one token file: a Tokens Studio file of a large system is more than a stylesheet. */
85
+ jsonBytes: 1_500_000,
86
+ /** Bytes read in all. */
87
+ totalBytes: 8_000_000,
88
+ /** Characters kept of a value in the report. */
89
+ valueChars: 200,
90
+ } as const;
91
+
92
+ /** How likely a file is to hold the design, for ordering: higher is read first. */
93
+ export function priority(rel: string): number {
94
+ const name = rel.split("/").at(-1)!.toLowerCase();
95
+ const extension = extname(name);
96
+ let score = 0;
97
+
98
+ if (/^\.(?:css|scss|sass|less|styl|stylus|pcss|postcss)$/.test(extension)) {
99
+ score += 40;
100
+ } else if (extension === ".json") {
101
+ score += 45;
102
+ } else if (/^\.(?:[cm]?[jt]s)$/.test(extension)) {
103
+ score += 20;
104
+ } else if (/^\.(?:html?|vue|svelte|astro|mdx)$/.test(extension)) {
105
+ score += 25;
106
+ } else {
107
+ score += 12;
108
+ }
109
+
110
+ if (
111
+ /(?:^|\/)(?:tailwind\.config|theme|tokens?|variables|vars|globals?|global|base|colors?|palette|design|root|index|main|app|styles?)(?:[.\-_/]|$)/.test(
112
+ rel.toLowerCase(),
113
+ )
114
+ ) {
115
+ score += 20;
116
+ }
117
+
118
+ if (/(?:^|\/)(?:theme|themes|tokens|styles|css|design|assets\/css)\//.test(rel.toLowerCase())) {
119
+ score += 8;
120
+ }
121
+
122
+ // Tokens Studio writes `$themes.json` and `$metadata.json` beside a file for each token set.
123
+ if (/(?:^|\/)\$(?:themes|metadata)\.json$/.test(rel)) {
124
+ score += 30;
125
+ }
126
+
127
+ if (
128
+ /\.min\.|(?:^|\/)(?:vendor|third[-_]?party|generated|__generated__)\/|\.d\.ts$/.test(
129
+ rel.toLowerCase(),
130
+ )
131
+ ) {
132
+ score -= 40;
133
+ }
134
+
135
+ if (/\.(?:test|spec|stories)\.|(?:^|\/)(?:__tests__|e2e|fixtures?)\//.test(rel.toLowerCase())) {
136
+ score -= 10;
137
+ }
138
+
139
+ // A script that is not named for a theme or styles comes after every file that is.
140
+ if (
141
+ /^\.(?:[cm]?[jt]s)$/.test(extension) &&
142
+ !/(?:tailwind\.config|theme|tokens?|colors?|palette|design|variables|styles?|constants?|config)/i.test(
143
+ rel,
144
+ )
145
+ ) {
146
+ score -= 15;
147
+ }
148
+
149
+ return score - rel.split("/").length * 2;
150
+ }
151
+
152
+ /** Whether a file is worth reading at all. */
153
+ function wanted(rel: string, name: string): boolean {
154
+ if (!STYLE.test(name)) {
155
+ return TOKEN_JSON.test(rel) && name.endsWith(".json");
156
+ }
157
+
158
+ // A script may hold a theme or CSS-in-JS styles. The walk keeps them all (a bounded number, behind the best files);
159
+ // the scan reads the ones that are not named for a theme only when they look like styles.
160
+ if (/\.(?:[cm]?[jt]s)$/i.test(name) && !/\.d\.[cm]?ts$/.test(name)) {
161
+ return true;
162
+ }
163
+
164
+ return !name.endsWith(".d.ts");
165
+ }
166
+
167
+ /** The `.json` files under a Tokens Studio folder (three levels, a bounded number), added to `found`. */
168
+ function studioSets(root: string, dir: string, depth: number, found: string[]): void {
169
+ let entries;
170
+
171
+ try {
172
+ entries = readdirSync(join(root, dir), { withFileTypes: true }).sort((a, b) =>
173
+ a.name.localeCompare(b.name),
174
+ );
175
+ } catch {
176
+ return;
177
+ }
178
+
179
+ for (const entry of entries) {
180
+ const rel = dir === "" ? entry.name : `${dir}/${entry.name}`;
181
+
182
+ if (found.length >= LIMITS.candidates) {
183
+ return;
184
+ }
185
+
186
+ if (
187
+ entry.isDirectory() &&
188
+ depth < 3 &&
189
+ !SKIP.has(entry.name) &&
190
+ !entry.name.startsWith(".")
191
+ ) {
192
+ studioSets(root, rel, depth + 1, found);
193
+ } else if (entry.isFile() && entry.name.endsWith(".json") && !found.includes(rel)) {
194
+ found.push(rel);
195
+ }
196
+ }
197
+ }
198
+
199
+ /** The files to read under `root`, best first, and whether a limit left some out. */
200
+ export function collectFiles(root: string): {
201
+ files: string[];
202
+ partial: boolean;
203
+ skipped: Skipped[];
204
+ } {
205
+ const found: string[] = [];
206
+ const skipped: Skipped[] = [];
207
+ let partial = false;
208
+ let seen = 0;
209
+
210
+ const note = (path: string, why: string) => {
211
+ if (skipped.length < 40) {
212
+ skipped.push({ path, why });
213
+ }
214
+ };
215
+
216
+ const walk = (dir: string, depth: number) => {
217
+ let entries;
218
+
219
+ try {
220
+ entries = readdirSync(dir, { withFileTypes: true }).sort((a, b) =>
221
+ a.name.localeCompare(b.name),
222
+ );
223
+ } catch {
224
+ return;
225
+ }
226
+
227
+ for (const entry of entries) {
228
+ if (found.length >= LIMITS.candidates || ++seen > LIMITS.entries) {
229
+ partial = true;
230
+
231
+ return;
232
+ }
233
+
234
+ // Dirent reports a symlink as a symlink, not as its target: neither branch below takes one.
235
+ if (entry.isDirectory()) {
236
+ const skip =
237
+ SKIP.has(entry.name) ||
238
+ (entry.name.startsWith(".") && !DOT_STYLE_FOLDERS.has(entry.name));
239
+
240
+ if (depth < LIMITS.depth && !skip) {
241
+ walk(join(dir, entry.name), depth + 1);
242
+ } else if (depth >= LIMITS.depth && !skip) {
243
+ partial = true;
244
+ note(
245
+ `${relative(root, join(dir, entry.name)).split(sep).join("/")}/`,
246
+ `deeper than ${LIMITS.depth} levels`,
247
+ );
248
+ } else if (skip && !entry.name.startsWith(".")) {
249
+ note(
250
+ `${relative(root, join(dir, entry.name)).split(sep).join("/")}/`,
251
+ FOLDER_WHY.find(([pattern]) => pattern.test(entry.name))?.[1] ??
252
+ "ignored folder",
253
+ );
254
+ }
255
+ } else if (entry.isSymbolicLink() && !entry.name.startsWith(".")) {
256
+ note(
257
+ relative(root, join(dir, entry.name)).split(sep).join("/"),
258
+ "a link, not followed",
259
+ );
260
+ } else if (entry.isFile()) {
261
+ const path = join(dir, entry.name);
262
+ const rel = relative(root, path).split(sep).join("/");
263
+
264
+ if (wanted(rel, entry.name)) {
265
+ found.push(rel);
266
+ }
267
+ }
268
+ }
269
+ };
270
+
271
+ walk(root, 0);
272
+
273
+ // The sets of a Tokens Studio folder have names of their own (`global.json`, `brand/acme.json`): the files beside
274
+ // `$themes.json` or `$metadata.json` are read too.
275
+ for (const dir of new Set(
276
+ found
277
+ .filter((rel) => /(?:^|\/)\$(?:themes|metadata)\.json$/.test(rel))
278
+ .map((rel) => rel.slice(0, Math.max(0, rel.lastIndexOf("/")))),
279
+ )) {
280
+ studioSets(root, dir, 0, found);
281
+ }
282
+
283
+ // A Style Dictionary config names its token files by globs: the folders they start in are read too.
284
+ for (const rel of [...found].filter((each) =>
285
+ SD_CONFIG_NAME.test((each.split("/").at(-1) ?? "").replace(/\.(?:json|[cm]?[jt]s)$/i, "")),
286
+ )) {
287
+ let text = "";
288
+
289
+ try {
290
+ text = readHead(join(root, ...rel.split("/")), 60_000);
291
+ } catch {
292
+ continue;
293
+ }
294
+
295
+ const dir = rel.slice(0, Math.max(0, rel.lastIndexOf("/")));
296
+ let configs: SdConfig[] = [];
297
+
298
+ if (rel.endsWith(".json")) {
299
+ try {
300
+ const root: unknown = JSON.parse(text);
301
+
302
+ if (isObject(root) && Array.isArray(root.source) && isObject(root.platforms)) {
303
+ configs = [sdConfigOfJson(dir, rel, root)];
304
+ }
305
+ } catch {
306
+ // Not JSON, or cut short: not a config that can be read.
307
+ }
308
+ } else {
309
+ configs = sdConfigsIn(dir, rel, text);
310
+ }
311
+
312
+ for (const config of configs.slice(0, 8)) {
313
+ for (const glob of [...config.include, ...config.source].slice(0, 12)) {
314
+ const fixed = glob
315
+ .replace(/^\.\//, "")
316
+ .split("/")
317
+ .filter((_, at, all) => at < all.length - 1)
318
+ .filter((part, at, all) =>
319
+ all.slice(0, at + 1).every((each) => !/[*?{$]/.test(each)),
320
+ );
321
+
322
+ for (const base of new Set([config.dir, ""])) {
323
+ const folder = [base, ...fixed].filter(Boolean).join("/");
324
+
325
+ if (folder !== "" || fixed.length === 0) {
326
+ studioSets(root, folder, 0, found);
327
+ }
328
+ }
329
+ }
330
+ }
331
+ }
332
+
333
+ // A minified file (`app.min.css`) is the build of a source, not the design: it is left out when the project has style
334
+ // files of its own, and read (last) when it has nothing else.
335
+ const isMin = (rel: string) => /\.min\.[a-z]+$/i.test(rel);
336
+ const own = found.filter(
337
+ (rel) => !isMin(rel) && /\.(?:css|scss|sass|less|styl|stylus|pcss)$/i.test(rel),
338
+ );
339
+ const kept = own.length > 0 ? found.filter((rel) => !isMin(rel)) : found;
340
+
341
+ for (const rel of found.filter((each) => !kept.includes(each))) {
342
+ note(rel, "minified");
343
+ }
344
+
345
+ const ranked = kept
346
+ .map((rel) => ({ rel, score: priority(rel) }))
347
+ .sort((a, b) => b.score - a.score || a.rel.localeCompare(b.rel))
348
+ .map((entry) => entry.rel);
349
+
350
+ if (ranked.length > LIMITS.files) {
351
+ partial = true;
352
+ note(
353
+ `${ranked.length - LIMITS.files} files`,
354
+ `over the limit of ${LIMITS.files} files read; the lowest ranked were left out`,
355
+ );
356
+ }
357
+
358
+ return { files: ranked.slice(0, LIMITS.files), partial, skipped };
359
+ }
360
+
361
+ /** The first `limit` bytes of a file as text (a stylesheet's size by default); it reads no more and never follows a link. */
362
+ export function readHead(path: string, limit: number = LIMITS.fileBytes): string {
363
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
364
+
365
+ try {
366
+ // No more than the file has (a regular file), so that a small file does not cost a large buffer.
367
+ const buffer = Buffer.alloc(Math.min(limit, Math.max(0, fstatSync(fd).size)));
368
+ let size = 0;
369
+
370
+ while (size < buffer.length) {
371
+ const read = readSync(fd, buffer, size, buffer.length - size, null);
372
+
373
+ if (read <= 0) {
374
+ break;
375
+ }
376
+
377
+ size += read;
378
+ }
379
+
380
+ return buffer.subarray(0, size).toString("utf8");
381
+ } finally {
382
+ closeSync(fd);
383
+ }
384
+ }
@@ -0,0 +1,277 @@
1
+ /**
2
+ * One token of a token file as a DTCG token (stream T). Style Dictionary (`value`, `type`), Tokens Studio (`value` and
3
+ * `type` with `sizing`, `fontFamilies`, `boxShadow`, `lineHeights`, ...), and DTCG (`$value`, `$type`) are all read; a
4
+ * value that has no unit gets the one its type implies, a font weight that is a name gets its number, and the members of
5
+ * a type style, a shadow, and a border are put in the forms that the tokens engine reads.
6
+ */
7
+ import { colorsIn } from "./scan-parse.ts";
8
+ import { shadowValue } from "./scan-scales.ts";
9
+
10
+ export type Obj = Record<string, unknown>;
11
+
12
+ export const isObject = (value: unknown): value is Obj =>
13
+ typeof value === "object" && value !== null && !Array.isArray(value);
14
+
15
+ // Tokens Studio and Style Dictionary type names to DTCG types.
16
+ const TYPES: Record<string, string> = {
17
+ color: "color",
18
+ dimension: "dimension",
19
+ sizing: "dimension",
20
+ spacing: "dimension",
21
+ borderradius: "dimension",
22
+ borderwidth: "dimension",
23
+ fontsizes: "dimension",
24
+ fontsize: "dimension",
25
+ letterspacing: "dimension",
26
+ paragraphspacing: "dimension",
27
+ fontfamilies: "fontFamily",
28
+ fontfamily: "fontFamily",
29
+ fontweights: "fontWeight",
30
+ fontweight: "fontWeight",
31
+ lineheights: "number",
32
+ lineheight: "number",
33
+ opacity: "number",
34
+ number: "number",
35
+ boxshadow: "shadow",
36
+ shadow: "shadow",
37
+ typography: "typography",
38
+ duration: "duration",
39
+ cubicbezier: "cubicBezier",
40
+ border: "border",
41
+ transition: "transition",
42
+ gradient: "gradient",
43
+ strokestyle: "strokeStyle",
44
+ };
45
+
46
+ const LENGTH_TYPES = new Set([
47
+ "sizing",
48
+ "spacing",
49
+ "borderradius",
50
+ "borderwidth",
51
+ "fontsizes",
52
+ "fontsize",
53
+ "letterspacing",
54
+ "paragraphspacing",
55
+ "dimension",
56
+ ]);
57
+
58
+ /** The weights that Figma and CSS name, by the name with no space or hyphen, lowercase. */
59
+ const WEIGHTS: Record<string, number> = {
60
+ thin: 100,
61
+ hairline: 100,
62
+ extralight: 200,
63
+ ultralight: 200,
64
+ light: 300,
65
+ regular: 400,
66
+ normal: 400,
67
+ book: 400,
68
+ medium: 500,
69
+ semibold: 600,
70
+ demibold: 600,
71
+ bold: 700,
72
+ extrabold: 800,
73
+ ultrabold: 800,
74
+ black: 900,
75
+ heavy: 900,
76
+ };
77
+
78
+ /** A font weight as a number when it is a name (`Bold`, `Semi Bold`, `Bold Italic`) or a number in text. */
79
+ export function weightOf(value: unknown): unknown {
80
+ if (typeof value === "number") {
81
+ return value;
82
+ }
83
+
84
+ if (typeof value !== "string") {
85
+ return value;
86
+ }
87
+
88
+ const text = value.trim();
89
+
90
+ if (/^\d{3,4}$/.test(text)) {
91
+ return Number(text);
92
+ }
93
+
94
+ if (text.startsWith("{") || text === "") {
95
+ return value;
96
+ }
97
+
98
+ const name = text
99
+ .toLowerCase()
100
+ .replace(/\b(?:italic|oblique)\b/g, "")
101
+ .replace(/[\s_-]+/g, "");
102
+
103
+ return WEIGHTS[name] ?? value;
104
+ }
105
+
106
+ const px = (value: unknown): unknown =>
107
+ typeof value === "number" ||
108
+ (typeof value === "string" && /^-?(?:\d+\.?\d*|\.\d+)$/.test(value.trim()))
109
+ ? `${Number(value)}px`
110
+ : value;
111
+
112
+ /** A letter spacing: a bare number is px, a percent is em (Figma's `-2%` is `-0.02em`). */
113
+ function trackingOf(value: unknown): unknown {
114
+ if (typeof value === "string") {
115
+ const percent = /^\s*(-?(?:\d+\.?\d*|\.\d+))\s*%\s*$/.exec(value);
116
+
117
+ if (percent !== null) {
118
+ return `${Number((Number(percent[1]) / 100).toFixed(4))}em`;
119
+ }
120
+ }
121
+
122
+ return px(value);
123
+ }
124
+
125
+ /** A line height: a percent is a ratio, a bare number is a ratio (as Tokens Studio writes it), a length stays. */
126
+ function leadingOf(value: unknown): unknown {
127
+ if (typeof value === "string") {
128
+ const percent = /^\s*(\d+\.?\d*|\.\d+)\s*%\s*$/.exec(value);
129
+
130
+ if (percent !== null) {
131
+ return Number((Number(percent[1]) / 100).toFixed(4));
132
+ }
133
+
134
+ if (/^\s*(?:\d+\.?\d*|\.\d+)\s*$/.test(value)) {
135
+ return Number(value);
136
+ }
137
+ }
138
+
139
+ return value;
140
+ }
141
+
142
+ function shadowLayer(layer: unknown): unknown {
143
+ if (!isObject(layer) || layer.x === undefined) {
144
+ return layer;
145
+ }
146
+
147
+ const length = (value: unknown) =>
148
+ typeof value === "number" || /^-?[\d.]+$/.test(String(value))
149
+ ? `${value}px`
150
+ : String(value);
151
+
152
+ return {
153
+ color: layer.color,
154
+ offsetX: length(layer.x),
155
+ offsetY: length(layer.y),
156
+ blur: length(layer.blur ?? 0),
157
+ ...(layer.spread === undefined ? {} : { spread: length(layer.spread) }),
158
+ ...(layer.type === "innerShadow" ? { inset: true } : {}),
159
+ };
160
+ }
161
+
162
+ /** A type style as the engine reads it: its five members, in their forms. Tokens Studio's other members are left out. */
163
+ function typographyOf(value: Obj): Obj {
164
+ const out: Obj = {};
165
+ const family = value.fontFamily ?? value.fontFamilies;
166
+ const size = value.fontSize ?? value.fontSizes;
167
+ const weight = value.fontWeight ?? value.fontWeights;
168
+ const leading = value.lineHeight ?? value.lineHeights;
169
+
170
+ if (family !== undefined) {
171
+ out.fontFamily = family;
172
+ }
173
+
174
+ if (size !== undefined) {
175
+ out.fontSize = px(size);
176
+ }
177
+
178
+ if (weight !== undefined) {
179
+ out.fontWeight = weightOf(weight);
180
+ }
181
+
182
+ // Figma's `AUTO` is no number: the style has no line height of its own.
183
+ if (leading !== undefined && !/^\s*(?:auto|normal)\s*$/i.test(String(leading))) {
184
+ out.lineHeight = leadingOf(leading);
185
+ }
186
+
187
+ if (value.letterSpacing !== undefined) {
188
+ out.letterSpacing = trackingOf(value.letterSpacing);
189
+ }
190
+
191
+ return out;
192
+ }
193
+
194
+ /** A border as the engine reads it: color, width, style. */
195
+ function borderOf(value: Obj): Obj {
196
+ return {
197
+ ...(value.color === undefined ? {} : { color: value.color }),
198
+ ...(value.width === undefined ? {} : { width: px(value.width) }),
199
+ ...(value.style === undefined ? {} : { style: value.style }),
200
+ };
201
+ }
202
+
203
+ /** One token node as a DTCG token, or undefined when it is not one that the engine can hold. */
204
+ export function convert(node: Obj, inherited: string | undefined): Obj | undefined {
205
+ const value = node.$value ?? node.value;
206
+
207
+ if (value === undefined || (typeof value === "object" && value === null)) {
208
+ return undefined;
209
+ }
210
+
211
+ const rawType = String(node.$type ?? node.type ?? inherited ?? "");
212
+ const key = rawType.toLowerCase();
213
+ const type =
214
+ TYPES[key] ??
215
+ (rawType === "" && typeof value === "string"
216
+ ? colorsIn(value, true).length === 1 && colorsIn(value, true)[0]!.text === value.trim()
217
+ ? "color"
218
+ : undefined
219
+ : undefined);
220
+ let out: unknown = value;
221
+
222
+ // A reference takes its type from the token it points at, and a mode file leaves the type to the default mode.
223
+ const reference = typeof value === "string" && /^\{[^{}]+\}$/.test(value.trim());
224
+
225
+ if (type === undefined && !reference) {
226
+ return undefined;
227
+ }
228
+
229
+ if (typeof value === "string" && !value.startsWith("{")) {
230
+ if (key === "letterspacing" && type === "dimension") {
231
+ out = trackingOf(value);
232
+ } else if (LENGTH_TYPES.has(key) && /^-?[\d.]+$/.test(value)) {
233
+ out = `${value}px`;
234
+ } else if (key.startsWith("lineheight") && /^[\d.]+%$/.test(value)) {
235
+ out = Number.parseFloat(value) / 100;
236
+ } else if (type === "number" && key === "opacity" && /^[\d.]+%$/.test(value)) {
237
+ out = Number.parseFloat(value) / 100;
238
+ } else if (type === "number" && /^-?[\d.]+$/.test(value)) {
239
+ out = Number(value);
240
+ } else if (type === "fontWeight") {
241
+ out = weightOf(value);
242
+ } else if (type === "duration" && /^-?\d*\.?\d+$/.test(value.trim())) {
243
+ out = `${value.trim()}ms`;
244
+ }
245
+ } else if (typeof value === "number" && LENGTH_TYPES.has(key)) {
246
+ out = `${value}px`;
247
+ } else if (typeof value === "number" && type === "duration") {
248
+ out = `${value}ms`;
249
+ }
250
+
251
+ if (type === "shadow") {
252
+ out =
253
+ typeof out === "string" && !out.trim().startsWith("{")
254
+ ? shadowValue(out)
255
+ : Array.isArray(out)
256
+ ? out.map(shadowLayer)
257
+ : shadowLayer(out);
258
+ } else if (type === "typography" && isObject(out)) {
259
+ out = typographyOf(out);
260
+ } else if (type === "border" && isObject(out)) {
261
+ out = borderOf(out);
262
+ }
263
+
264
+ // A number that is not one (`AUTO`) is no token.
265
+ if (type === "number" && typeof out === "string" && !out.trim().startsWith("{")) {
266
+ return undefined;
267
+ }
268
+
269
+ const token: Obj = type === undefined ? { $value: out } : { $value: out, $type: type };
270
+ const description = node.$description ?? node.description ?? node.comment;
271
+
272
+ if (typeof description === "string" && description !== "") {
273
+ token.$description = description.slice(0, 200);
274
+ }
275
+
276
+ return token;
277
+ }