@homepages/concrete 10.0.0 → 11.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/codemods/manifest.json +5 -158
  3. package/dist/artifact/playground/client/assets/index-ByeGGedv.js +1259 -0
  4. package/dist/artifact/playground/client/assets/index-CxWPYOH2.css +1 -0
  5. package/dist/artifact/playground/client/index.html +2 -2
  6. package/dist/artifact/playground/client/island-canvas-host.mjs +1 -1
  7. package/dist/artifact/playground/host.mjs +26 -26
  8. package/dist/base.css +1 -8
  9. package/dist/cli/build/artifact.js +1 -1
  10. package/dist/cli/build/fixtures.js +3 -2
  11. package/dist/cli/check/stages/sections.js +1 -1
  12. package/dist/cli/dev/workspace-reader.js +3 -2
  13. package/dist/css/compile.js +3 -6
  14. package/dist/css/rules.js +1 -51
  15. package/dist/design-system/format-variants.js +1 -1
  16. package/dist/fixtures/resolve.js +5 -1
  17. package/dist/fixtures/rows.js +2 -2
  18. package/dist/index.d.ts +5 -5
  19. package/dist/packages/external/concrete/package.js +1 -1
  20. package/dist/packages/internal/fill-vocabulary/dist/holder.js +3 -14
  21. package/dist/packages/internal/media-resolution/dist/document.js +3 -3
  22. package/dist/packages/internal/media-resolution/dist/image.js +3 -3
  23. package/dist/packages/internal/media-resolution/dist/tour.js +6 -6
  24. package/dist/packages/internal/media-resolution/dist/video.js +9 -9
  25. package/dist/packages/internal/section-contracts/dist/fill-verb-contract.js +1 -0
  26. package/dist/packages/internal/section-contracts/dist/runners.js +1 -3
  27. package/dist/packages/internal/section-contracts/dist/source-contract.js +3 -3
  28. package/dist/packages/internal/section-contracts/dist/sources-contract.js +0 -2
  29. package/dist/packages/internal/template-artifact/dist/index.js +2 -2
  30. package/dist/packages/internal/template-artifact/dist/layout.js +11 -11
  31. package/dist/packages/internal/template-artifact/dist/manifest.js +1 -1
  32. package/dist/packages/internal/template-artifact/dist/verify.js +13 -17
  33. package/dist/packages/internal/template-contracts/dist/document-value.d.ts +3 -5
  34. package/dist/packages/internal/template-contracts/dist/fill-builders.js +2 -6
  35. package/dist/packages/internal/template-contracts/dist/fill-spec-schema.js +4 -1
  36. package/dist/packages/internal/template-contracts/dist/list.js +0 -14
  37. package/dist/packages/internal/template-contracts/dist/primitive-descriptors.js +1 -1
  38. package/dist/packages/internal/template-contracts/dist/runtime-values.d.ts +6 -7
  39. package/dist/packages/internal/template-contracts/dist/slot-builders.js +0 -2
  40. package/dist/packages/internal/template-contracts/dist/slot-ref.d.ts +6 -1
  41. package/dist/packages/internal/template-contracts/dist/tour-value.d.ts +2 -4
  42. package/dist/packages/internal/template-contracts/dist/video-value.d.ts +3 -4
  43. package/dist/primitives/Image.d.ts +2 -2
  44. package/dist/primitives/Tour.d.ts +2 -2
  45. package/dist/primitives/Video.d.ts +2 -2
  46. package/dist/primitives/slot-bindings.js +6 -13
  47. package/dist/primitives/slot-document.d.ts +1 -1
  48. package/dist/primitives/slot-download.d.ts +3 -1
  49. package/dist/primitives/slot-media.d.ts +5 -2
  50. package/dist/primitives/slot-media.js +1 -1
  51. package/dist/rules/registry.js +0 -6
  52. package/dist/schema/format-presets.d.ts +1 -1
  53. package/dist/schema/section-schema.d.ts +5 -5
  54. package/dist/styles.css +4 -4
  55. package/dist/template/define-template.js +0 -1
  56. package/guide/reference/cli/INDEX.md +2 -2
  57. package/guide/reference/cli/build.md +1 -1
  58. package/guide/reference/cli/check.md +1 -1
  59. package/guide/reference/cli/dev.md +1 -1
  60. package/guide/reference/cli/property-add.md +1 -1
  61. package/guide/reference/cli/property-list.md +1 -1
  62. package/guide/reference/cli/publish.md +1 -1
  63. package/guide/reference/cli/upgrade.md +1 -1
  64. package/guide/reference/rules/INDEX.md +1 -2
  65. package/package.json +2 -2
  66. package/codemods/fill-is-a-source.mjs +0 -533
  67. package/codemods/framework-namespace.mjs +0 -107
  68. package/codemods/list-grammar.mjs +0 -923
  69. package/codemods/object-form-only.mjs +0 -39
  70. package/codemods/platform-namespace.mjs +0 -83
  71. package/codemods/process-builders.mjs +0 -198
  72. package/codemods/reads-replace-reconcile.mjs +0 -285
  73. package/codemods/registry-keys-only.mjs +0 -113
  74. package/codemods/slot-object.mjs +0 -1097
  75. package/codemods/steps/content-object-fields.mjs +0 -324
  76. package/codemods/steps/list-object-form.mjs +0 -686
  77. package/codemods/steps/registry-key-reads.mjs +0 -276
  78. package/codemods/steps/select-object-form.mjs +0 -210
  79. package/codemods/table-rows.mjs +0 -568
  80. package/codemods/theme-collapse.mjs +0 -396
  81. package/codemods/unlayer-author-css.mjs +0 -194
  82. package/codemods/unwrap-object-fields.mjs +0 -310
  83. package/codemods/viewer-slot-document.mjs +0 -131
  84. package/codemods/write-property-as-facts-document.mjs +0 -716
  85. package/codemods/write-the-address-line.mjs +0 -255
  86. package/codemods/write-the-registry-members.mjs +0 -653
  87. package/codemods/write-the-select-from.mjs +0 -141
  88. package/codemods/write-the-sole-from.mjs +0 -369
  89. package/codemods/write-the-table-from.mjs +0 -267
  90. package/codemods/write-the-whole-item.mjs +0 -512
  91. package/codemods/writeback-drop.mjs +0 -168
  92. package/codemods/written-contact-address.mjs +0 -162
  93. package/codemods/written-media-category.mjs +0 -227
  94. package/codemods/written-ref-kinds-name-the-layer.mjs +0 -172
  95. package/codemods/written-uploads-replace-pool-reads.mjs +0 -454
  96. package/codemods/written-uploads-sort-into-lists.mjs +0 -405
  97. package/codemods/written-uploads-stated-in-sorted-lists.mjs +0 -295
  98. package/codemods/written-video-sources-drop.mjs +0 -144
  99. package/codemods/written-without-pick-none.mjs +0 -146
  100. package/codemods/written-without-retired-knowledge.mjs +0 -223
  101. package/codemods/written-without-the-media-key.mjs +0 -202
  102. package/codemods/written-without-the-property-type.mjs +0 -249
  103. package/dist/artifact/playground/client/assets/index-BFNHB7VM.css +0 -1
  104. package/dist/artifact/playground/client/assets/index-Div1yo6s.js +0 -1259
