tempo-sdk 0.0.99 → 0.0.102

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 (170) hide show
  1. package/README.md +3 -403
  2. package/dist/assets/editor.d.ts +43 -65
  3. package/dist/assets/editor.js +1 -573
  4. package/dist/assets/index.d.ts +11 -61
  5. package/dist/assets/index.js +1 -338
  6. package/dist/assets/parser.d.ts +68 -78
  7. package/dist/assets/parser.js +1 -33
  8. package/dist/astro/asset-preview-client.d.ts +3 -2
  9. package/dist/astro/asset-preview-client.js +1 -93
  10. package/dist/astro/controls.d.ts +1 -3
  11. package/dist/astro/controls.js +1 -7
  12. package/dist/astro/document-client.d.ts +5 -6
  13. package/dist/astro/document-client.js +1 -78
  14. package/dist/astro/runtime.d.ts +23 -11
  15. package/dist/astro/runtime.js +1 -86
  16. package/dist/astro.d.ts +19 -13
  17. package/dist/astro.js +1 -818
  18. package/dist/canvas/astro-contract.d.ts +0 -3
  19. package/dist/canvas/astro-contract.js +1 -9
  20. package/dist/canvas/astro.d.ts +3 -4
  21. package/dist/canvas/astro.js +1 -42
  22. package/dist/canvas/editor.d.ts +187 -183
  23. package/dist/canvas/editor.js +1 -1094
  24. package/dist/canvas/flutter-preview.d.ts +0 -1
  25. package/dist/canvas/flutter-preview.js +1 -9
  26. package/dist/canvas/index.d.ts +46 -100
  27. package/dist/canvas/index.js +1 -3926
  28. package/dist/canvas/interact-projection.d.ts +7 -5
  29. package/dist/canvas/interact-projection.js +1 -12
  30. package/dist/canvas/parser.d.ts +10 -303
  31. package/dist/canvas/parser.js +1 -30
  32. package/dist/canvas/svelte.d.ts +6 -7
  33. package/dist/canvas/svelte.js +1 -91
  34. package/dist/canvas/vue.d.ts +9 -49
  35. package/dist/canvas/vue.js +1 -264
  36. package/dist/chunk-CXCUJCXD.js +1 -0
  37. package/dist/chunk-FH6TMWFA.js +1 -0
  38. package/dist/chunk-FL7FSJSL.js +1 -0
  39. package/dist/chunk-GQIOB5SV.js +1 -0
  40. package/dist/chunk-HBQ7FFH7.js +1 -0
  41. package/dist/chunk-JRJOWLCN.js +1 -0
  42. package/dist/chunk-LJCBFTMP.js +1 -0
  43. package/dist/chunk-M3GN2KUH.js +1 -0
  44. package/dist/chunk-MPIHFFML.js +1 -0
  45. package/dist/chunk-T5TY3U2H.js +1 -0
  46. package/dist/chunk-XO2BSHWM.js +1 -0
  47. package/dist/chunk-XUSV3KOD.js +1 -0
  48. package/dist/chunk-ZXBMP6RV.js +1 -0
  49. package/dist/{controls-uCaQ3CNX.d.ts → controls-DKslABtM.d.ts} +0 -3
  50. package/dist/expo/plugin.cjs +1 -1928
  51. package/dist/expo/plugin.js +1 -8
  52. package/dist/expo-babel-plugin.cjs +1 -1928
  53. package/dist/expo-babel-plugin.d.cts +46 -40
  54. package/dist/expo-babel-plugin.d.ts +46 -40
  55. package/dist/expo-babel-plugin.js +1 -8
  56. package/dist/flutter-preview-path.d.ts +23 -7
  57. package/dist/flutter-preview-path.js +1 -16
  58. package/dist/index.d.ts +33 -45
  59. package/dist/index.js +1 -20
  60. package/dist/nextjs/plugin.cjs +1 -413
  61. package/dist/nextjs/plugin.js +1 -7
  62. package/dist/nextjs-loader.cjs +1 -2277
  63. package/dist/nextjs.cjs +1 -484
  64. package/dist/nextjs.d.cts +2 -58
  65. package/dist/nextjs.d.ts +2 -58
  66. package/dist/nextjs.js +1 -17
  67. package/dist/nuxt/runtime/identity.d.ts +2 -4
  68. package/dist/nuxt/runtime/identity.js +1 -18
  69. package/dist/nuxt.d.ts +31 -92
  70. package/dist/nuxt.js +1 -5854
  71. package/dist/{page-DwLnOM5d.d.ts → page-Bc8PekIX.d.ts} +1 -5
  72. package/dist/parser.d-MO5ciJ5n.d.ts +236 -0
  73. package/dist/{storyboard-CMJVBSXn.d.ts → storyboard.contract.d-UQ4MUYN5.d.ts} +3 -25
  74. package/dist/svelte.d.ts +8 -18
  75. package/dist/svelte.js +1 -917
  76. package/dist/types-CfUgM2w4.d.ts +57 -0
  77. package/dist/v1-client-compat-n0E0XxuX.d.ts +5 -0
  78. package/dist/vue.d.ts +17 -58
  79. package/dist/vue.js +1 -1501
  80. package/package.json +12 -62
  81. package/dist/assets/editor.js.map +0 -1
  82. package/dist/assets/index.js.map +0 -1
  83. package/dist/assets/parser.js.map +0 -1
  84. package/dist/astro/asset-preview-client.js.map +0 -1
  85. package/dist/astro/controls.js.map +0 -1
  86. package/dist/astro/document-client.js.map +0 -1
  87. package/dist/astro/runtime.js.map +0 -1
  88. package/dist/astro.js.map +0 -1
  89. package/dist/canvas/astro-contract.js.map +0 -1
  90. package/dist/canvas/astro.js.map +0 -1
  91. package/dist/canvas/editor.js.map +0 -1
  92. package/dist/canvas/flutter-preview.js.map +0 -1
  93. package/dist/canvas/index.js.map +0 -1
  94. package/dist/canvas/interact-projection.js.map +0 -1
  95. package/dist/canvas/parser.js.map +0 -1
  96. package/dist/canvas/svelte.js.map +0 -1
  97. package/dist/canvas/vue.js.map +0 -1
  98. package/dist/chunk-27WT3XUG.js +0 -455
  99. package/dist/chunk-27WT3XUG.js.map +0 -1
  100. package/dist/chunk-5HIIF354.js +0 -67
  101. package/dist/chunk-5HIIF354.js.map +0 -1
  102. package/dist/chunk-65B52AR7.js +0 -11
  103. package/dist/chunk-65B52AR7.js.map +0 -1
  104. package/dist/chunk-6HYKKP5N.js +0 -2658
  105. package/dist/chunk-6HYKKP5N.js.map +0 -1
  106. package/dist/chunk-6SOP4XU6.js +0 -1891
  107. package/dist/chunk-6SOP4XU6.js.map +0 -1
  108. package/dist/chunk-AFXE462X.js +0 -1253
  109. package/dist/chunk-AFXE462X.js.map +0 -1
  110. package/dist/chunk-BQPKOVI5.js +0 -115
  111. package/dist/chunk-BQPKOVI5.js.map +0 -1
  112. package/dist/chunk-CYDF4LYJ.js +0 -342
  113. package/dist/chunk-CYDF4LYJ.js.map +0 -1
  114. package/dist/chunk-CYQE3TLC.js +0 -37
  115. package/dist/chunk-CYQE3TLC.js.map +0 -1
  116. package/dist/chunk-DI2ZFAWL.js +0 -14
  117. package/dist/chunk-DI2ZFAWL.js.map +0 -1
  118. package/dist/chunk-EGRHWZRV.js +0 -1
  119. package/dist/chunk-EGRHWZRV.js.map +0 -1
  120. package/dist/chunk-FGWGY3G3.js +0 -157
  121. package/dist/chunk-FGWGY3G3.js.map +0 -1
  122. package/dist/chunk-HOBTDB6G.js +0 -112
  123. package/dist/chunk-HOBTDB6G.js.map +0 -1
  124. package/dist/chunk-I7VF4ZOV.js +0 -630
  125. package/dist/chunk-I7VF4ZOV.js.map +0 -1
  126. package/dist/chunk-JVVHU3A7.js +0 -1077
  127. package/dist/chunk-JVVHU3A7.js.map +0 -1
  128. package/dist/chunk-MIXQVPDH.js +0 -8606
  129. package/dist/chunk-MIXQVPDH.js.map +0 -1
  130. package/dist/chunk-MU7S7NU7.js +0 -183
  131. package/dist/chunk-MU7S7NU7.js.map +0 -1
  132. package/dist/chunk-OX2YKYSL.js +0 -13
  133. package/dist/chunk-OX2YKYSL.js.map +0 -1
  134. package/dist/chunk-PYAJHLXO.js +0 -903
  135. package/dist/chunk-PYAJHLXO.js.map +0 -1
  136. package/dist/chunk-SGN7BDRE.js +0 -16
  137. package/dist/chunk-SGN7BDRE.js.map +0 -1
  138. package/dist/chunk-SGTGDLOX.js +0 -285
  139. package/dist/chunk-SGTGDLOX.js.map +0 -1
  140. package/dist/chunk-T364NBR3.js +0 -1440
  141. package/dist/chunk-T364NBR3.js.map +0 -1
  142. package/dist/chunk-U66QI3EN.js +0 -1524
  143. package/dist/chunk-U66QI3EN.js.map +0 -1
  144. package/dist/chunk-WTXOWQ7N.js +0 -47
  145. package/dist/chunk-WTXOWQ7N.js.map +0 -1
  146. package/dist/chunk-X5DJKVBT.js +0 -1308
  147. package/dist/chunk-X5DJKVBT.js.map +0 -1
  148. package/dist/chunk-ZT7HJ6YU.js +0 -38
  149. package/dist/chunk-ZT7HJ6YU.js.map +0 -1
  150. package/dist/chunk-ZW26VZHX.js +0 -3169
  151. package/dist/chunk-ZW26VZHX.js.map +0 -1
  152. package/dist/controls-reader-5MFHYBZZ.js +0 -192
  153. package/dist/controls-reader-5MFHYBZZ.js.map +0 -1
  154. package/dist/expo/plugin.cjs.map +0 -1
  155. package/dist/expo/plugin.js.map +0 -1
  156. package/dist/expo-babel-plugin.cjs.map +0 -1
  157. package/dist/expo-babel-plugin.js.map +0 -1
  158. package/dist/flutter-preview-path.js.map +0 -1
  159. package/dist/index.js.map +0 -1
  160. package/dist/nextjs/plugin.cjs.map +0 -1
  161. package/dist/nextjs/plugin.js.map +0 -1
  162. package/dist/nextjs-loader.cjs.map +0 -1
  163. package/dist/nextjs.cjs.map +0 -1
  164. package/dist/nextjs.js.map +0 -1
  165. package/dist/nuxt/runtime/identity.js.map +0 -1
  166. package/dist/nuxt.js.map +0 -1
  167. package/dist/svelte.js.map +0 -1
  168. package/dist/types-C8OIU-kc.d.ts +0 -106
  169. package/dist/v1-client-compat-qxaXEDm_.d.ts +0 -23
  170. package/dist/vue.js.map +0 -1
