@astro-spec/toolbar 0.0.0-stage → 1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 otoneko.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,35 @@
1
- # Temporary Holding Version
1
+ # @astro-spec/toolbar
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > Try Astro Actions from the Astro Dev Toolbar
4
+
5
+ Adds an Actions app to the [Astro Dev Toolbar](https://docs.astro.build/en/guides/dev-toolbar/). It lists the actions in `src/actions`, builds a form from each action's input schema, calls the action and shows the response. Successful results are decoded from devalue, so dates, maps and sets show up as such.
6
+
7
+ It only runs in `astro dev` and adds nothing to the built site.
8
+
9
+ ## Install
10
+
11
+ ```sh
12
+ npm install --save-dev @astro-spec/toolbar
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ```ts
18
+ // astro.config.mjs
19
+ import astroSpecToolbar from '@astro-spec/toolbar'
20
+ import { defineConfig } from 'astro/config'
21
+
22
+ export default defineConfig({
23
+ integrations: [astroSpecToolbar()],
24
+ })
25
+ ```
26
+
27
+ Run `astro dev`, open any page and select the Actions icon in the toolbar.
28
+
29
+ Each property of an object schema gets its own control: a text box, a select for enums, a number box or a checkbox. Arrays, nested objects and schemas that are not objects are entered as JSON. A form action (`accept: 'form'`) is sent as form data, the same way a browser form would send it.
30
+
31
+ The app reads the input schemas the same way [`@astro-spec/openapi`](../openapi#readme) does, so actions written with plain `defineAction` work without changes. Actions written with `defineSpecAction` from [`@astro-spec/openapi/actions`](../openapi#readme) also show their summary and description.
32
+
33
+ ## License
34
+
35
+ [MIT](https://github.com/betterlib/astro-spec/blob/main/LICENSE)
package/dist/app.d.mts ADDED
@@ -0,0 +1,2 @@
1
+ declare const _default: import("astro").DevToolbarApp;
2
+ export { _default as default };
package/dist/app.mjs ADDED
@@ -0,0 +1,253 @@
1
+ import options from "virtual:astro-spec/toolbar-options";
2
+ import { defineToolbarApp } from "astro/toolbar";
3
+ import { parse } from "devalue";
4
+ import { t as SPECS_PATH } from "./specs-path-3A6CMgI8.mjs";
5
+ // src/describe-response.ts
6
+ const displayReplacer = (_key, value) => {
7
+ if (value instanceof Set) return { Set: [...value] };
8
+ if (value instanceof Map) return { Map: Object.fromEntries(value) };
9
+ if (typeof value === "bigint") return `${value}n`;
10
+ if (value === void 0) return "undefined";
11
+ return value;
12
+ };
13
+ const withDatesTagged = (value) => {
14
+ if (value instanceof Date) return { Date: value.toISOString() };
15
+ if (Array.isArray(value)) return value.map(withDatesTagged);
16
+ if (value instanceof Set) return new Set([...value].map(withDatesTagged));
17
+ if (value instanceof Map) return new Map([...value].map(([key, entry]) => [key, withDatesTagged(entry)]));
18
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, withDatesTagged(entry)]));
19
+ return value;
20
+ };
21
+ /**
22
+ * Describes an action's HTTP response for display: the status, and the body decoded from
23
+ * devalue or JSON and pretty-printed.
24
+ */
25
+ const describeResponse = (status, contentType, body) => {
26
+ const heading = `${status} ${status < 400 ? "OK" : "Error"}`;
27
+ if (status === 204 || body === "") return {
28
+ ok: status < 400,
29
+ heading,
30
+ text: "(no content)"
31
+ };
32
+ const value = contentType?.includes("devalue") ? parse(body) : contentType?.includes("json") ? JSON.parse(body) : body;
33
+ const text = typeof value === "string" && !contentType?.includes("devalue") ? value : JSON.stringify(withDatesTagged(value), displayReplacer, 2);
34
+ return {
35
+ ok: status < 400,
36
+ heading,
37
+ text
38
+ };
39
+ };
40
+ // src/form-fields.ts
41
+ const fieldFor = (name, schema, required) => {
42
+ const enumValues = schema.enum;
43
+ if (Array.isArray(enumValues) && enumValues.every((value) => typeof value === "string")) return {
44
+ kind: "text",
45
+ name,
46
+ required,
47
+ options: enumValues
48
+ };
49
+ switch (schema.type) {
50
+ case "string": return {
51
+ kind: "text",
52
+ name,
53
+ required,
54
+ options: void 0
55
+ };
56
+ case "number":
57
+ case "integer": return {
58
+ kind: "number",
59
+ name,
60
+ required,
61
+ integer: schema.type === "integer"
62
+ };
63
+ case "boolean": return {
64
+ kind: "boolean",
65
+ name,
66
+ required
67
+ };
68
+ default: return {
69
+ kind: "json",
70
+ name,
71
+ required
72
+ };
73
+ }
74
+ };
75
+ /**
76
+ * Turns an action's input schema into form controls: one per property of an object schema,
77
+ * or a single JSON textarea for any other schema. No schema means no input.
78
+ */
79
+ const fieldsFromSchema = (schema) => {
80
+ if (!schema) return [];
81
+ const properties = schema.properties;
82
+ if (schema.type !== "object" || !properties) return [{
83
+ kind: "json",
84
+ name: "",
85
+ required: true
86
+ }];
87
+ const required = new Set(schema.required ?? []);
88
+ return Object.entries(properties).map(([name, property]) => fieldFor(name, property, required.has(name)));
89
+ };
90
+ const isBlank = (value) => value === void 0 || value === "";
91
+ const parseValue = (field, value) => {
92
+ switch (field.kind) {
93
+ case "text": return value;
94
+ case "number": return Number(value);
95
+ case "boolean": return value === true;
96
+ case "json": return JSON.parse(String(value));
97
+ }
98
+ };
99
+ /**
100
+ * Builds the JSON body for an action from the form values. Blank optional fields are left out,
101
+ * so the action's schema applies its defaults. Throws when a JSON field does not parse.
102
+ */
103
+ const toJsonInput = (fields, values) => {
104
+ const [root] = fields;
105
+ if (root?.kind === "json" && root.name === "") return isBlank(values[""]) ? void 0 : JSON.parse(String(values[""]));
106
+ return Object.fromEntries(fields.filter((field) => field.kind === "boolean" || !isBlank(values[field.name])).map((field) => [field.name, parseValue(field, values[field.name] ?? false)]));
107
+ };
108
+ /**
109
+ * Builds the form data for an action with `accept: 'form'`. Astro converts the strings back
110
+ * with the action's schema; an unchecked checkbox is left out, as a browser form would.
111
+ */
112
+ const toFormData = (fields, values) => {
113
+ const formData = new FormData();
114
+ for (const field of fields) {
115
+ const value = values[field.name];
116
+ if (field.kind === "boolean") {
117
+ if (value === true) formData.set(field.name, "on");
118
+ } else if (!isBlank(value)) formData.set(field.name, String(value));
119
+ }
120
+ return formData;
121
+ };
122
+ // src/app.ts
123
+ const styles = `
124
+ .astro-spec { display: grid; gap: 12px; max-height: 70vh; overflow: auto; }
125
+ .astro-spec h2 { margin: 0; font-size: 1.1em; }
126
+ .astro-spec form { display: grid; gap: 10px; }
127
+ .astro-spec label { display: grid; gap: 4px; }
128
+ .astro-spec .checkbox { display: flex; gap: 8px; align-items: center; }
129
+ .astro-spec input, .astro-spec select, .astro-spec textarea, .astro-spec button {
130
+ font: inherit; color: inherit; background: rgba(255, 255, 255, 0.06);
131
+ border: 1px solid rgba(255, 255, 255, 0.35); border-radius: 6px; padding: 6px 8px;
132
+ }
133
+ .astro-spec textarea { min-height: 6em; font-family: ui-monospace, monospace; }
134
+ .astro-spec button { justify-self: start; cursor: pointer; min-height: 32px; }
135
+ .astro-spec [aria-invalid='true'] { border-color: #ff8a8a; }
136
+ .astro-spec .meta { margin: 0; opacity: 0.8; }
137
+ .astro-spec pre { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; }
138
+ .astro-spec .error-text { color: #ff8a8a; }
139
+ `;
140
+ const element = (tag, properties = {}, children = []) => {
141
+ const node = Object.assign(document.createElement(tag), properties);
142
+ node.append(...children);
143
+ return node;
144
+ };
145
+ const actionUrl = (name) => `${options.base.replace(/\/$/, "")}/_actions/${name}${options.trailingSlash === "always" ? "/" : ""}`;
146
+ const fieldControl = (field, id) => {
147
+ const required = field.required;
148
+ switch (field.kind) {
149
+ case "text": return field.options ? element("select", {
150
+ id,
151
+ name: field.name,
152
+ required
153
+ }, [...required ? [] : [""], ...field.options].map((option) => element("option", { value: option }, [option]))) : element("input", {
154
+ id,
155
+ name: field.name,
156
+ type: "text",
157
+ required
158
+ });
159
+ case "number": return element("input", {
160
+ id,
161
+ name: field.name,
162
+ type: "number",
163
+ step: field.integer ? "1" : "any",
164
+ required
165
+ });
166
+ case "boolean": return element("input", {
167
+ id,
168
+ name: field.name,
169
+ type: "checkbox"
170
+ });
171
+ case "json": return element("textarea", {
172
+ id,
173
+ name: field.name,
174
+ required,
175
+ spellcheck: false
176
+ });
177
+ }
178
+ };
179
+ const fieldRow = (field, id) => {
180
+ const text = `${field.name || "Input"} ${field.kind === "json" ? "(JSON)" : ""}`.trim();
181
+ const control = fieldControl(field, id);
182
+ return field.kind === "boolean" ? element("label", { className: "checkbox" }, [control, text]) : element("label", {}, [text, control]);
183
+ };
184
+ const readValues = (form, fields) => Object.fromEntries(fields.map((field) => {
185
+ const control = form.elements.namedItem(field.name);
186
+ return [field.name, field.kind === "boolean" ? control.checked : control.value];
187
+ }));
188
+ const renderAction = (spec, container, status) => {
189
+ const fields = fieldsFromSchema(spec.input);
190
+ const form = element("form", { noValidate: true }, fields.map((field, index) => fieldRow(field, `astro-spec-field-${index}`)));
191
+ const submit = element("button", { type: "submit" }, ["Run action"]);
192
+ form.append(submit);
193
+ form.addEventListener("submit", async (event) => {
194
+ event.preventDefault();
195
+ for (const control of form.querySelectorAll("[aria-invalid]")) control.removeAttribute("aria-invalid");
196
+ const values = readValues(form, fields);
197
+ const body = (() => {
198
+ try {
199
+ return spec.accept === "form" ? toFormData(fields, values) : JSON.stringify(toJsonInput(fields, values) ?? null);
200
+ } catch {
201
+ return;
202
+ }
203
+ })();
204
+ if (body === void 0) {
205
+ const jsonControl = form.querySelector("textarea");
206
+ jsonControl?.setAttribute("aria-invalid", "true");
207
+ jsonControl?.focus();
208
+ status.replaceChildren(element("p", { className: "error-text" }, ["The JSON is not valid."]));
209
+ return;
210
+ }
211
+ submit.setAttribute("aria-busy", "true");
212
+ status.replaceChildren(element("p", {}, ["Running…"]));
213
+ try {
214
+ const response = await fetch(actionUrl(spec.name), {
215
+ method: "POST",
216
+ headers: spec.accept === "form" ? {} : { "Content-Type": "application/json" },
217
+ body
218
+ });
219
+ const result = describeResponse(response.status, response.headers.get("Content-Type"), await response.text());
220
+ status.replaceChildren(element("p", { className: result.ok ? "" : "error-text" }, [result.heading]), element("pre", {}, [result.text]));
221
+ } catch (error) {
222
+ status.replaceChildren(element("p", { className: "error-text" }, [`Request failed: ${String(error)}`]));
223
+ } finally {
224
+ submit.removeAttribute("aria-busy");
225
+ }
226
+ });
227
+ const details = [spec.summary, spec.description].filter(Boolean).join(" — ");
228
+ container.replaceChildren(...details ? [element("p", { className: "meta" }, [details])] : [], element("p", { className: "meta" }, [`POST ${actionUrl(spec.name)} · ${spec.accept === "form" ? "form data" : "JSON"}`]), form);
229
+ };
230
+ var app_default = defineToolbarApp({ async init(canvas) {
231
+ const root = element("div", { className: "astro-spec" });
232
+ const toolbarWindow = document.createElement("astro-dev-toolbar-window");
233
+ toolbarWindow.append(root);
234
+ canvas.append(element("style", {}, [styles]), toolbarWindow);
235
+ root.append(element("h2", {}, ["Actions"]));
236
+ const { actions } = await (await fetch(`${options.base.replace(/\/$/, "")}${SPECS_PATH}`)).json();
237
+ if (actions.length === 0) {
238
+ root.append(element("p", {}, ["No actions found in src/actions."]));
239
+ return;
240
+ }
241
+ const select = element("select", { id: "astro-spec-action" }, actions.map((spec) => element("option", { value: spec.name }, [spec.name])));
242
+ const container = element("div");
243
+ const status = element("div", { role: "status" });
244
+ root.append(element("label", {}, ["Action", select]), container, element("section", { ariaLabel: "Result" }, [status]));
245
+ const show = () => {
246
+ const spec = actions.find(({ name }) => name === select.value);
247
+ if (spec) renderAction(spec, container, status);
248
+ status.replaceChildren();
249
+ };
250
+ select.addEventListener("change", show);
251
+ show();
252
+ } });
253
+ export { app_default as default };
@@ -0,0 +1,15 @@
1
+ import { AstroIntegration } from "astro";
2
+ /**
3
+ * Adds an Actions app to the Astro Dev Toolbar. It lists the project's actions, builds a form
4
+ * from each input schema and shows the decoded result. It only runs in `astro dev`.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * // astro.config.mjs
9
+ * import astroSpecToolbar from '@astro-spec/toolbar'
10
+ *
11
+ * export default defineConfig({ integrations: [astroSpecToolbar()] })
12
+ * ```
13
+ */
14
+ declare const astroSpecToolbar: () => AstroIntegration;
15
+ export { astroSpecToolbar as default };
package/dist/index.mjs ADDED
@@ -0,0 +1,154 @@
1
+ import { existsSync } from "node:fs";
2
+ import { relative } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { t as SPECS_PATH } from "./specs-path-3A6CMgI8.mjs";
5
+ // ../core/src/vite-plugin.ts
6
+ const ACTIONS_MODULE_ID = "virtual:astro-spec/actions";
7
+ const SHIM_MODULE_ID = "virtual:astro-spec/actions-shim";
8
+ const ENDPOINTS_MODULE_ID = "virtual:astro-spec/endpoints";
9
+ const VIRTUAL_MODULE_IDS = [
10
+ ACTIONS_MODULE_ID,
11
+ SHIM_MODULE_ID,
12
+ ENDPOINTS_MODULE_ID
13
+ ];
14
+ const ACTION_FILE_CANDIDATES = [
15
+ "ts",
16
+ "mts",
17
+ "js",
18
+ "mjs"
19
+ ].flatMap((extension) => [`actions.${extension}`, `actions/index.${extension}`]);
20
+ const SCRIPT_FILE = /\.[cm]?[jt]sx?$/;
21
+ const ASTRO_ACTIONS_SPECIFIER = /(\bfrom\s*|\bimport\s*\(\s*)(['"])astro:actions\2/g;
22
+ const toVitePath = (path) => (path instanceof URL ? fileURLToPath(path) : path).replaceAll("\\", "/");
23
+ const actionsModuleCode = (actionsFile) => `
24
+ import { ActionError } from 'astro:actions'
25
+ import * as zod from 'astro/zod'
26
+ ${actionsFile ? `export { server } from ${JSON.stringify(toVitePath(actionsFile))}` : "export const server = {}"}
27
+ export const runtime = {
28
+ zod4ToJsonSchema: zod.toJSONSchema,
29
+ codeToStatus: (code) => ActionError.codeToStatus(code),
30
+ }
31
+ `;
32
+ const shimModuleCode = `
33
+ import { defineAction as defineAstroAction } from 'astro:actions'
34
+ export * from 'astro:actions'
35
+ export const defineAction = (options) =>
36
+ Object.assign(defineAstroAction(options), {
37
+ [Symbol.for('astro-spec.action')]: { accept: options.accept, input: options.input },
38
+ })
39
+ `;
40
+ const endpointsModuleCode = (pagesDirectory) => `
41
+ export const pagesDirectory = ${JSON.stringify(pagesDirectory)}
42
+ export const modules = import.meta.glob(
43
+ ${JSON.stringify([
44
+ `${pagesDirectory}/**/*.{ts,mts,js,mjs}`,
45
+ "!**/*.d.ts",
46
+ "!**/_*",
47
+ "!**/_*/**"
48
+ ])},
49
+ { eager: true },
50
+ )
51
+ `;
52
+ /**
53
+ * The Vite plugin every astro-spec integration adds. It provides `virtual:astro-spec/actions`,
54
+ * which exports the project's `server` actions and an `AstroRuntime` for `createActionSpecs`,
55
+ * and `virtual:astro-spec/endpoints`, which imports the script pages for `collectPages`.
56
+ *
57
+ * It also makes `defineAction` from `astro:actions` record `accept` and `input` in every script
58
+ * outside `node_modules`, so actions documented without `defineSpecAction` still get their input
59
+ * schema. The action behaves the same. Scripts outside `srcDir` count too, so actions written in
60
+ * another workspace package are covered.
61
+ *
62
+ * @example
63
+ * ```ts
64
+ * updateConfig({ vite: { plugins: [astroSpecVitePlugin({ srcDir: config.srcDir })] } })
65
+ * ```
66
+ */
67
+ const astroSpecVitePlugin = ({ srcDir }) => {
68
+ const pagesUrl = new URL("pages", srcDir);
69
+ let pagesDirectory = "/src/pages";
70
+ return {
71
+ name: "astro-spec:actions",
72
+ enforce: "pre",
73
+ configResolved({ root }) {
74
+ pagesDirectory = `/${toVitePath(relative(root, fileURLToPath(pagesUrl)))}`;
75
+ },
76
+ resolveId(id) {
77
+ return VIRTUAL_MODULE_IDS.includes(id) ? `\0${id}` : void 0;
78
+ },
79
+ configureServer(server) {
80
+ const invalidate = () => {
81
+ const graphs = server.environments ? Object.values(server.environments).map(({ moduleGraph }) => moduleGraph) : [server.moduleGraph];
82
+ for (const graph of graphs) {
83
+ const module = graph?.getModuleById(`\0${ENDPOINTS_MODULE_ID}`);
84
+ if (module) graph?.invalidateModule(module);
85
+ }
86
+ };
87
+ server.watcher.on("add", invalidate);
88
+ server.watcher.on("unlink", invalidate);
89
+ },
90
+ load(id) {
91
+ if (id === `\0${ACTIONS_MODULE_ID}`) {
92
+ const actionsFile = ACTION_FILE_CANDIDATES.map((file) => new URL(file, srcDir)).find((url) => existsSync(url));
93
+ return actionsModuleCode(actionsFile);
94
+ }
95
+ if (id === `\0${SHIM_MODULE_ID}`) return shimModuleCode;
96
+ if (id === `\0${ENDPOINTS_MODULE_ID}`) return endpointsModuleCode(pagesDirectory);
97
+ },
98
+ transform(code, id) {
99
+ const [path] = id.split("?");
100
+ if (id.startsWith("\0") || path.includes("/node_modules/") || !SCRIPT_FILE.test(path)) return;
101
+ if (!code.includes("astro:actions")) return void 0;
102
+ return {
103
+ code: code.replace(ASTRO_ACTIONS_SPECIFIER, `$1$2${SHIM_MODULE_ID}$2`),
104
+ map: null
105
+ };
106
+ }
107
+ };
108
+ };
109
+ // src/integration.ts
110
+ const OPTIONS_MODULE_ID = "virtual:astro-spec/toolbar-options";
111
+ const optionsVitePlugin = (options) => ({
112
+ name: "astro-spec:toolbar-options",
113
+ resolveId: (id) => id === OPTIONS_MODULE_ID ? `\0${OPTIONS_MODULE_ID}` : void 0,
114
+ load: (id) => id === `\0${OPTIONS_MODULE_ID}` ? `export default ${JSON.stringify(options)}` : void 0
115
+ });
116
+ const ICON = "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M13 2 3 14h9l-1 8 10-12h-9z\"/></svg>";
117
+ /**
118
+ * Adds an Actions app to the Astro Dev Toolbar. It lists the project's actions, builds a form
119
+ * from each input schema and shows the decoded result. It only runs in `astro dev`.
120
+ *
121
+ * @example
122
+ * ```ts
123
+ * // astro.config.mjs
124
+ * import astroSpecToolbar from '@astro-spec/toolbar'
125
+ *
126
+ * export default defineConfig({ integrations: [astroSpecToolbar()] })
127
+ * ```
128
+ */
129
+ const astroSpecToolbar = () => ({
130
+ name: "@astro-spec/toolbar",
131
+ hooks: { "astro:config:setup": ({ config, command, injectRoute, updateConfig, addDevToolbarApp }) => {
132
+ if (command !== "dev") return;
133
+ updateConfig({ vite: {
134
+ plugins: [astroSpecVitePlugin({ srcDir: config.srcDir }), optionsVitePlugin({
135
+ base: config.base,
136
+ trailingSlash: config.trailingSlash
137
+ })],
138
+ ssr: { noExternal: ["@astro-spec/openapi", "@astro-spec/toolbar"] },
139
+ optimizeDeps: { exclude: ["@astro-spec/toolbar"] }
140
+ } });
141
+ injectRoute({
142
+ pattern: SPECS_PATH,
143
+ entrypoint: "@astro-spec/toolbar/specs-route",
144
+ prerender: false
145
+ });
146
+ addDevToolbarApp({
147
+ id: "astro-spec",
148
+ name: "Actions",
149
+ icon: ICON,
150
+ entrypoint: "@astro-spec/toolbar/app"
151
+ });
152
+ } }
153
+ });
154
+ export { astroSpecToolbar as default };
@@ -0,0 +1,4 @@
1
+ // src/specs-path.ts
2
+ /** Where the dev server lists the actions for the toolbar app, after Astro's `base`. */
3
+ const SPECS_PATH = "/_astro-spec/toolbar.json";
4
+ export { SPECS_PATH as t };
@@ -0,0 +1,2 @@
1
+ import { APIRoute } from "astro";
2
+ export declare const GET: APIRoute;
@@ -0,0 +1,87 @@
1
+ import { runtime, server } from "virtual:astro-spec/actions";
2
+ import { zodToJsonSchema } from "zod-to-json-schema";
3
+ // ../core/src/action-metadata.ts
4
+ /**
5
+ * The key under which an action carries its astro-spec metadata.
6
+ *
7
+ * It comes from the global symbol registry because the Vite plugin attaches metadata from
8
+ * generated code that cannot import this module.
9
+ */
10
+ const ACTION_METADATA = Symbol.for("astro-spec.action");
11
+ const readActionMetadata = (action) => action[ACTION_METADATA];
12
+ // ../core/src/collect-actions.ts
13
+ const isAction = (value) => typeof value === "function" && "orThrow" in value;
14
+ const isNamespace = (value) => typeof value === "object" && value !== null;
15
+ /** Walks the `server` export of `src/actions` and yields every action, nested ones included. */
16
+ function* collectActions(server, prefix = "") {
17
+ for (const [key, value] of Object.entries(server)) {
18
+ const name = `${prefix}${key}`;
19
+ if (isAction(value)) yield {
20
+ name,
21
+ action: value
22
+ };
23
+ else if (isNamespace(value)) yield* collectActions(value, `${name}.`);
24
+ }
25
+ }
26
+ // ../core/src/to-json-schema.ts
27
+ /**
28
+ * Converts a Zod 3 or Zod 4 schema to a JSON Schema for OpenAPI 3.1, without the `$schema` key.
29
+ *
30
+ * `io` picks which side of transforms, pipes and defaults to describe: `input` for what a client
31
+ * sends, `output` for what a handler returns. Dates become `date-time` strings with both Zod
32
+ * versions; other types JSON Schema cannot express become `{}`.
33
+ */
34
+ const toJsonSchema = (schema, io, zod4ToJsonSchema) => {
35
+ if ("_zod" in schema) {
36
+ if (!zod4ToJsonSchema) throw new Error("Found a Zod 4 schema, but `astro/zod` has no `toJSONSchema`. Import `z` from `astro/zod`.");
37
+ const { $schema: _, ...jsonSchema } = zod4ToJsonSchema(schema, {
38
+ target: "draft-2020-12",
39
+ io,
40
+ unrepresentable: "any",
41
+ override: ({ zodSchema, jsonSchema }) => {
42
+ if (zodSchema._zod.def.type === "date") {
43
+ jsonSchema.type = "string";
44
+ jsonSchema.format = "date-time";
45
+ }
46
+ }
47
+ });
48
+ return jsonSchema;
49
+ }
50
+ if ("_def" in schema) {
51
+ const { $schema: _, ...jsonSchema } = zodToJsonSchema(schema, {
52
+ target: "jsonSchema2019-09",
53
+ $refStrategy: "none",
54
+ pipeStrategy: io,
55
+ effectStrategy: io === "input" ? "input" : "any"
56
+ });
57
+ return jsonSchema;
58
+ }
59
+ throw new Error("Expected a Zod 3 or Zod 4 schema.");
60
+ };
61
+ // ../core/src/create-action-specs.ts
62
+ /**
63
+ * Describes every action in the `server` export of `src/actions`.
64
+ *
65
+ * Actions made with `defineSpecAction`, or with `defineAction` while the astro-spec Vite plugin
66
+ * runs, have schemas. Others are listed with their name only.
67
+ */
68
+ const createActionSpecs = (server, runtime) => Array.from(collectActions(server), ({ name, action }) => {
69
+ const metadata = readActionMetadata(action);
70
+ return {
71
+ name,
72
+ accept: metadata?.accept ?? "json",
73
+ input: metadata?.input && toJsonSchema(metadata.input, "input", runtime.zod4ToJsonSchema),
74
+ output: metadata?.output && toJsonSchema(metadata.output, "output", runtime.zod4ToJsonSchema),
75
+ summary: metadata?.summary,
76
+ description: metadata?.description,
77
+ deprecated: metadata?.deprecated ?? false,
78
+ tags: metadata?.tags,
79
+ errors: (metadata?.errors ?? []).map((code) => ({
80
+ code,
81
+ status: runtime.codeToStatus(code)
82
+ }))
83
+ };
84
+ });
85
+ // src/specs-route.ts
86
+ const GET = () => Response.json({ actions: createActionSpecs(server, runtime) });
87
+ export { GET };
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "@astro-spec/toolbar",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0",
4
+ "description": "Try Astro Actions from the Astro Dev Toolbar",
5
+ "keywords": [
6
+ "astro",
7
+ "astro-integration",
8
+ "withastro",
9
+ "openapi",
10
+ "astro-actions"
11
+ ],
12
+ "homepage": "https://github.com/betterlib/astro-spec/tree/main/packages/toolbar#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/betterlib/astro-spec/issues"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/betterlib/astro-spec.git",
19
+ "directory": "packages/toolbar"
20
+ },
21
+ "license": "MIT",
22
+ "author": "otoneko.",
23
+ "type": "module",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.mts",
27
+ "default": "./dist/index.mjs"
28
+ },
29
+ "./app": "./dist/app.mjs",
30
+ "./specs-route": "./dist/specs-route.mjs",
31
+ "./package.json": "./package.json"
32
+ },
33
+ "files": [
34
+ "dist"
35
+ ],
36
+ "engines": {
37
+ "node": ">=22.12.0"
38
+ },
39
+ "dependencies": {
40
+ "devalue": "^6.0.4",
41
+ "zod-to-json-schema": "^3.25.2"
42
+ },
43
+ "peerDependencies": {
44
+ "astro": "^4.15.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"
45
+ },
46
+ "publishConfig": {
47
+ "access": "public",
48
+ "provenance": true
49
+ },
50
+ "devDependencies": {
51
+ "astro": "^7.4.14",
52
+ "@astro-spec/core": "1.0.0"
53
+ },
54
+ "scripts": {
55
+ "build": "tsdown",
56
+ "typecheck": "tsc --noEmit"
57
+ }
6
58
  }