@@ -1,310 +0,0 @@
1
- // 9.0.0 — an object's field is read straight off its object: `slot.address.street`,
2
- // `plan.image`. The `.fields` hop a binding carried is gone, so a field reads the way a
3
- // row's member does (`agent.phone`).
4
- //
5
- // What this codemod does, in every `.ts` and `.tsx` under the workspace, wherever the
6
- // value holding `.fields` is an object's binding — a top-level object's (`slot.address`)
7
- // or an item's of a list of objects (`bindItems(slot.units)[i]`, an item function's
8
- // argument):
9
- //
10
- // - `slot.address.fields.street` reads `slot.address.street`, `item.fields?.photo` reads
11
- // `item?.photo`, and `item.fields[key]` reads `item[key]`;
12
- // - `const { street, city } = slot.address.fields` destructures the binding itself;
13
- // `const field = entry.fields` holds the binding where `field` is only ever read by a
14
- // field's name or handed on to the workspace's own code, and
15
- // `<ContactLinks fields={contact.fields} />` hands on the binding — the component's
16
- // own prop type is rewritten with it, so the hand-off is typechecked;
17
- // - in a type, `Bindings["address"]["fields"]["street"]` reads
18
- // `Bindings["address"]["street"]`, and `typeof slot.address.fields.street`
19
- // `typeof slot.address.street`.
20
- //
21
- // It tells a binding from a declaration by type, against this package's own typings:
22
- // `Hero.schema.slots.address.fields.street`, `list.element.fields` and every other
23
- // `.fields` on a definition stay as they are, since a definition still declares its
24
- // fields there.
25
- //
26
- // What it hands back, by line: a `.fields` read off a binding that is then enumerated,
27
- // spread or handed to a library (`Object.keys(item.fields)`) — the binding carries its
28
- // own keys beside its fields, so that read has no one-for-one rewrite — a `.fields` read
29
- // whose holder it could not type at all, and an object field named like one of the
30
- // binding's own keys (`value`, `index`, …), which `concrete check` now refuses: renaming
31
- // it renames the key its content is stored under, so the name is the author's to choose.
32
- // The adoption a publish runs carries each stored value, and the edit pinning it, to the
33
- // new name when the renamed field keeps its type and label and no other field new to the
34
- // object declares both: that is how it tells a rename from a field replaced.
35
-
36
- import { readdir, readFile, writeFile } from "node:fs/promises";
37
- import { dirname, join, relative, sep } from "node:path";
38
- import { fileURLToPath } from "node:url";
39
-
40
- import ts from "typescript";
41
-
42
- const EXTENSIONS = [".ts", ".tsx"];
43
- const SKIP_DIRS = new Set(["node_modules", ".concrete", ".git", "dist", "build"]);
44
-
45
- // The package this codemod ships in: its typings type the workspace's imports of it, so
46
- // the rewrite holds wherever the codemod runs — an installed workspace or a bare copy.
47
- const PACKAGE_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
48
- const TYPINGS = {
49
- "@homepages/concrete": ["dist/index.d.ts"],
50
- "@homepages/concrete/fixtures": ["dist/fixtures.d.ts"],
51
- "@homepages/concrete/browser": ["dist/browser.d.ts"],
52
- };
53
-
54
- async function sourceFiles(root) {
55
- const found = [];
56
- async function walk(dir) {
57
- for (const entry of await readdir(dir, { withFileTypes: true })) {
58
- if (entry.isDirectory()) {
59
- if (!SKIP_DIRS.has(entry.name)) await walk(join(dir, entry.name));
60
- } else if (EXTENSIONS.some((ext) => entry.name.endsWith(ext)) && !entry.name.endsWith(".d.ts")) {
61
- found.push(join(dir, entry.name));
62
- }
63
- }
64
- }
65
- await walk(root);
66
- return found.sort();
67
- }
68
-
69
- /** Non-overlapping text replacements, applied back to front. */
70
- class Edits {
71
- constructor() {
72
- this.list = [];
73
- }
74
- add(start, end, text) {
75
- this.list.push({ start, end, text });
76
- }
77
- apply(source) {
78
- const sorted = [...this.list].sort((a, b) => b.start - a.start || b.end - a.end);
79
- let out = source;
80
- let floor = Infinity;
81
- for (const edit of sorted) {
82
- if (edit.end > floor) throw new Error(`unwrap-object-fields: overlapping rewrites at ${String(edit.start)}`);
83
- out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);
84
- floor = edit.start;
85
- }
86
- return out;
87
- }
88
- }
89
-
90
- function program(files) {
91
- const paths = Object.fromEntries(Object.entries(TYPINGS).map(([specifier, [file]]) => [specifier, [join(PACKAGE_DIR, file)]]));
92
- return ts.createProgram(files, {
93
- target: ts.ScriptTarget.ES2022,
94
- module: ts.ModuleKind.ESNext,
95
- moduleResolution: ts.ModuleResolutionKind.Bundler,
96
- jsx: ts.JsxEmit.ReactJSX,
97
- strict: true,
98
- noEmit: true,
99
- skipLibCheck: true,
100
- allowImportingTsExtensions: true,
101
- resolveJsonModule: true,
102
- paths,
103
- });
104
- }
105
-
106
- function lineOf(sf, node) {
107
- return sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;
108
- }
109
-
110
- // A binding answers `value`, `present` and its `def`; a definition answers none of the
111
- // first two, and a fact or a content value carries no `def`.
112
- function isBindingType(checker, type) {
113
- const held = checker.getNonNullableType(type);
114
- if (held.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) return undefined;
115
- const constituents = held.isUnion() ? held.types : [held];
116
- const binding = (t) => ["value", "present", "def"].every((key) => checker.getPropertyOfType(t, key) !== undefined);
117
- if (constituents.every(binding)) return true;
118
- return constituents.some(binding) ? undefined : false;
119
- }
120
-
121
- // The `.fields` part of `holder.fields` / `holder?.fields`: removing it leaves `holder` /
122
- // `holder?`, which the access after it continues — `holder?.street`.
123
- function hopRange(sf, access) {
124
- const token = access.questionDotToken ?? access.getChildren(sf).find((child) => child.kind === ts.SyntaxKind.DotToken);
125
- const start = access.questionDotToken !== undefined ? token.getStart(sf) + 1 : token.getStart(sf);
126
- return { start, end: access.name.getEnd() };
127
- }
128
-
129
- // Whether `symbol` is declared in the workspace's own source rather than a library's.
130
- function ownedBy(checker, symbol, root) {
131
- const target = symbol !== undefined && symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
132
- const file = target?.declarations?.[0]?.getSourceFile().fileName;
133
- return file !== undefined && !file.includes("/node_modules/") && relative(root, file).split(sep)[0] !== "..";
134
- }
135
-
136
- // Whether a fields value handed on whole (`<ContactLinks fields={f} />`, `links(f)`) goes
137
- // to a component or function of the workspace's own — whose parameter type the codemod
138
- // rewrites alongside, so the binding's arrival there is typechecked. A library's
139
- // (`Object.keys`, a DOM attribute) might enumerate it, and is the author's to judge.
140
- function passedOn(checker, node, root) {
141
- const parent = node.parent;
142
- if (ts.isJsxExpression(parent) && ts.isJsxAttribute(parent.parent)) {
143
- const element = parent.parent.parent.parent;
144
- return ownedBy(checker, checker.getSymbolAtLocation(element.tagName), root);
145
- }
146
- if (ts.isCallExpression(parent) && parent.arguments.includes(node)) {
147
- return ownedBy(checker, checker.getSymbolAtLocation(parent.expression), root);
148
- }
149
- return false;
150
- }
151
-
152
- // The keys an object's binding owns — no field may take one (`OBJECT_BINDING_OWN_KEYS`).
153
- const OWN_KEYS = new Set(["id", "slot", "index", "def", "value", "present", "enclosing"]);
154
-
155
- // Whether `callee` is this package's `object()` builder.
156
- function isConcreteObject(checker, callee, root) {
157
- const symbol = checker.getSymbolAtLocation(callee);
158
- if (symbol === undefined || ownedBy(checker, symbol, root)) return false;
159
- const target = symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
160
- return target.name === "object" && (target.declarations ?? []).some((declaration) => declaration.getSourceFile().fileName.startsWith(PACKAGE_DIR));
161
- }
162
-
163
- /** The `fields` object literal an `object({ … })` call declares, or `undefined`. */
164
- function objectFields(call) {
165
- const [options] = call.arguments;
166
- if (options === undefined || !ts.isObjectLiteralExpression(options)) return undefined;
167
- const fields = options.properties.find((property) => ts.isPropertyAssignment(property) && property.name.getText() === "fields");
168
- return fields !== undefined && ts.isObjectLiteralExpression(fields.initializer) ? fields.initializer : undefined;
169
- }
170
-
171
- /** The property a destructuring element reads: `fields` in `{ fields }` and `{ fields: f }`. */
172
- function elementKey(element) {
173
- const key = element.propertyName ?? element.name;
174
- return ts.isIdentifier(key) || ts.isStringLiteral(key) ? key.text : undefined;
175
- }
176
-
177
- const continues = (node) => {
178
- const parent = node.parent;
179
- return (ts.isPropertyAccessExpression(parent) || ts.isElementAccessExpression(parent)) && parent.expression === node;
180
- };
181
-
182
- // Whether every use of the variable `name` declares reads a field off it (`field.x`,
183
- // `field[key]`) or hands it on to the workspace's own code, so it may hold the binding
184
- // instead of its fields.
185
- function holdsFields(checker, sf, name, root) {
186
- const symbol = checker.getSymbolAtLocation(name);
187
- if (symbol === undefined) return false;
188
- let only = true;
189
- const visit = (node) => {
190
- if (!only) return;
191
- if (ts.isIdentifier(node) && node !== name && checker.getSymbolAtLocation(node) === symbol) {
192
- if (!continues(node) && !passedOn(checker, node, root)) only = false;
193
- return;
194
- }
195
- ts.forEachChild(node, visit);
196
- };
197
- visit(sf);
198
- return only;
199
- }
200
-
201
- function rewrite(checker, sf, root) {
202
- const edits = new Edits();
203
- const refused = [];
204
-
205
- const visit = (node) => {
206
- // A value read: `holder.fields`.
207
- if (ts.isPropertyAccessExpression(node) && node.name.text === "fields") {
208
- const holder = isBindingType(checker, checker.getTypeAtLocation(node.expression));
209
- if (holder === undefined) {
210
- refused.push(`line ${String(lineOf(sf, node))}: \`${node.getText(sf)}\` — the codemod could not tell whether this is an object's binding; if it is, read each field straight off it`);
211
- } else if (holder) {
212
- const parent = node.parent;
213
- const destructured = ts.isVariableDeclaration(parent) && parent.initializer === node && ts.isObjectBindingPattern(parent.name);
214
- const held = ts.isVariableDeclaration(parent) && parent.initializer === node && ts.isIdentifier(parent.name) && holdsFields(checker, sf, parent.name, root);
215
- const read = continues(node) && ts.isPropertyAccessExpression(node.parent) ? node.parent.name.text : undefined;
216
- if (read !== undefined && OWN_KEYS.has(read)) {
217
- // Dropping the hop would read the binding's own `value`, never the field.
218
- refused.push(`line ${String(lineOf(sf, node))}: \`${node.parent.getText(sf)}\` reads a field named like its binding's own \`${read}\` — rename the field, then read it straight off the binding`);
219
- } else if (continues(node)) {
220
- const { start, end } = hopRange(sf, node);
221
- edits.add(start, end, "");
222
- } else if (destructured || held || passedOn(checker, node, root)) {
223
- edits.add(node.expression.getEnd(), node.getEnd(), "");
224
- } else {
225
- refused.push(
226
- `line ${String(lineOf(sf, node))}: \`${node.getText(sf)}\` is used whole — an object's binding carries its own keys beside its fields, so read the fields you need off \`${node.expression.getText(sf)}\` by name`,
227
- );
228
- }
229
- }
230
- }
231
- // A field the binding would shadow: `object({ fields: { value: … } })`.
232
- if (ts.isCallExpression(node) && isConcreteObject(checker, node.expression, root)) {
233
- const fields = objectFields(node);
234
- for (const property of fields?.properties ?? []) {
235
- const key = property.name !== undefined && (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name)) ? property.name.text : undefined;
236
- if (key !== undefined && OWN_KEYS.has(key)) {
237
- refused.push(
238
- `line ${String(lineOf(sf, property))}: object field "${key}" is named like its binding's own \`${key}\`, which a read off the binding answers instead — rename it for what it holds, keeping its type and label, and add no other new field of that type and label to the object: publishing then carries every site's stored value, and the edit pinning it, to the new name`,
239
- );
240
- }
241
- }
242
- }
243
- // A destructured hop: `({ fields }) => fields.price`, `const { fields: { price } } = item`.
244
- if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent) && node.dotDotDotToken === undefined && elementKey(node) === "fields") {
245
- const pattern = node.parent;
246
- if (isBindingType(checker, checker.getTypeAtLocation(pattern)) === true) {
247
- const others = pattern.elements.filter((element) => element !== node);
248
- if (node.initializer !== undefined) {
249
- refused.push(`line ${String(lineOf(sf, node))}: \`${node.getText(sf)}\` gives the fields a default — read each field straight off the binding instead`);
250
- } else if (ts.isObjectBindingPattern(node.name)) {
251
- // The fields it names are the binding's own now: they join the outer pattern.
252
- edits.add(node.getStart(sf), node.getEnd(), node.name.elements.map((element) => element.getText(sf)).join(", "));
253
- } else if (!holdsFields(checker, sf, node.name, root)) {
254
- refused.push(`line ${String(lineOf(sf, node))}: \`${node.name.text}\` is used whole — an object's binding carries its own keys beside its fields, so read the fields you need off the binding by name`);
255
- } else if (others.length === 0) {
256
- edits.add(pattern.getStart(sf), pattern.getEnd(), node.name.text);
257
- } else if (others.some((element) => element.dotDotDotToken !== undefined)) {
258
- refused.push(`line ${String(lineOf(sf, node))}: \`${pattern.getText(sf)}\` already gathers a rest — read each field straight off the binding instead`);
259
- } else {
260
- // The rest of the binding answers every field by name; the other keys stay as they were.
261
- edits.add(pattern.getStart(sf), pattern.getEnd(), `{ ${[...others.map((element) => element.getText(sf)), `...${node.name.text}`].join(", ")} }`);
262
- }
263
- return;
264
- }
265
- }
266
- // A type: `Binding["fields"]["street"]`.
267
- if (ts.isIndexedAccessTypeNode(node) && ts.isLiteralTypeNode(node.indexType) && ts.isStringLiteral(node.indexType.literal) && node.indexType.literal.text === "fields") {
268
- if (isBindingType(checker, checker.getTypeFromTypeNode(node.objectType)) === true) {
269
- edits.add(node.objectType.getEnd(), node.getEnd(), "");
270
- }
271
- }
272
- // A type query: `typeof slot.address.fields.street`.
273
- if (ts.isQualifiedName(node) && node.right.text === "fields" && ts.isQualifiedName(node.parent) && node.parent.left === node) {
274
- if (isBindingType(checker, checker.getTypeAtLocation(node.left)) === true) {
275
- edits.add(node.left.getEnd(), node.getEnd(), "");
276
- }
277
- }
278
- ts.forEachChild(node, visit);
279
- };
280
- visit(sf);
281
- const text = sf.getFullText();
282
- return { text: edits.list.length === 0 ? text : edits.apply(text), refused };
283
- }
284
-
285
- /** @param {string} root @returns {Promise<{rewritten: string[], notRewritten: {file: string, reason: string}[]}>} */
286
- export default async function unwrapObjectFields(root) {
287
- const rewritten = [];
288
- const notRewritten = [];
289
- const name = (file) => relative(root, file).split(sep).join("/");
290
- const files = await sourceFiles(root);
291
- const texts = new Map();
292
- for (const file of files) texts.set(file, await readFile(file, "utf8"));
293
- // Only a file that reads `.fields` at all is a candidate; the program types it against
294
- // every file it imports.
295
- const candidates = files.filter((file) => /\bfields\b/.test(texts.get(file)));
296
- if (candidates.length === 0) return { rewritten, notRewritten };
297
- const built = program(files);
298
- const checker = built.getTypeChecker();
299
- for (const file of candidates) {
300
- const sf = built.getSourceFile(file);
301
- if (sf === undefined) continue;
302
- const result = rewrite(checker, sf, root);
303
- if (result.text !== texts.get(file)) {
304
- await writeFile(file, result.text, "utf8");
305
- rewritten.push(name(file));
306
- }
307
- for (const reason of new Set(result.refused)) notRewritten.push({ file: name(file), reason });
308
- }
309
- return { rewritten, notRewritten };
310
- }
@@ -1,131 +0,0 @@
1
- // 9.0.0 — `Slot.Document` is the document's embedded viewer; the link it rendered is
2
- // `Slot.Download`.
3
- //
4
- // Before this break `Slot.Document` rendered one anchor at the served file with the
5
- // author's children inside it. That anchor is now `Slot.Download`, widened to link the
6
- // original of an image or a video slot too, and `Slot.Document` embeds a PDF in place, as
7
- // `Slot.Video` and `Slot.Tour` embed theirs. A section that kept `Slot.Document` would
8
- // turn every download link into a viewer frame.
9
- //
10
- // What this codemod does, in every `.ts` and `.tsx` under the workspace, wherever `Slot`
11
- // is the one this package exports (imported by name, under an alias, or read off a
12
- // namespace import): `<Slot.Document …>…</Slot.Document>` becomes
13
- // `<Slot.Download …>…</Slot.Download>`, and so does every other read of the member —
14
- // `Slot.Document` handed on as a value, `typeof Slot.Document` in a type, and
15
- // `const { Document } = Slot`, which keeps its local name (`{ Download: Document }`).
16
- // Every prop the link took, `Slot.Download` takes, so a rewritten call renders the same
17
- // markup it did.
18
- //
19
- // What it hands back, by line: `Slot["Document"]`, a computed read it cannot name with
20
- // certainty — rewrite it to `Slot.Download` by hand.
21
-
22
- import { readdir, readFile, writeFile } from "node:fs/promises";
23
- import { join, relative } from "node:path";
24
-
25
- import ts from "typescript";
26
-
27
- const PACKAGE = "@homepages/concrete";
28
- const EXTENSIONS = [".ts", ".tsx"];
29
- const SKIP_DIRS = new Set(["node_modules", ".concrete", ".git", "dist", "build"]);
30
-
31
- async function sourceFiles(root) {
32
- const found = [];
33
- async function walk(dir) {
34
- for (const entry of await readdir(dir, { withFileTypes: true })) {
35
- if (entry.isDirectory()) {
36
- if (!SKIP_DIRS.has(entry.name)) await walk(join(dir, entry.name));
37
- } else if (EXTENSIONS.some((ext) => entry.name.endsWith(ext)) && !entry.name.endsWith(".d.ts")) {
38
- found.push(join(dir, entry.name));
39
- }
40
- }
41
- }
42
- await walk(root);
43
- return found.sort();
44
- }
45
-
46
- /** The local names this package's `Slot` is bound to, and the names of a namespace import of it. */
47
- function bindingsOf(source) {
48
- const slotNames = new Set();
49
- const namespaces = new Set();
50
- for (const statement of source.statements) {
51
- if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) continue;
52
- if (statement.moduleSpecifier.text !== PACKAGE) continue;
53
- const bindings = statement.importClause?.namedBindings;
54
- if (bindings === undefined) continue;
55
- if (ts.isNamespaceImport(bindings)) {
56
- namespaces.add(bindings.name.text);
57
- } else {
58
- for (const element of bindings.elements) {
59
- if ((element.propertyName ?? element.name).text === "Slot") slotNames.add(element.name.text);
60
- }
61
- }
62
- }
63
- return { slotNames, namespaces };
64
- }
65
-
66
- /** @param {string} root @returns {Promise<{rewritten: string[], notRewritten: {file: string, reason: string}[]}>} */
67
- export default async function viewerSlotDocument(root) {
68
- const rewritten = [];
69
- const notRewritten = [];
70
- for (const file of await sourceFiles(root)) {
71
- const text = await readFile(file, "utf8");
72
- if (!text.includes("Document")) continue;
73
- const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, file.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
74
- const { slotNames, namespaces } = bindingsOf(source);
75
- if (slotNames.size === 0 && namespaces.size === 0) continue;
76
- const rel = relative(root, file).split("\\").join("/");
77
-
78
- // `Slot` (or its alias), or `<namespace>.Slot`.
79
- const isSlot = (node) =>
80
- (ts.isIdentifier(node) && slotNames.has(node.text)) ||
81
- (ts.isPropertyAccessExpression(node) &&
82
- node.name.text === "Slot" &&
83
- ts.isIdentifier(node.expression) &&
84
- namespaces.has(node.expression.text)) ||
85
- (ts.isQualifiedName(node) && node.right.text === "Slot" && ts.isIdentifier(node.left) && namespaces.has(node.left.text));
86
-
87
- const edits = [];
88
- const visit = (node) => {
89
- if (ts.isPropertyAccessExpression(node) && node.name.text === "Document" && isSlot(node.expression)) {
90
- edits.push({ start: node.name.getStart(source), end: node.name.getEnd(), text: "Download" });
91
- } else if (ts.isQualifiedName(node) && node.right.text === "Document" && isSlot(node.left)) {
92
- edits.push({ start: node.right.getStart(source), end: node.right.getEnd(), text: "Download" });
93
- } else if (
94
- ts.isVariableDeclaration(node) &&
95
- ts.isObjectBindingPattern(node.name) &&
96
- node.initializer !== undefined &&
97
- isSlot(node.initializer)
98
- ) {
99
- for (const element of node.name.elements) {
100
- const key = element.propertyName ?? element.name;
101
- if (!ts.isIdentifier(key) || key.text !== "Document") continue;
102
- // `{ Document }` keeps its local name; `{ Document: Doc }` renames the key alone.
103
- const text = element.propertyName === undefined ? "Download: Document" : "Download";
104
- edits.push({ start: key.getStart(source), end: key.getEnd(), text });
105
- }
106
- } else if (
107
- ts.isElementAccessExpression(node) &&
108
- isSlot(node.expression) &&
109
- ts.isStringLiteralLike(node.argumentExpression) &&
110
- node.argumentExpression.text === "Document"
111
- ) {
112
- const { line } = source.getLineAndCharacterOfPosition(node.getStart(source));
113
- notRewritten.push({
114
- file: rel,
115
- reason: `line ${String(line + 1)}: \`Slot["Document"]\` — the link is \`Slot.Download\` now; \`Slot.Document\` embeds the file`,
116
- });
117
- }
118
- ts.forEachChild(node, visit);
119
- };
120
- visit(source);
121
- if (edits.length === 0) continue;
122
-
123
- let out = text;
124
- for (const edit of edits.sort((a, b) => b.start - a.start)) {
125
- out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);
126
- }
127
- await writeFile(file, out);
128
- rewritten.push(rel);
129
- }
130
- return { rewritten, notRewritten };
131
- }