package/dist/astro.js CHANGED
@@ -1,818 +1 @@
1
- import {
2
- annotateAstroSource,
3
- parseAstroSource
4
- } from "./chunk-U66QI3EN.js";
5
- import "./chunk-EGRHWZRV.js";
6
- import {
7
- MagicString
8
- } from "./chunk-JVVHU3A7.js";
9
- import {
10
- tempoVitePlugin
11
- } from "./chunk-6HYKKP5N.js";
12
- import "./chunk-PYAJHLXO.js";
13
- import "./chunk-DI2ZFAWL.js";
14
- import {
15
- TEMPO_HOST_IDENTITY_CAPABILITY_HEADER,
16
- TEMPO_HOST_IDENTITY_ENDPOINT,
17
- createTempoHostIdentity
18
- } from "./chunk-CYDF4LYJ.js";
19
- import "./chunk-BQPKOVI5.js";
20
- import "./chunk-FGWGY3G3.js";
21
- import {
22
- sourceVersionHash
23
- } from "./chunk-MU7S7NU7.js";
24
- import {
25
- componentFrameworkForStoryboard,
26
- parseCanvasFile
27
- } from "./chunk-AFXE462X.js";
28
- import "./chunk-5HIIF354.js";
29
- import "./chunk-WTXOWQ7N.js";
30
- import "./chunk-65B52AR7.js";
31
- import "./chunk-CYQE3TLC.js";
32
- import {
33
- astroStoryboardPath
34
- } from "./chunk-OX2YKYSL.js";
35
-
36
- // astro.ts
37
- import {
38
- closeSync as closeSync2,
39
- fstatSync as fstatSync2,
40
- openSync as openSync2,
41
- readFileSync as readFileSync3,
42
- realpathSync
43
- } from "fs";
44
- import { isAbsolute as isAbsolute3, relative as relative3, resolve as resolve3 } from "path";
45
- import { fileURLToPath as fileURLToPath2 } from "url";
46
- import { createRequire } from "module";
47
-
48
- // astro/compiler-adapter.ts
49
- import { parseSync } from "oxc-parser";
50
- function instrumentFrameworkModule(code, id, metadata, runtimeId) {
51
- const parsed = parseSync(`${id}.js`, code);
52
- if (parsed.errors.length) return;
53
- let name = "$$tempoFrameworkComponent";
54
- while (code.includes(name)) name += "_";
55
- const output = new MagicString(code);
56
- const bindings = /* @__PURE__ */ new Map();
57
- let wrapped = false;
58
- for (const node of parsed.program.body) {
59
- if (node.type === "ExportDefaultDeclaration") {
60
- const value = node.declaration;
61
- if (value.type === "Identifier") bindings.set(value.name, "default");
62
- else if ((value.type === "FunctionDeclaration" || value.type === "ClassDeclaration") && value.id)
63
- bindings.set(value.id.name, "default");
64
- else {
65
- output.prependLeft(value.start, `${name}(`);
66
- output.appendLeft(
67
- value.end,
68
- `, ${JSON.stringify({ ...metadata, exportName: "default" })})`
69
- );
70
- wrapped = true;
71
- }
72
- } else if (node.type === "ExportNamedDeclaration" && !node.source) {
73
- const value = node.declaration;
74
- if (value?.type === "VariableDeclaration") {
75
- for (const declaration of value.declarations)
76
- if (declaration.id.type === "Identifier")
77
- bindings.set(declaration.id.name, declaration.id.name);
78
- } else if ((value?.type === "FunctionDeclaration" || value?.type === "ClassDeclaration") && value.id)
79
- bindings.set(value.id.name, value.id.name);
80
- for (const specifier of node.specifiers)
81
- if (specifier.local.type === "Identifier")
82
- bindings.set(
83
- specifier.local.name,
84
- specifier.exported.type === "Identifier" ? specifier.exported.name : specifier.exported.value
85
- );
86
- }
87
- }
88
- if (!wrapped && !bindings.size) return;
89
- output.prepend(
90
- `import { instrumentFrameworkComponent as ${name} } from ${JSON.stringify(runtimeId)};
91
- `
92
- );
93
- for (const [binding, exportName] of bindings)
94
- output.append(
95
- `
96
- ${name}(${binding}, ${JSON.stringify({ ...metadata, exportName })});`
97
- );
98
- return {
99
- code: output.toString(),
100
- map: output.generateMap({ source: id, includeContent: true, hires: true })
101
- };
102
- }
103
- function instrumentAstroModule(code, id, metadata, runtimeId, occurrenceFactory) {
104
- const parsed = parseSync(`${id}.js`, code);
105
- if (parsed.errors.length)
106
- throw new Error(`Tempo could not parse Astro's compiled module: ${id}`);
107
- const output = new MagicString(code);
108
- let prefix = "$$tempo";
109
- while (code.includes(prefix)) prefix += "_";
110
- const wrappers = [];
111
- let hasFactory = false;
112
- for (const node of parsed.program.body) {
113
- if (node.type !== "ImportDeclaration") continue;
114
- const runtime = node.source.value;
115
- if (runtime !== "astro/runtime/server/index.js" && runtime !== "astro/compiler-runtime" && runtime !== "astro/runtime/compiler/index.js" && !runtime.endsWith("/astro/dist/runtime/compiler/index.js"))
116
- continue;
117
- for (const specifier of node.specifiers) {
118
- if (specifier.type !== "ImportSpecifier" || specifier.imported.type !== "Identifier")
119
- continue;
120
- const imported = specifier.imported.name;
121
- if (imported !== "createComponent" && imported !== "renderComponent")
122
- continue;
123
- if (imported === "createComponent" && !metadata) {
124
- hasFactory = true;
125
- continue;
126
- }
127
- const local = specifier.local;
128
- const original = `${prefix}_${imported}`;
129
- output.overwrite(
130
- specifier.start,
131
- specifier.end,
132
- `${imported} as ${original}`
133
- );
134
- const helper = imported === "createComponent" ? "instrumentCreateComponent" : "instrumentRenderComponent";
135
- wrappers.push(
136
- `const ${local.name} = ${prefix}_${helper}(${original}${imported === "createComponent" ? `, ${JSON.stringify(metadata)}` : ""});`
137
- );
138
- if (imported === "createComponent") hasFactory = true;
139
- }
140
- }
141
- if (!hasFactory)
142
- throw new Error(
143
- `Unsupported Astro compiler output for ${id}; Tempo requires Astro 7 createComponent (${parsed.program.body.filter((n) => n.type === "ImportDeclaration").map((n) => n.source.value).join(", ")})`
144
- );
145
- output.prepend(
146
- `import { astroHostId as ${occurrenceFactory}, instrumentCreateComponent as ${prefix}_instrumentCreateComponent, instrumentRenderComponent as ${prefix}_instrumentRenderComponent } from ${JSON.stringify(runtimeId)};
147
- ${wrappers.join("\n")}
148
- `
149
- );
150
- return {
151
- code: output.toString(),
152
- map: output.generateMap({ source: id, includeContent: true, hires: true })
153
- };
154
- }
155
-
156
- // astro/storyboards.ts
157
- import { createHash } from "crypto";
158
- import {
159
- existsSync,
160
- readFileSync,
161
- readdirSync,
162
- mkdirSync,
163
- writeFileSync,
164
- openSync,
165
- closeSync,
166
- fstatSync
167
- } from "fs";
168
- import { dirname, isAbsolute, join, relative, resolve } from "path";
169
- import { fileURLToPath } from "url";
170
-
171
- // astro/json.ts
172
- import { parseSync as parseSync2 } from "oxc-parser";
173
- function readAstroStoryboardProps(expression) {
174
- if (!expression) return {};
175
- const parsed = parseSync2("props.ts", `(${expression})`);
176
- if (parsed.errors.length)
177
- throw new Error("Astro storyboard props must be a JSON object literal");
178
- const read = (node) => {
179
- if (node?.type === "ParenthesizedExpression") return read(node.expression);
180
- if (node?.type === "Literal" && (node.value === null || ["string", "boolean"].includes(typeof node.value) || typeof node.value === "number" && Number.isFinite(node.value)))
181
- return node.value;
182
- if (node?.type === "UnaryExpression" && ["-", "+"].includes(node.operator) && node.argument?.type === "Literal" && typeof node.argument.value === "number" && Number.isFinite(node.argument.value))
183
- return node.operator === "-" ? -node.argument.value : node.argument.value;
184
- if (node?.type === "ArrayExpression") return node.elements.map(read);
185
- if (node?.type === "ObjectExpression") {
186
- const value2 = /* @__PURE__ */ Object.create(null);
187
- for (const property of node.properties) {
188
- if (property.type !== "Property" || property.computed || property.method || property.shorthand || property.kind !== "init")
189
- throw new Error(
190
- "Astro storyboard props cannot contain expressions, spreads or getters"
191
- );
192
- const key = property.key.type === "Identifier" ? property.key.name : property.key.value;
193
- if (typeof key !== "string" && typeof key !== "number")
194
- throw new Error("Astro storyboard props require literal keys");
195
- value2[key] = read(property.value);
196
- }
197
- return value2;
198
- }
199
- throw new Error(
200
- "Astro storyboard props must be static JSON; use an authored .astro fixture for server data or slots"
201
- );
202
- };
203
- const statement = parsed.program.body[0];
204
- const value = read(
205
- statement?.type === "ExpressionStatement" ? statement.expression : void 0
206
- );
207
- if (!value || typeof value !== "object" || Array.isArray(value))
208
- throw new Error("Astro storyboard props must be a JSON object literal");
209
- return value;
210
- }
211
-
212
- // astro/storyboards.ts
213
- import { parseSync as parseSync3 } from "oxc-parser";
214
- var revisionClient = `<script>
215
- const hot = import.meta.hot;
216
- if (hot) {
217
- const receipt = () => JSON.parse(document.querySelector('meta[name="tempo-astro-storyboard"]')?.getAttribute('content') ?? 'null');
218
- const check = () => hot.send('tempo:astro:revision-request', { path: location.pathname, revision: receipt()?.revision });
219
- const accept = (data) => {
220
- if (data.path === location.pathname && data.revision !== receipt()?.revision) location.reload();
221
- };
222
- hot.on('tempo:astro:revision', accept);
223
- hot.on('vite:ws:connect', check);
224
- check();
225
- hot.dispose(() => {
226
- hot.off('tempo:astro:revision', accept);
227
- hot.off('vite:ws:connect', check);
228
- });
229
- }
230
- </script>`;
231
- function filesUnder(root) {
232
- if (!existsSync(root)) return [];
233
- return readdirSync(root, { withFileTypes: true }).flatMap((entry) => {
234
- if (entry.isSymbolicLink()) return [];
235
- const file = join(root, entry.name);
236
- return entry.isDirectory() ? filesUnder(file) : entry.name.endsWith(".canvas.tsx") ? [file] : [];
237
- });
238
- }
239
- function collectAstroStoryboards(root, canvasesRoot, generatedRoot, styles = []) {
240
- const routes = [];
241
- for (const canvasFile of new Set(
242
- (Array.isArray(canvasesRoot) ? canvasesRoot : [canvasesRoot]).flatMap(
243
- filesUnder
244
- )
245
- )) {
246
- const fd = openSync(canvasFile, "r");
247
- let source, modifiedTs;
248
- try {
249
- const before = fstatSync(fd);
250
- source = readFileSync(fd, "utf8");
251
- const after = fstatSync(fd);
252
- if (!["mtimeMs", "ctimeMs", "size", "ino", "dev"].every(
253
- (key) => before[key] === after[key]
254
- ))
255
- throw new Error(`Canvas changed while reading: ${canvasFile}`);
256
- modifiedTs = Math.trunc(before.mtimeMs);
257
- } finally {
258
- closeSync(fd);
259
- }
260
- const canvas = parseCanvasFile(canvasFile, source);
261
- const canvasPath = canvas.canvasPath ?? relative(root, dirname(canvasFile)).replaceAll("\\", "/");
262
- for (const storyboard of canvas.storyboards) {
263
- if (componentFrameworkForStoryboard(storyboard) !== "astro") continue;
264
- const path = astroStoryboardPath(canvasPath, storyboard.storyboardKey);
265
- const file = join(
266
- generatedRoot,
267
- `${createHash("sha256").update(path).digest("hex")}.astro`
268
- );
269
- const revision = createHash("sha256").update(source).digest("hex");
270
- let generated;
271
- try {
272
- if (canvas.errors.some((error) => error.kind === "structural") || storyboard.errors.length)
273
- throw new Error(
274
- "Fix the Astro storyboard's canvas declaration before rendering it"
275
- );
276
- const imported = storyboard.component?.import;
277
- if (!imported || imported.kind !== "default" || !imported.source.endsWith(".astro?tempo-component"))
278
- throw new Error(
279
- "AstroStoryboard requires a default .astro?tempo-component import; use an authored .astro fixture for slots and server data"
280
- );
281
- const module = imported.source.slice(0, -"?tempo-component".length);
282
- const specifier = module.startsWith(".") ? resolve(dirname(canvasFile), module).replaceAll("\\", "/") : module;
283
- const props = JSON.stringify(
284
- readAstroStoryboardProps(storyboard.props?.expression)
285
- ).replaceAll("<", "\\u003c");
286
- const callsite = JSON.stringify({
287
- filepath: relative(root, canvasFile).replaceAll("\\", "/"),
288
- sourceVersion: sourceVersionHash(source),
289
- modifiedTs,
290
- position: storyboard.jsxElementSpan.start,
291
- name: storyboard.component?.localName ?? "Component"
292
- });
293
- const receipt = JSON.stringify({
294
- canvasPath,
295
- storyboardId: storyboard.storyboardKey,
296
- revision
297
- });
298
- let preview;
299
- if (canvasFile.replaceAll("\\", "/").includes("/.tempo/asset-edit-previews/")) {
300
- for (const statement of parseSync3(canvasFile, source).program.body) {
301
- if (statement.type !== "ExportNamedDeclaration" || statement.declaration?.type !== "VariableDeclaration")
302
- continue;
303
- for (const declaration of statement.declaration.declarations)
304
- if (declaration.id.type === "Identifier" && declaration.id.name === "__tempoAstroAssetPreview" && declaration.init)
305
- preview = readAstroStoryboardProps(
306
- source.slice(declaration.init.start, declaration.init.end)
307
- );
308
- }
309
- }
310
- generated = `---
311
- import Component from ${JSON.stringify(specifier)};
312
- import ComponentMetadata from ${JSON.stringify(specifier + "?tempo-component")};
313
- ${styles.map((file2) => `import ${JSON.stringify(file2.replaceAll("\\", "/"))};`).join("\n")}
314
- const props = ${props};
315
- const controls = JSON.stringify(ComponentMetadata.__tempoAstroControls ?? {});
316
- ---
317
- <!doctype html><html><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="tempo-project-root" content={${JSON.stringify(root)}} /><meta name="tempo-astro-storyboard" content={${JSON.stringify(receipt)}} /></head><body style="margin:0"><Component {...props} __tempo_astro_callsite__={${callsite}} /><pre hidden data-asset-definition={controls}>Component controls</pre></body></html>`;
318
- if (preview) {
319
- const client = fileURLToPath(
320
- new URL(
321
- import.meta.url.endsWith(".ts") ? "./asset-preview-client.ts" : "./astro/asset-preview-client.js",
322
- import.meta.url
323
- )
324
- );
325
- generated = generated.replace(
326
- `const props = ${props};`,
327
- `const preview = ${JSON.stringify(preview).replaceAll("<", "\\u003c")};
328
- const raw = Astro.url.searchParams.get("__tempo_asset_update");
329
- if (raw && raw.length > 64000) throw new Error("Astro preview props are too large");
330
- const update = raw ? JSON.parse(raw) : {variant:null,edits:{}};
331
- if (!(update.variant === null || typeof update.variant === "string") || !update.edits || typeof update.edits !== "object" || Array.isArray(update.edits)) throw new Error("Invalid Astro preview props");
332
- const variant = update.variant !== null && Object.hasOwn(preview.asset.variants,update.variant) ? preview.asset.variants[update.variant] : undefined;
333
- if (update.variant !== null && (!variant || variant.error)) throw new Error(variant?.error ?? "The Astro asset variant no longer exists");
334
- const props = {...variant?.props};
335
- for (const [key,value] of Object.entries(update.edits)) { if(value && typeof value === "object" && Object.keys(value).length===1 && value.__tempo_omit_prop__===true) delete props[key]; else Object.defineProperty(props,key,{value,enumerable:true,configurable:true}); }
336
- const assetMetadata = JSON.stringify({sessionId:preview.sessionId,metadata:{asset:preview.asset,...ComponentMetadata.__tempoAstroControls}});`
337
- ).replace(
338
- "</head>",
339
- `<meta name="tempo-astro-asset-preview" content={assetMetadata} /></head>`
340
- ).replace(
341
- `<Component {...props} __tempo_astro_callsite__={${callsite}} />`,
342
- `{update.variant !== null && <Component {...props} __tempo_astro_callsite__={${callsite}} />}`
343
- ).replace(
344
- "</body>",
345
- `<script>import {startAstroAssetPreview} from ${JSON.stringify(client)}; startAstroAssetPreview();</script></body>`
346
- );
347
- }
348
- } catch (error) {
349
- generated = `---
350
- throw new Error(${JSON.stringify(error instanceof Error ? error.message : String(error))});
351
- ---`;
352
- }
353
- generated = generated.replace("</body>", `${revisionClient}</body>`);
354
- routes.push({ path, file, source: generated, revision });
355
- }
356
- }
357
- const seen = /* @__PURE__ */ new Set();
358
- for (const route of routes) {
359
- if (seen.has(route.path))
360
- throw new Error(`Duplicate Astro storyboard address: ${route.path}`);
361
- seen.add(route.path);
362
- }
363
- return routes;
364
- }
365
- function writeChanged(file, source) {
366
- const exists = existsSync(file);
367
- if (exists && readFileSync(file, "utf8") === source) return;
368
- mkdirSync(dirname(file), { recursive: true });
369
- writeFileSync(file, source);
370
- return exists ? "updated" : "created";
371
- }
372
- function storyboardEntrypoint(registryFile) {
373
- return String.raw`---
374
- import { readFileSync } from "node:fs";
375
- import { createComponent } from "astro/runtime/server/index.js";
376
- const base = import.meta.env.BASE_URL.replace(/\/$/, "");
377
- const pathname = Astro.url.pathname.slice(base.length).replace(/\/$/, "");
378
- const routes = JSON.parse(readFileSync(${JSON.stringify(registryFile)}, "utf8"));
379
- const route = routes.find((entry) => entry.path === pathname);
380
- if (!route) return new Response("Astro storyboard not found", { status: 404 });
381
- // Do not turn these into a glob or a static import map: unopened boards may
382
- // contain broken imports, and their global CSS must never enter this document.
383
- const { default: assets } = await import(/* @vite-ignore */ route.file + "?astroPropagatedAssets");
384
- const { default: Page } = await assets.getMod();
385
- const Preview = createComponent((result, props, slots) => {
386
- // The generated document owns its <head>. It was loaded during frontmatter,
387
- // after Astro computed the dispatch page's static head metadata.
388
- result._metadata.headInTree = true;
389
- result._metadata.routeHasPropagation = true;
390
- for (const style of assets.collectedStyles) {
391
- result.styles.add({ props: { "data-vite-dev-id": style.id }, children: style.content });
392
- const src = style.id.startsWith("/@id/") ? style.id : "/@fs/" + style.id.replace(/^\//, "");
393
- result.scripts.add({ props: { type: "module", src: base + src }, children: "" });
394
- }
395
- for (const href of assets.collectedLinks) {
396
- result.links.add({ props: { rel: "stylesheet", href }, children: "" });
397
- }
398
- return Page(result, props, slots);
399
- });
400
- ---
401
- <Preview />`;
402
- }
403
- function createAstroStoryboardRegistry(root, canvasesRoot, generatedRoot, styles = []) {
404
- const roots = Array.isArray(canvasesRoot) ? canvasesRoot : [canvasesRoot];
405
- const routes = collectAstroStoryboards(root, roots, generatedRoot, styles);
406
- let currentRoutes = routes;
407
- const registryFile = join(generatedRoot, "routes.json");
408
- const entrypoint = join(generatedRoot, "storyboards.astro");
409
- const shape = (items) => JSON.stringify(
410
- items.map(({ path, file }) => ({
411
- path,
412
- file: file.replaceAll("\\", "/")
413
- }))
414
- );
415
- const unmodifiedNewFiles = /* @__PURE__ */ new Set();
416
- const writeDocument = (route) => {
417
- const change = writeChanged(route.file, route.source);
418
- const file = route.file.replaceAll("\\", "/");
419
- if (change === "created") unmodifiedNewFiles.add(file);
420
- else if (change === "updated") unmodifiedNewFiles.delete(file);
421
- return change;
422
- };
423
- for (const route of routes) writeDocument(route);
424
- writeChanged(registryFile, shape(routes));
425
- writeChanged(entrypoint, storyboardEntrypoint(registryFile));
426
- let synchronizeCanvas;
427
- const plugin = {
428
- name: "tempo:astro-storyboards",
429
- hotUpdate: {
430
- order: "pre",
431
- async handler({ type, file, modules, read }) {
432
- if (this.environment.name === "client" && file.endsWith(".canvas.tsx")) {
433
- if (type !== "delete") await read();
434
- synchronizeCanvas?.(file);
435
- }
436
- if (type === "create" && unmodifiedNewFiles.has(file))
437
- return modules.filter((module) => module.file !== file);
438
- }
439
- },
440
- configureServer(server) {
441
- const changed = (file) => {
442
- if (!file.endsWith(".canvas.tsx") || !roots.some((root2) => {
443
- const path = relative(root2, file);
444
- return !isAbsolute(path) && !path.startsWith("../");
445
- }))
446
- return;
447
- try {
448
- const next = collectAstroStoryboards(
449
- root,
450
- roots,
451
- generatedRoot,
452
- styles
453
- );
454
- const updatedFiles = next.filter((route) => writeDocument(route) === "updated").map((route) => route.file);
455
- const nextFiles = new Set(
456
- next.map((route) => route.file.replaceAll("\\", "/"))
457
- );
458
- for (const file2 of unmodifiedNewFiles)
459
- if (!nextFiles.has(file2)) unmodifiedNewFiles.delete(file2);
460
- currentRoutes = next;
461
- writeChanged(registryFile, shape(next));
462
- for (const file2 of updatedFiles) server.watcher.emit("change", file2);
463
- } catch (error) {
464
- server.config.logger.error(String(error));
465
- }
466
- };
467
- synchronizeCanvas = changed;
468
- server.watcher.add(roots);
469
- const verifyRevision = (data, client) => {
470
- if (typeof data?.path !== "string" || typeof data.revision !== "string")
471
- return;
472
- const base = server.config.base.replace(/\/$/, "");
473
- const pathname = base && data.path.startsWith(`${base}/`) ? data.path.slice(base.length) : data.path;
474
- const route = currentRoutes.find((route2) => route2.path === pathname);
475
- if (route)
476
- client.send({
477
- type: "custom",
478
- event: "tempo:astro:revision",
479
- data: { path: data.path, revision: route.revision }
480
- });
481
- };
482
- server.ws.on("tempo:astro:revision-request", verifyRevision);
483
- const dispose = () => {
484
- server.ws.off("tempo:astro:revision-request", verifyRevision);
485
- };
486
- server.httpServer?.once("close", dispose);
487
- }
488
- };
489
- return { routes, registryFile, entrypoint, plugin };
490
- }
491
-
492
- // astro/project-context.ts
493
- import { existsSync as existsSync2, readFileSync as readFileSync2, readdirSync as readdirSync2 } from "fs";
494
- import { dirname as dirname2, join as join2, resolve as resolve2 } from "path";
495
- function astroProjectContext(appRoot, rootOverride, canvasesOverride) {
496
- let root = resolve2(rootOverride ?? appRoot);
497
- if (!rootOverride) {
498
- for (let candidate = root; ; candidate = dirname2(candidate)) {
499
- const file = join2(candidate, "tempo/tempo.config.json");
500
- if (existsSync2(file)) {
501
- const config2 = JSON.parse(readFileSync2(file, "utf8"));
502
- if (candidate === appRoot || resolve2(
503
- candidate,
504
- config2.apps?.[0]?.appDir ?? config2.appDir ?? "."
505
- ) === appRoot) {
506
- root = candidate;
507
- break;
508
- }
509
- }
510
- if (dirname2(candidate) === candidate) break;
511
- }
512
- }
513
- const tempoRoot = join2(root, "tempo");
514
- const configFile = join2(tempoRoot, "tempo.config.json");
515
- const config = existsSync2(configFile) ? JSON.parse(readFileSync2(configFile, "utf8")) : {};
516
- return {
517
- root,
518
- tempoRoot,
519
- canvasesRoot: canvasesOverride ? resolve2(root, canvasesOverride) : resolve2(tempoRoot, config.paths?.canvases ?? "designs")
520
- };
521
- }
522
- function discoverAstroStyles(appRoot) {
523
- const styles = /* @__PURE__ */ new Set();
524
- const scan = (directory, depth) => {
525
- if (!existsSync2(directory) || depth > 5) return;
526
- for (const entry of readdirSync2(directory, { withFileTypes: true })) {
527
- if (entry.isSymbolicLink()) continue;
528
- const file = join2(directory, entry.name);
529
- if (entry.isDirectory()) scan(file, depth + 1);
530
- else if (entry.name.endsWith(".astro")) {
531
- const source = readFileSync2(file, "utf8");
532
- const parsed = parseAstroSource(source);
533
- if (parsed.kind !== "ok") continue;
534
- for (const declaration of parsed.imports) {
535
- const specifier = declaration.source?.value;
536
- if (typeof specifier !== "string" || !specifier.endsWith(".css") || specifier.endsWith(".module.css"))
537
- continue;
538
- const style = specifier.startsWith(".") ? resolve2(dirname2(file), specifier) : specifier;
539
- if (!specifier.startsWith(".") || existsSync2(style))
540
- styles.add(style);
541
- }
542
- }
543
- }
544
- };
545
- scan(join2(appRoot, "src/layouts"), 0);
546
- if (!styles.size) scan(join2(appRoot, "src/pages"), 0);
547
- if (!styles.size)
548
- for (const file of [
549
- "src/styles/global.css",
550
- "src/styles/tailwind.css",
551
- "src/styles.css",
552
- "src/index.css"
553
- ]) {
554
- const candidate = resolve2(appRoot, file);
555
- if (existsSync2(candidate)) {
556
- styles.add(candidate);
557
- break;
558
- }
559
- }
560
- return [...styles];
561
- }
562
-
563
- // astro/tailwind.ts
564
- import { isAbsolute as isAbsolute2, relative as relative2 } from "path";
565
- function astroTailwindSources(root, sources) {
566
- return {
567
- name: "tempo:astro-tailwind-sources",
568
- enforce: "pre",
569
- transform: {
570
- order: "pre",
571
- handler(code, id) {
572
- const file = id.split("?")[0];
573
- if (!file.endsWith(".css") || file.replaceAll("\\", "/").includes("/node_modules/"))
574
- return;
575
- const path = relative2(root, file);
576
- if (path.startsWith("..") || isAbsolute2(path)) return;
577
- if (!/@import\s+(?:url\(\s*)?["']tailwindcss(?:\/[\w.-]+)?["']/.test(code))
578
- return;
579
- return {
580
- code: `${code}
581
- ${sources.map((directory) => `@source ${JSON.stringify(directory.replaceAll("\\", "/"))};`).join("\n")}
582
- `,
583
- map: null
584
- };
585
- }
586
- }
587
- };
588
- }
589
-
590
- // astro.ts
591
- function tempoAstro(options = {}) {
592
- return {
593
- name: "tempo-astro",
594
- hooks: {
595
- "astro:config:setup"({
596
- config,
597
- command,
598
- updateConfig,
599
- injectRoute,
600
- createCodegenDir,
601
- injectScript
602
- }) {
603
- if (command !== "dev" || !(options.enabled ?? Boolean(process.env.TEMPO)))
604
- return;
605
- const [nodeMajor, nodeMinor] = process.versions.node.split(".").map(Number);
606
- if (nodeMajor < 22 || nodeMajor === 22 && nodeMinor < 12)
607
- throw new Error("Tempo Astro support requires Node 22.12 or newer");
608
- const appRequire = createRequire(new URL("package.json", config.root));
609
- const version = appRequire("astro/package.json").version;
610
- if (!version.startsWith("7."))
611
- throw new Error(
612
- `Tempo native Astro support requires Astro 7; this app uses ${version}`
613
- );
614
- const appRoot = realpathSync.native(fileURLToPath2(config.root));
615
- const { root, tempoRoot, canvasesRoot } = astroProjectContext(
616
- appRoot,
617
- options.root,
618
- options.canvasesRoot
619
- );
620
- const generatedRoot = fileURLToPath2(createCodegenDir());
621
- const canvasRoots = [
622
- canvasesRoot,
623
- resolve3(tempoRoot, ".tempo/library-canvases"),
624
- resolve3(tempoRoot, ".tempo/asset-edit-previews")
625
- ];
626
- const registry = createAstroStoryboardRegistry(
627
- root,
628
- canvasRoots,
629
- generatedRoot,
630
- options.styles?.map((file) => resolve3(appRoot, file)) ?? discoverAstroStyles(appRoot)
631
- );
632
- injectRoute({
633
- pattern: "/__tempo/astro/[...storyboard]",
634
- entrypoint: registry.entrypoint,
635
- prerender: false
636
- });
637
- injectScript(
638
- "head-inline",
639
- `if(!document.querySelector('meta[name="tempo-project-root"]')){const m=document.createElement('meta');m.name='tempo-project-root';m.content=${JSON.stringify(root).replaceAll("<", "\\u003c")};document.head.append(m)}`
640
- );
641
- const documentClient = fileURLToPath2(
642
- new URL(
643
- import.meta.url.endsWith(".ts") ? "./astro/document-client.ts" : "./astro/document-client.js",
644
- import.meta.url
645
- )
646
- );
647
- injectScript(
648
- "page",
649
- `import { startAstroDocumentClient } from ${JSON.stringify(documentClient)}; startAstroDocumentClient(import.meta.hot);`
650
- );
651
- const identity = {
652
- name: "tempo:astro-identity",
653
- // The generic annotation plugin also serves /__tempo/identity.
654
- // Register Astro's capability first, before its pre-enforced middleware.
655
- enforce: "pre",
656
- configureServer(server) {
657
- server.middlewares.use((req, res, next) => {
658
- if (req.method !== "GET" || req.url?.split("?")[0] !== TEMPO_HOST_IDENTITY_ENDPOINT)
659
- return next();
660
- res.setHeader(TEMPO_HOST_IDENTITY_CAPABILITY_HEADER, "1");
661
- res.setHeader("Cache-Control", "no-store");
662
- res.setHeader("Content-Type", "application/json");
663
- res.end(
664
- JSON.stringify({
665
- ...createTempoHostIdentity("astro", {
666
- root: tempoRoot,
667
- pluginActive: true
668
- }),
669
- capabilities: { astroComponents: 1 }
670
- })
671
- );
672
- });
673
- }
674
- };
675
- updateConfig({
676
- vite: {
677
- plugins: [
678
- identity,
679
- astroTailwindSources(root, [
680
- ...canvasRoots,
681
- // Request-time registry data contains paths, never utilities.
682
- // Scanning it makes Tailwind reload pages on every board add.
683
- resolve3(generatedRoot, "*.astro")
684
- ]),
685
- ...astroAnnotationPlugins(root, generatedRoot),
686
- tempoVitePlugin({ root, enabled: true }),
687
- registry.plugin
688
- ]
689
- }
690
- });
691
- }
692
- }
693
- };
694
- }
695
- function astroAnnotationPlugins(root, generatedRoot) {
696
- const environments = /* @__PURE__ */ new WeakMap();
697
- const receiptMap = (environment) => {
698
- let map = environments.get(environment);
699
- if (!map) {
700
- map = /* @__PURE__ */ new Map();
701
- environments.set(environment, map);
702
- }
703
- return map;
704
- };
705
- const runtime = fileURLToPath2(new URL("./astro/runtime.js", import.meta.url));
706
- const runtimeId = import.meta.url.endsWith(".ts") ? runtime.replace(/\.js$/, ".ts") : runtime;
707
- return [
708
- {
709
- name: "tempo:astro-source",
710
- enforce: "pre",
711
- transform: {
712
- order: "pre",
713
- handler(source, id, options) {
714
- const astro = id.endsWith(".astro");
715
- const framework = options?.ssr && /\.[jt]sx?$/.test(id);
716
- if (!astro && !framework || id.includes("?") || !isAbsolute3(id))
717
- return;
718
- const receipts = receiptMap(this.environment);
719
- receipts.delete(id);
720
- let physical;
721
- try {
722
- physical = realpathSync.native(id);
723
- } catch {
724
- return;
725
- }
726
- if (generatedRoot && !relative3(generatedRoot, physical).startsWith(".."))
727
- return;
728
- const filepath = relative3(root, physical).replaceAll("\\", "/");
729
- if (!filepath || filepath.startsWith("../") || isAbsolute3(filepath) || filepath.split("/").includes("node_modules"))
730
- return;
731
- const fd = openSync2(physical, "r");
732
- let metadata;
733
- try {
734
- const before = fstatSync2(fd);
735
- const raw = readFileSync3(fd, "utf8");
736
- const after = fstatSync2(fd);
737
- if (source !== raw || !["mtimeMs", "ctimeMs", "size", "ino", "dev"].every(
738
- (key) => before[key] === after[key]
739
- ))
740
- return;
741
- const parsed = astro ? parseAstroSource(source) : null;
742
- if (parsed && parsed.kind !== "ok") return;
743
- metadata = {
744
- filepath,
745
- sourceVersion: parsed?.sourceVersion ?? sourceVersionHash(source),
746
- modifiedTs: Math.trunc(before.mtimeMs)
747
- };
748
- } finally {
749
- closeSync2(fd);
750
- }
751
- if (framework) {
752
- receipts.set(id, { metadata });
753
- return;
754
- }
755
- const transformed = annotateAstroSource(source, metadata, id);
756
- if (transformed.kind !== "ok") this.error(transformed.message);
757
- receipts.set(id, {
758
- metadata,
759
- occurrenceFactory: transformed.occurrenceFactory
760
- });
761
- return { code: transformed.code, map: transformed.map };
762
- }
763
- }
764
- },
765
- {
766
- name: "tempo:astro-compiled",
767
- enforce: "post",
768
- transform: {
769
- order: "post",
770
- handler(code, id) {
771
- if (generatedRoot && id.endsWith(".astro") && !relative3(generatedRoot, id).startsWith("..")) {
772
- return instrumentAstroModule(
773
- code,
774
- id,
775
- null,
776
- runtimeId,
777
- "$$tempoStoryboardHostId"
778
- );
779
- }
780
- const receipts = receiptMap(this.environment);
781
- const receipt = receipts.get(id);
782
- if (!receipt) return;
783
- receipts.delete(id);
784
- if (!receipt.occurrenceFactory)
785
- return instrumentFrameworkModule(
786
- code,
787
- id,
788
- receipt.metadata,
789
- runtimeId
790
- );
791
- return instrumentAstroModule(
792
- code,
793
- id,
794
- receipt.metadata,
795
- runtimeId,
796
- receipt.occurrenceFactory
797
- );
798
- }
799
- }
800
- }
801
- ];
802
- }
803
- var astro_default = tempoAstro;
804
- function withTempoAstro(config) {
805
- if (config instanceof Promise)
806
- return config.then((value) => withTempoAstro(value));
807
- return {
808
- ...config,
809
- integrations: [...config.integrations ?? [], tempoAstro()]
810
- };
811
- }
812
- export {
813
- astroAnnotationPlugins,
814
- astro_default as default,
815
- tempoAstro,
816
- withTempoAstro
817
- };
818
- //# sourceMappingURL=astro.js.map
1
+ import{a as n,b as e}from"./chunk-ZXBMP6RV.js";import{a as r}from"./chunk-XUSV3KOD.js";import{fileURLToPath as a}from"url";var s=r(function(t={}){return{name:"tempo-astro",hooks:{"astro:config:setup":r(function(o){return o.command!=="dev"||!(t.enabled??!!process.env.TEMPO)?void 0:n("astro",a(o.config.root)).tempoAstro(t).hooks["astro:config:setup"]?.call(this,o)},"astro:config:setup")}}},"tempoAstro"),f=e("astro","astroAnnotationPlugins"),i=r((t=>t instanceof Promise?t.then(o=>i(o)):{...t,integrations:[...t.integrations??[],s()]}),"withTempoAstro"),u=s;export{f as astroAnnotationPlugins,u as default,s as tempoAstro,i as withTempoAstro};