@stacksjs/actions 0.70.228 → 0.70.230

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/dist/action.d.ts CHANGED
@@ -123,6 +123,7 @@ export declare class Action<TModel = string, TValidations extends ActionValidati
123
123
  before?: ActionOptions<TModel, TValidations, TPath>['before'];
124
124
  handle: ActionOptions<TModel, TValidations, TPath>['handle'];
125
125
  model?: string;
126
+ modelDefinition?: TModel;
126
127
  constructor({
127
128
  name,
128
129
  description,
package/dist/action.js CHANGED
@@ -16,6 +16,7 @@ export class Action {
16
16
  before;
17
17
  handle;
18
18
  model;
19
+ modelDefinition;
19
20
  _dependenciesFactory;
20
21
  _resolvedDeps;
21
22
  _depsOverrides;
@@ -56,6 +57,7 @@ export class Action {
56
57
  this.authorize = authorize;
57
58
  this.before = before;
58
59
  this._dependenciesFactory = dependencies;
60
+ this.modelDefinition = model;
59
61
  if (model && typeof model === "object" && "name" in model)
60
62
  this.model = model.name;
61
63
  else if (typeof model === "string")
@@ -0,0 +1,3 @@
1
+ import type { ComponentLibraryBuildResult } from '@stacksjs/stx';
2
+ export declare function componentPrefix(packageName: string | undefined): string;
3
+ export declare function buildStxComponentLibrary(): Promise<ComponentLibraryBuildResult | undefined>;
@@ -0,0 +1,36 @@
1
+ import { log } from "@stacksjs/logging";
2
+ import { projectPath } from "@stacksjs/path";
3
+ import { hasComponents } from "@stacksjs/storage";
4
+ import { buildComponentLibrary } from "@stacksjs/stx";
5
+ export function componentPrefix(packageName) {
6
+ return (packageName?.split("/").at(-1) || "stx").replace(/(?:-stx|-components?)$/i, "").replace(/[^a-z0-9]+/gi, "-").replace(/^-+|-+$/g, "").toLowerCase() || "stx";
7
+ }
8
+ async function projectPackageName() {
9
+ try {
10
+ return (await Bun.file(projectPath("package.json")).json()).name;
11
+ } catch {
12
+ return;
13
+ }
14
+ }
15
+ export async function buildStxComponentLibrary() {
16
+ if (!hasComponents()) {
17
+ log.warn("No components found in resources/components.");
18
+ return;
19
+ }
20
+ const inputDir = projectPath("resources/components"), outputDir = projectPath("storage/framework/libs/components/stx/dist"), prefix = componentPrefix(await projectPackageName());
21
+ log.info("Building your STX component library...");
22
+ const result = await buildComponentLibrary({
23
+ inputDir,
24
+ outputDir,
25
+ prefix,
26
+ progressive: !0,
27
+ manifest: !0,
28
+ declarations: !0,
29
+ css: !0,
30
+ bundle: !0,
31
+ minify: !0,
32
+ sourcemap: "external"
33
+ });
34
+ log.success(`Built ${result.components.length} components to ${outputDir}`);
35
+ return result;
36
+ }
@@ -1,7 +1,2 @@
1
- import { runCommand } from "@stacksjs/cli";
2
- import { NpmScript } from "@stacksjs/enums";
3
- import { frameworkPath } from "@stacksjs/path";
4
- await runCommand(NpmScript.BuildComponents, {
5
- cwd: frameworkPath(),
6
- verbose: !0
7
- });
1
+ import { buildStxComponentLibrary } from "./component-library";
2
+ await buildStxComponentLibrary();
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ import { buildStxComponentLibrary } from "./build/component-library";
2
+ await buildStxComponentLibrary();
package/dist/build.d.ts CHANGED
@@ -2,8 +2,8 @@ import type { BuildOptions } from '@stacksjs/types';
2
2
  export declare function invoke(options: BuildOptions): Promise<void>;
3
3
  export declare function build(options: BuildOptions): Promise<void>;
4
4
  export declare function componentLibraries(options: BuildOptions): Promise<void>;
5
- export declare function stxComponentLibrary(options: BuildOptions): Promise<void>;
6
- export declare function webComponentLibrary(options: BuildOptions): Promise<void>;
5
+ export declare function stxComponentLibrary(): Promise<void>;
6
+ export declare function webComponentLibrary(): Promise<void>;
7
7
  export declare function docs(options: BuildOptions): Promise<void>;
8
8
  export declare function stacks(options: BuildOptions): Promise<void>;
9
9
  export declare function functionsLibrary(options: BuildOptions): Promise<void>;
package/dist/build.js CHANGED
@@ -1,13 +1,14 @@
1
1
  import { NpmScript } from "@stacksjs/enums";
2
2
  import { log } from "@stacksjs/logging";
3
- import { hasComponents, hasFunctions } from "@stacksjs/storage";
3
+ import { hasFunctions } from "@stacksjs/storage";
4
4
  import { runNpmScript } from "@stacksjs/utils";
5
+ import { buildStxComponentLibrary } from "./build/component-library";
5
6
  import { generateTypes } from "./generate";
6
7
  export async function invoke(options) {
7
8
  if (options.components)
8
9
  await componentLibraries(options);
9
10
  else if (options.webComponents || options.elements)
10
- await webComponentLibrary(options);
11
+ await webComponentLibrary();
11
12
  else if (options.functions)
12
13
  await functionsLibrary(options);
13
14
  else if (options.docs)
@@ -21,27 +22,13 @@ export async function build(options) {
21
22
  }
22
23
  export async function componentLibraries(options) {
23
24
  await runNpmScript(NpmScript.GenerateEntries, options);
24
- await stxComponentLibrary(options);
25
- await webComponentLibrary(options);
25
+ await stxComponentLibrary();
26
26
  }
27
- export async function stxComponentLibrary(options) {
28
- if (hasComponents()) {
29
- log.info("Building your component library...");
30
- await runNpmScript(NpmScript.BuildComponents, options);
31
- log.success("Your component library was built successfully");
32
- } else {
33
- log.warn("No components found.");
34
- log.info("Before you can build components,");
35
- log.info("you need to have created some in the ./components folder.");
36
- }
27
+ export async function stxComponentLibrary() {
28
+ await buildStxComponentLibrary();
37
29
  }
38
- export async function webComponentLibrary(options) {
39
- log.info("Building your component library for production use & npm/CDN distribution...");
40
- if (hasComponents()) {
41
- await runNpmScript(NpmScript.BuildWebComponents, options);
42
- log.success("Your Web Component library was built successfully");
43
- } else
44
- log.info("No components found.");
30
+ export async function webComponentLibrary() {
31
+ await buildStxComponentLibrary();
45
32
  }
46
33
  export async function docs(options) {
47
34
  log.info("Building the documentation site...");
package/dist/bump.js CHANGED
@@ -30,10 +30,12 @@ async function resolveBumpArg(bump) {
30
30
  return `${major}.${minor}.${patch + 1}`;
31
31
  }
32
32
  const resolvedBumpArg = await resolveBumpArg(bumpArg);
33
- async function git(args, cwd = p.projectPath()) {
33
+ async function git(args, cwd = p.projectPath(), options = {}) {
34
34
  return await execSync(["git", ...args], {
35
35
  cwd,
36
- stdin: "inherit"
36
+ stdin: "inherit",
37
+ stderr: "pipe",
38
+ throwOnError: options.throwOnError ?? !0
37
39
  });
38
40
  }
39
41
  async function readVersion(file) {
@@ -94,7 +96,7 @@ await versionBump({
94
96
  yes: Boolean(resolvedBumpArg),
95
97
  verbose: isVerbose
96
98
  });
97
- const nextVersion = isDryRun && resolvedBumpArg && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(resolvedBumpArg) ? resolvedBumpArg : await readVersion(primaryManifest), latestTag = (await git(["describe", "--abbrev=0", "--tags"]).catch(() => "")).trim();
99
+ const nextVersion = isDryRun && resolvedBumpArg && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(resolvedBumpArg) ? resolvedBumpArg : await readVersion(primaryManifest), latestTag = (await git(["describe", "--abbrev=0", "--tags"], p.projectPath(), { throwOnError: !1 }).catch(() => "")).trim();
98
100
  async function writeChangelog() {
99
101
  const config = await loadLogsmithConfig({
100
102
  dir: p.projectPath(),
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Resolve the default CSRF middleware for both framework checkouts and apps
3
+ * consuming the published defaults package.
4
+ */
5
+ export declare function resolveCsrfMiddlewarePath(): string;
6
+ /**
7
+ * Seed the API's double-submit CSRF cookie on an STX page response.
8
+ */
9
+ export declare function seedCsrfPageResponse(request: Request, response: Response): Promise<Response | undefined>;
10
+ /**
11
+ * Apply the application's canonical CSRF validator to a direct development
12
+ * handler that intentionally does not pass through the Stacks router.
13
+ */
14
+ export declare function validateDevCsrfRequest(request: Request): Promise<void>;
@@ -0,0 +1,28 @@
1
+ import { existsSync } from "node:fs";
2
+ import { projectPath } from "@stacksjs/path";
3
+ export function resolveCsrfMiddlewarePath() {
4
+ const relativePath = "app/Middleware/Csrf.ts", vendoredPath = projectPath(`storage/framework/defaults/${relativePath}`);
5
+ if (existsSync(vendoredPath))
6
+ return vendoredPath;
7
+ try {
8
+ const packageJson = Bun.resolveSync("@stacksjs/defaults/package.json", process.cwd());
9
+ return `${packageJson.slice(0, packageJson.lastIndexOf("/"))}/${relativePath}`;
10
+ } catch {
11
+ return vendoredPath;
12
+ }
13
+ }
14
+ export async function seedCsrfPageResponse(request, response) {
15
+ const method = request.method.toUpperCase();
16
+ if (method !== "GET" && method !== "HEAD")
17
+ return;
18
+ if (!(response.headers.get("content-type") || "").toLowerCase().includes("text/html"))
19
+ return;
20
+ try {
21
+ const { seedCsrfCookieIfMissing } = await import(resolveCsrfMiddlewarePath());
22
+ return seedCsrfCookieIfMissing(request, response);
23
+ } catch {}
24
+ }
25
+ export async function validateDevCsrfRequest(request) {
26
+ const { validateCsrfRequest } = await import(resolveCsrfMiddlewarePath());
27
+ await validateCsrfRequest(request);
28
+ }
@@ -0,0 +1 @@
1
+ export declare function shouldDelegateDashboardRequest(pathname: string, method: string): boolean;
@@ -0,0 +1,10 @@
1
+ export function shouldDelegateDashboardRequest(pathname, method) {
2
+ if (pathname.startsWith("/api/config/") || pathname.startsWith("/__deps/"))
3
+ return !1;
4
+ if (pathname.startsWith("/api/"))
5
+ return !0;
6
+ if (pathname.startsWith("/auth/") || pathname === "/me")
7
+ return !0;
8
+ const normalizedMethod = method.toUpperCase();
9
+ return normalizedMethod !== "GET" && normalizedMethod !== "HEAD";
10
+ }
@@ -111,9 +111,9 @@ export declare interface DiscoveredModelManifestRow {
111
111
  }
112
112
  /**
113
113
  * Per-section toggles. Read from the project's `config/dashboard.ts` (when
114
- * present) and passed through buildSidebarConfig / buildSidebarNavHtml so the
115
- * commerce / content / marketing sections collapse out of the sidebar entirely
116
- * for projects that don't ship those features. Anything not specified is on.
114
+ * present) and passed through the native sidebar config plus the STX sidebar
115
+ * data builder, so commerce, content, and marketing sections collapse out for
116
+ * projects that do not ship those features. Anything not specified is on.
117
117
  *
118
118
  * `data` is a per-row toggle map (instead of a single boolean) because the
119
119
  * Data section is always relevant — projects just want to hide individual
@@ -1,5 +1,7 @@
1
1
  import { Glob } from "bun";
2
+ import { existsSync } from "node:fs";
2
3
  import path from "node:path";
4
+ import { pathToFileURL } from "node:url";
3
5
  export const iconMap = {
4
6
  user: "person.fill",
5
7
  team: "person.2.fill",
@@ -96,39 +98,37 @@ function categorizeModel(relativePath, modelId, defaultCategory) {
96
98
  }
97
99
  async function readModelDashboardConfig(absolutePath) {
98
100
  try {
99
- const mod = await import(absolutePath);
101
+ const mod = await import(pathToFileURL(absolutePath).href);
100
102
  return (mod.default ?? mod).dashboard;
101
- } catch {
102
- return;
103
+ } catch (error) {
104
+ throw Error(`Could not discover dashboard model ${absolutePath}: ${error instanceof Error ? error.message : String(error)}`);
103
105
  }
104
106
  }
105
107
  export async function scanModelsDir(dir, seenNames, models, defaultCategory) {
106
- try {
107
- const glob = new Glob("**/*.ts");
108
- for await (const file of glob.scan({ cwd: dir })) {
109
- if (file.includes("README") || file.includes(".d.ts"))
110
- continue;
111
- const name = file.replace(/\.ts$/, "").split("/").pop() || "", nameLower = name.toLowerCase();
112
- if (name && !seenNames.has(nameLower) && !excludeModels.has(nameLower)) {
113
- seenNames.add(nameLower);
114
- const id = modelNameToId(name), absolutePath = path.join(dir, file), dashboard = await readModelDashboardConfig(absolutePath);
115
- models.push({
116
- name,
117
- icon: dashboard?.icon ?? getModelIcon(name),
118
- id,
119
- category: categorizeModel(file, id, defaultCategory),
120
- dashboard
121
- });
122
- }
108
+ if (!existsSync(dir))
109
+ return;
110
+ const glob = new Glob("**/*.ts");
111
+ for await (const file of glob.scan({ cwd: dir })) {
112
+ if (file.includes("README") || file.includes(".d.ts"))
113
+ continue;
114
+ const name = file.replace(/\.ts$/, "").split("/").pop() || "", nameLower = name.toLowerCase();
115
+ if (name && !seenNames.has(nameLower) && !excludeModels.has(nameLower)) {
116
+ seenNames.add(nameLower);
117
+ const id = modelNameToId(name), absolutePath = path.resolve(dir, file), dashboard = await readModelDashboardConfig(absolutePath);
118
+ models.push({
119
+ name,
120
+ icon: dashboard?.icon ?? getModelIcon(name),
121
+ id,
122
+ category: categorizeModel(file, id, defaultCategory),
123
+ dashboard
124
+ });
123
125
  }
124
- } catch {}
126
+ }
125
127
  }
126
128
  export async function discoverModels(userModelsPath, defaultModelsPath) {
127
129
  const models = [], seenNames = new Set;
128
- await Promise.all([
129
- scanModelsDir(userModelsPath, seenNames, models, "userland"),
130
- scanModelsDir(defaultModelsPath, seenNames, models)
131
- ]);
130
+ await scanModelsDir(userModelsPath, seenNames, models, "userland");
131
+ await scanModelsDir(defaultModelsPath, seenNames, models);
132
132
  return models.sort((a, b) => a.name.localeCompare(b.name));
133
133
  }
134
134
  export function buildManifest(models) {
@@ -7,16 +7,4 @@ declare interface CraftApplication {
7
7
  show: () => Promise<void>
8
8
  close: () => void
9
9
  }
10
- // Load dashboard section toggles from `config/dashboard.ts` if present.
11
- // Falls back to "everything enabled" when the file is missing or fails to
12
- // parse, so a fresh project (no dashboard config) still gets the full
13
- // sidebar. Shape mirrors `DashboardSectionToggles` in dashboard-utils.ts.
14
- declare type DataRowToggles = {
15
- dashboard: boolean
16
- activity: boolean
17
- users: boolean
18
- teams: boolean
19
- subscribers: boolean
20
- allModels: boolean
21
- }
22
10
  declare type CraftCreateApp = (options: Record<string, unknown>) => CraftApplication;
@@ -1,7 +1,10 @@
1
1
  import process from "node:process";
2
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
- import { bold, cyan, dim, green, red } from "@stacksjs/cli";
2
+ import { randomUUID } from "node:crypto";
3
+ import { existsSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
4
+ import { bold, cyan, dim, green } from "@stacksjs/cli";
4
5
  import { projectPath, storagePath } from "@stacksjs/path";
6
+ import { seedCsrfPageResponse, validateDevCsrfRequest } from "./csrf";
7
+ import { shouldDelegateDashboardRequest } from "./dashboard-request-routing";
5
8
  import { buildDashboardUrl, buildManifest, discoverModels, findAvailablePort, waitForServer } from "./dashboard-utils";
6
9
  const verboseIdx = process.argv.indexOf("--verbose"), verbose = verboseIdx !== -1 && process.argv[verboseIdx + 1] !== "false", startTime = Bun.nanoseconds(), originalConsoleLog = console.log, originalConsoleWarn = console.warn, bufferedLogs = [];
7
10
  console.log = (...args) => {
@@ -21,30 +24,29 @@ function restoreConsole() {
21
24
  };
22
25
  }
23
26
  async function startStxServer() {
24
- try {
25
- await import("@stacksjs/orm");
26
- } catch (err) {
27
- if (verbose)
28
- console.warn("[dashboard] orm preload failed:", err?.message || err);
29
- }
30
- try {
31
- const { hoistDashboardGlobals } = await import("./dashboard-globals");
32
- await hoistDashboardGlobals({ verbose });
33
- } catch (err) {
34
- if (verbose)
35
- console.warn("[dashboard] globals preload failed:", err?.message || err);
36
- }
27
+ await import("@stacksjs/orm");
37
28
  let serve;
38
29
  try {
39
- serve = (await import("bun-plugin-stx/serve")).serve;
30
+ const localServe = process.env.BUN_PLUGIN_STX_SRC || `${process.env.HOME}/Code/Tools/stx/packages/bun-plugin/src/serve.ts`;
31
+ if (!await Bun.file(localServe).exists())
32
+ throw Error("local bun-plugin-stx source not found");
33
+ serve = (await import(localServe)).serve;
40
34
  } catch {
41
- serve = (await import(projectPath("pantry/bun-plugin-stx/dist/serve.js"))).serve;
35
+ try {
36
+ serve = (await import("bun-plugin-stx/serve")).serve;
37
+ } catch {
38
+ serve = (await import(projectPath("pantry/bun-plugin-stx/dist/serve.js"))).serve;
39
+ }
42
40
  }
43
41
  let stxModule;
44
42
  try {
45
43
  const localStx = process.env.STX_SRC || `${process.env.HOME}/Code/Tools/stx/packages/stx/src/index.ts`;
46
- if (await Bun.file(localStx).exists())
44
+ if (await Bun.file(localStx).exists()) {
45
+ const localCrosswind = `${process.env.HOME}/Code/Tools/crosswind/packages/crosswind/src/index.ts`;
46
+ if (!process.env.CROSSWIND_SRC && await Bun.file(localCrosswind).exists())
47
+ process.env.CROSSWIND_SRC = localCrosswind;
47
48
  stxModule = await import(localStx);
49
+ }
48
50
  } catch {}
49
51
  if (stxModule && verbose)
50
52
  console.log("[Dashboard] Using local stx checkout");
@@ -54,16 +56,79 @@ async function startStxServer() {
54
56
  if (await Bun.file(vendoredStx).exists())
55
57
  stxModule = await import(vendoredStx);
56
58
  } catch {}
57
- const { listConfigFiles, readConfig, updateConfigKey } = await import(storagePath("framework/defaults/resources/functions/dashboard/config-io.ts")), depRoutes = {
58
- "/__deps/charts.js": storagePath("framework/core/charts/dist/index.js")
59
- };
59
+ const { listConfigFiles, readConfig, updateConfigKeys } = await import(storagePath("framework/defaults/resources/functions/dashboard/config-io.ts")), localTsChartsRoot = process.env.TS_CHARTS_SRC || `${process.env.HOME}/Code/Libraries/ts-charts`, dependencyBundles = new Map;
60
+ function resolveTsChartsSource(packageName) {
61
+ return [
62
+ `${localTsChartsRoot}/packages/${packageName}/src/index.ts`,
63
+ projectPath(`node_modules/@ts-charts/${packageName}/src/index.ts`),
64
+ projectPath(`pantry/@ts-charts/${packageName}/src/index.ts`)
65
+ ].find(existsSync) || null;
66
+ }
67
+ const tsChartsEntry = [
68
+ `${localTsChartsRoot}/packages/ts-charts/src/index.ts`,
69
+ projectPath("node_modules/ts-charts/src/index.ts"),
70
+ projectPath("pantry/ts-charts/src/index.ts")
71
+ ].find(existsSync);
72
+ async function buildDashboardDependency(entrypoint) {
73
+ const cached = dependencyBundles.get(entrypoint);
74
+ if (cached)
75
+ return cached;
76
+ const build = (async () => {
77
+ const result = await Bun.build({
78
+ entrypoints: [entrypoint],
79
+ target: "browser",
80
+ format: "esm",
81
+ minify: !0,
82
+ plugins: [{
83
+ name: "dashboard-ts-charts-source",
84
+ setup(builder) {
85
+ builder.onResolve({ filter: /^@ts-charts\/[a-z0-9-]+$/ }, (args) => {
86
+ const packageName = args.path.slice(11), source = resolveTsChartsSource(packageName);
87
+ if (source)
88
+ return { path: source };
89
+ return null;
90
+ });
91
+ }
92
+ }]
93
+ });
94
+ if (!result.success) {
95
+ const errors = result.logs.filter((log) => log.level === "error").map((log) => log.message).join(`
96
+ `);
97
+ throw Error(errors || `Failed to bundle ${entrypoint}`);
98
+ }
99
+ const output = result.outputs.find((file) => file.path.endsWith(".js"));
100
+ if (!output)
101
+ throw Error(`No JavaScript output produced for ${entrypoint}`);
102
+ return output.text();
103
+ })();
104
+ dependencyBundles.set(entrypoint, build);
105
+ return build;
106
+ }
107
+ function browserDependencyRoute(entrypoint) {
108
+ return async () => {
109
+ try {
110
+ return new Response(await buildDashboardDependency(entrypoint), {
111
+ headers: {
112
+ "content-type": "text/javascript; charset=utf-8",
113
+ "cache-control": "no-cache"
114
+ }
115
+ });
116
+ } catch (error) {
117
+ dependencyBundles.delete(entrypoint);
118
+ return new Response(`throw new Error(${JSON.stringify(error.message)})`, {
119
+ status: 500,
120
+ headers: { "content-type": "text/javascript; charset=utf-8" }
121
+ });
122
+ }
123
+ };
124
+ }
60
125
  let dashboardIconCss = null;
61
126
  async function buildDashboardIconCss() {
62
127
  const { generateCrosswindCSS } = await import("@stacksjs/stx"), dirs = [dashboardPath, userDashboardPath, storagePath("framework/defaults/resources/components/Dashboard")], icons = new Set;
63
128
  for (const dir of dirs) {
64
129
  if (!existsSync(dir))
65
130
  continue;
66
- const glob = new Bun.Glob("**/*.stx");
131
+ const glob = new Bun.Glob("**/*.{stx,ts}");
67
132
  for await (const file of glob.scan({ cwd: dir, absolute: !0 })) {
68
133
  const text = await Bun.file(file).text();
69
134
  for (const match of text.matchAll(/\bi-[a-z][a-z0-9]*(?:-[a-z0-9]+)+/g))
@@ -75,6 +140,8 @@ async function startStxServer() {
75
140
  return generateCrosswindCSS(`<div class="${[...icons].join(" ")}"></div>`, process.cwd());
76
141
  }
77
142
  const configRoutes = {
143
+ "/__deps/charts.js": browserDependencyRoute(storagePath("framework/core/charts/src/index.ts")),
144
+ "/__deps/ts-charts.js": browserDependencyRoute(tsChartsEntry || `${localTsChartsRoot}/packages/ts-charts/src/index.ts`),
78
145
  "/__deps/dashboard-icons.css": async () => {
79
146
  if (!dashboardIconCss)
80
147
  dashboardIconCss = buildDashboardIconCss();
@@ -82,21 +149,6 @@ async function startStxServer() {
82
149
  headers: { "content-type": "text/css; charset=utf-8", "cache-control": "no-cache" }
83
150
  });
84
151
  },
85
- ...Object.fromEntries(Object.entries(depRoutes).map(([url, file]) => [
86
- url,
87
- async () => {
88
- const f = Bun.file(file);
89
- if (!await f.exists())
90
- return new Response(`// dependency dist missing: ${file}
91
- // rebuild with: cd ${file.replace(/\/dist\/[^/]+$/, "")} && bun build.ts`, { status: 500, headers: { "content-type": "text/javascript; charset=utf-8" } });
92
- return new Response(f, {
93
- headers: {
94
- "content-type": "text/javascript; charset=utf-8",
95
- "cache-control": "no-cache"
96
- }
97
- });
98
- }
99
- ])),
100
152
  "/api/config/list": async () => {
101
153
  try {
102
154
  return Response.json({ ok: !0, files: listConfigFiles() });
@@ -112,7 +164,7 @@ async function startStxServer() {
112
164
  const result = await readConfig(name);
113
165
  if (!result)
114
166
  return Response.json({ ok: !1, error: "Not found" }, { status: 404 });
115
- return Response.json({ ok: !0, name, fields: result.fields, values: result.values });
167
+ return Response.json({ ok: !0, name, fields: result.fields });
116
168
  } catch (e) {
117
169
  return Response.json({ ok: !1, error: e?.message }, { status: 500 });
118
170
  }
@@ -134,6 +186,7 @@ async function startStxServer() {
134
186
  if (req.method !== "POST")
135
187
  return Response.json({ ok: !1, error: "Method not allowed" }, { status: 405 });
136
188
  try {
189
+ await validateDevCsrfRequest(req);
137
190
  const body = await req.json(), file = body.file?.replace(/\.ts$/, "");
138
191
  if (!file || !/^[\w-]+$/.test(file))
139
192
  return Response.json({ ok: !1, error: "Invalid file" }, { status: 400 });
@@ -148,68 +201,57 @@ async function startStxServer() {
148
201
  updates.push({ key: body.key, value: body.value });
149
202
  if (updates.length === 0)
150
203
  return Response.json({ ok: !1, error: "No updates supplied" }, { status: 400 });
151
- const results = [];
152
- for (const u of updates)
153
- try {
154
- const r = await updateConfigKey(file, u.key, coerce(u.value));
155
- results.push({ key: u.key, ok: !0, newValue: r.newValue });
156
- } catch (err) {
157
- results.push({ key: u.key, ok: !1, error: err?.message });
158
- }
159
- const allOk = results.every((r) => r.ok);
160
- return Response.json({ ok: allOk, file, results });
204
+ const invalid = updates.find((update) => !/^[A-Za-z_$][\w$]*$/.test(update.key) || typeof update.value !== "string" && typeof update.value !== "number" && typeof update.value !== "boolean" || typeof update.value === "number" && !Number.isFinite(update.value));
205
+ if (invalid)
206
+ return Response.json({ ok: !1, error: `Invalid value for configuration key "${invalid.key}"` }, { status: 400 });
207
+ const typedUpdates = updates;
208
+ try {
209
+ await updateConfigKeys(file, typedUpdates);
210
+ } catch (err) {
211
+ const error = err?.message || "Configuration values could not be updated.", results = typedUpdates.map((update) => ({
212
+ key: update.key,
213
+ ok: !1,
214
+ error
215
+ }));
216
+ return Response.json({ ok: !1, file, results, error }, { status: 422 });
217
+ }
218
+ const results = typedUpdates.map((update) => ({
219
+ key: update.key,
220
+ ok: !0,
221
+ newValue: update.value
222
+ }));
223
+ return Response.json({ ok: !0, file, results });
161
224
  } catch (e) {
225
+ if (e?.status === 403)
226
+ return Response.json({ ok: !1, error: "Forbidden", message: "CSRF token mismatch" }, { status: 403 });
162
227
  return Response.json({ ok: !1, error: e?.message }, { status: 500 });
163
228
  }
164
229
  }
165
- };
166
- function coerce(v) {
167
- if (typeof v === "boolean" || typeof v === "number")
168
- return v;
169
- if (v === "true")
170
- return !0;
171
- if (v === "false")
172
- return !1;
173
- if (v === "" || v == null)
174
- return "";
175
- if (typeof v === "string" && /^-?\d+(?:\.\d+)?$/.test(v))
176
- return Number(v);
177
- return String(v);
178
- }
179
- let stacksRoute = null;
180
- try {
181
- const router = await import("@stacksjs/router"), routeRegistry = (await import(projectPath("app/Routes.ts"))).default;
182
- await router.loadRoutes(routeRegistry);
183
- stacksRoute = router.route;
184
- } catch (err) {
185
- const detail = err?.message || String(err);
186
- console.error(`
187
- ${red(bold(" Dashboard API disabled: Stacks router init failed."))}`);
188
- console.error(` ${detail}`);
189
- console.error(dim(" Every /api/dashboard/* endpoint will return 404; pages render but show no data."));
190
- console.error(dim(` Re-run with --verbose for the full stack trace.
191
- `));
192
- if (verbose)
193
- console.error(err);
194
- }
230
+ }, router = await import("@stacksjs/router"), routeRegistry = (await import(projectPath("app/Routes.ts"))).default;
231
+ await router.loadRoutes(routeRegistry);
232
+ const stacksRoute = router.route;
195
233
  serve({
196
234
  patterns: [userDashboardPath, dashboardPath],
197
235
  port: dashboardPort,
198
236
  componentsDir: storagePath("framework/defaults/resources/components/Dashboard"),
199
237
  layoutsDir: dashboardPath,
200
238
  partialsDir: dashboardPath,
239
+ renderCache: !0,
240
+ renderCacheVary: "source",
241
+ prewarmRenderCache: 4,
242
+ watchDirs: [
243
+ projectPath("resources/functions"),
244
+ storagePath("framework/defaults/resources/functions")
245
+ ],
201
246
  quiet: !0,
202
247
  routes: configRoutes,
203
- onRequest: stacksRoute ? async (req) => {
248
+ onRequest: async (req) => {
204
249
  const pathname = new URL(req.url).pathname;
205
- if (pathname.startsWith("/api/config/") || pathname.startsWith("/__deps/"))
206
- return null;
207
- if (pathname.startsWith("/api/"))
208
- return stacksRoute.handleRequest(req);
209
- if (req.method.toUpperCase() !== "GET")
250
+ if (shouldDelegateDashboardRequest(pathname, req.method))
210
251
  return stacksRoute.handleRequest(req);
211
252
  return null;
212
- } : void 0,
253
+ },
254
+ onResponse: seedCsrfPageResponse,
213
255
  auth: !1,
214
256
  ...stxModule && { stxModule }
215
257
  }).catch((err) => {
@@ -245,100 +287,20 @@ async function startReverseProxy() {
245
287
  return !1;
246
288
  }
247
289
  }
248
- const configApiPort = dashboardPort + 1;
249
- function jsonResponse(data, status = 200, extraHeaders = {}) {
250
- return new Response(JSON.stringify(data), {
251
- status,
252
- headers: {
253
- "Content-Type": "application/json",
254
- "Access-Control-Allow-Origin": "*",
255
- "Access-Control-Allow-Methods": "POST, OPTIONS",
256
- "Access-Control-Allow-Headers": "Content-Type",
257
- ...extraHeaders
258
- }
259
- });
260
- }
261
- function startConfigApi() {
262
- Bun.serve({
263
- port: configApiPort,
264
- fetch: async (req) => {
265
- if (req.method === "OPTIONS")
266
- return new Response(null, {
267
- headers: {
268
- "Access-Control-Allow-Origin": "*",
269
- "Access-Control-Allow-Methods": "POST, OPTIONS",
270
- "Access-Control-Allow-Headers": "Content-Type"
271
- }
272
- });
273
- if (new URL(req.url).pathname === "/api/config/update" && req.method === "POST")
274
- try {
275
- const { file, updates } = await req.json();
276
- if (!file || file.includes("..") || !file.match(/^[\w.-]+\.ts$/))
277
- return jsonResponse({ error: "Invalid file name" }, 400);
278
- const filePath = projectPath(`config/${file}`);
279
- let content = readFileSync(filePath, "utf-8");
280
- for (const { path: keyPath, value } of updates) {
281
- const escapedKey = keyPath.split(".").pop().replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), pattern = new RegExp(`(${escapedKey}\\s*:\\s*)(?:'[^']*'|"[^"]*"|\\d+(?:\\.\\d+)?|true|false)`);
282
- if (pattern.test(content)) {
283
- const isNum = /^\d+(?:\.\d+)?$/.test(value), isBool = value === "true" || value === "false", sanitizedValue = value.replace(/'/g, "\\'").replace(/\$/g, "$$$$"), replacement = isNum || isBool ? value : `'${sanitizedValue}'`;
284
- content = content.replace(pattern, `$1${replacement}`);
285
- }
286
- }
287
- writeFileSync(filePath, content, "utf-8");
288
- return jsonResponse({ success: !0 });
289
- } catch (err) {
290
- return jsonResponse({ error: err.message }, 500);
291
- }
292
- return jsonResponse({ error: "Not found" }, 404);
293
- }
294
- });
295
- }
296
- startConfigApi();
297
290
  const [, discoveredModels] = await Promise.all([
298
291
  startStxServer(),
299
292
  discoverModels(projectPath("app/Models"), storagePath("framework/defaults/app/Models"))
300
- ]);
301
- async function loadDashboardToggles() {
302
- const fallback = {
303
- library: !0,
304
- content: !0,
305
- commerce: !0,
306
- marketing: !0,
307
- analytics: !0,
308
- management: !0,
309
- utilities: !0,
310
- ci: !1,
311
- data: { dashboard: !0, activity: !0, users: !0, teams: !0, subscribers: !0, allModels: !0 }
312
- };
313
- try {
314
- const mod = await import(projectPath("config/dashboard.ts")), sections = mod.default?.sections ?? {}, data = sections.data ?? {};
315
- return {
316
- library: sections.library?.enabled ?? !0,
317
- content: sections.content?.enabled ?? !0,
318
- commerce: sections.commerce?.enabled ?? !0,
319
- marketing: sections.marketing?.enabled ?? !0,
320
- analytics: sections.analytics?.enabled ?? !0,
321
- management: sections.management?.enabled ?? !0,
322
- utilities: sections.utilities?.enabled ?? !0,
323
- ci: mod.default?.ci?.enabled ?? !1,
324
- data: {
325
- dashboard: data.dashboard?.enabled ?? !0,
326
- activity: data.activity?.enabled ?? !0,
327
- users: data.users?.enabled ?? !0,
328
- teams: data.teams?.enabled ?? !0,
329
- subscribers: data.subscribers?.enabled ?? !0,
330
- allModels: data.allModels?.enabled ?? !0
331
- }
332
- };
333
- } catch {
334
- return fallback;
335
- }
336
- }
337
- const dashboardToggles = await loadDashboardToggles(), manifestPath = storagePath("framework/defaults/views/dashboard/.discovered-models.json"), manifestPayload = {
293
+ ]), { loadDashboardToggles } = await import(storagePath("framework/defaults/resources/functions/dashboard/toggles.ts")), dashboardToggles = await loadDashboardToggles(projectPath("config/dashboard.ts")), manifestPath = storagePath("framework/defaults/views/dashboard/.discovered-models.json"), manifestPayload = {
338
294
  models: buildManifest(discoveredModels),
339
295
  sections: dashboardToggles
340
- };
341
- writeFileSync(manifestPath, JSON.stringify(manifestPayload, null, 2));
296
+ }, manifestTempPath = `${manifestPath}.${process.pid}.${randomUUID()}.tmp`;
297
+ try {
298
+ writeFileSync(manifestTempPath, JSON.stringify(manifestPayload, null, 2), { flag: "wx" });
299
+ renameSync(manifestTempPath, manifestPath);
300
+ } finally {
301
+ if (existsSync(manifestTempPath))
302
+ unlinkSync(manifestTempPath);
303
+ }
342
304
  const serverReady = await waitForServer(dashboardPort);
343
305
  restoreConsole();
344
306
  let proxyStarted = Boolean(process.env.STACKS_PROXY_MANAGED);
package/dist/dev/views.js CHANGED
@@ -2,6 +2,7 @@ import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { existsSync } from "node:fs";
3
3
  import { config, overridesReady } from "@stacksjs/config";
4
4
  import { projectPath } from "@stacksjs/path";
5
+ import { seedCsrfPageResponse } from "./csrf";
5
6
  const requestStore = new AsyncLocalStorage;
6
7
  function currentRequestContext() {
7
8
  return requestStore.getStore() ?? globalThis.__stxServeContext;
@@ -109,7 +110,8 @@ async function startDefaultServer() {
109
110
  globalThis.__stxServeContext = ctx;
110
111
  requestStore.enterWith(ctx);
111
112
  return null;
112
- }
113
+ },
114
+ onResponse: seedCsrfPageResponse
113
115
  });
114
116
  }
115
117
  async function firstExistingPath(candidates) {
package/dist/make.js CHANGED
@@ -298,9 +298,9 @@ export async function createMigration(options) {
298
298
  const optionName = options.name;
299
299
  if (!optionName[0])
300
300
  throw Error("options.name is required and cannot be empty");
301
- const fileName = `${Date.now()}-${kebabCase(optionName)}.ts`, path = p.userMigrationsPath(fileName), snake = kebabCase(optionName).replace(/-/g, "_"), table = /^create_(.+)_table$/.exec(snake)?.[1] ?? "table_name";
301
+ const fileName = `${Date.now()}-${kebabCase(optionName)}.sql`, path = p.userMigrationsPath(fileName), snake = kebabCase(optionName).replace(/-/g, "_"), table = /^create_(.+)_table$/.exec(snake)?.[1] ?? "table_name", driver = (process.env.DB_CONNECTION || "sqlite").toLowerCase(), mysqlLike = driver === "mysql" || driver === "singlestore", tableIdentifier = mysqlLike ? `\`${table}\`` : `"${table}"`, primaryKey = driver === "postgres" ? '"id" BIGSERIAL PRIMARY KEY' : mysqlLike ? "`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY" : '"id" INTEGER PRIMARY KEY AUTOINCREMENT';
302
302
  try {
303
- await createFileWithTemplate(path, "migration", table);
303
+ await createFileWithTemplate(path, "migration", tableIdentifier, primaryKey);
304
304
  log.success(`Migration created: ${italic(`database/migrations/${fileName}`)}`);
305
305
  } catch (error) {
306
306
  log.error(error);
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The pinned suite: every `protocol:…:check` and `docs:…:check` script.
3
+ *
4
+ * Deliberately narrow. `types:check`, `format:check` and `deps:lockfile:check`
5
+ * also end in `:check` but are not generated-artifact freshness checks, they
6
+ * are slow, and two of them have no generator to fix them with.
7
+ */
8
+ export declare function pinnedCheckScripts(scripts: Record<string, unknown>): string[];
9
+ export declare function readPinnedChecks(cwd: string): string[];
10
+ /**
11
+ * Run every pinned check, concurrently, and report all failures.
12
+ *
13
+ * Concurrent because each one pays roughly five seconds of buddy CLI startup;
14
+ * sequentially the suite is about a minute, in parallel it is closer to the
15
+ * slowest single check. They are independent read-only checks, so there is
16
+ * nothing to serialise.
17
+ *
18
+ * Reports ALL failures rather than stopping at the first: a release blocked by
19
+ * two stale artifacts should cost one round trip, not two.
20
+ */
21
+ export declare function runPinnedChecks(options?: {
22
+ cwd: string
23
+ env?: Record<string, string | undefined>
24
+ scripts?: string[]
25
+ }): Promise<PreflightResult>;
26
+ /** The message shown when the pre-flight blocks a release. */
27
+ export declare function formatPreflightFailure(failures: PreflightResult['failures']): string;
28
+ /** Set to '1' or 'true' to skip the pre-flight. Mirrors the workflow's RELEASE_GATE_BYPASS variable. */
29
+ export declare const BYPASS_ENV: 'RELEASE_GATE_BYPASS';
30
+ export declare interface PreflightResult {
31
+ ran: string[]
32
+ failures: Array<{ script: string, output: string }>
33
+ bypassed: boolean
34
+ }
@@ -0,0 +1,61 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ export const BYPASS_ENV = "RELEASE_GATE_BYPASS";
4
+ export function pinnedCheckScripts(scripts) {
5
+ return Object.keys(scripts).filter((name) => /^(?:protocol|docs):(?:[\w:-]+:)?check$/.test(name)).sort();
6
+ }
7
+ export function readPinnedChecks(cwd) {
8
+ try {
9
+ const pkg = JSON.parse(readFileSync(join(cwd, "package.json"), "utf8"));
10
+ return pinnedCheckScripts(pkg.scripts ?? {});
11
+ } catch {
12
+ return [];
13
+ }
14
+ }
15
+ function isBypassed(env) {
16
+ const value = env[BYPASS_ENV];
17
+ return value === "1" || value === "true";
18
+ }
19
+ export async function runPinnedChecks(options = { cwd: process.cwd() }) {
20
+ const env = options.env ?? process.env;
21
+ if (isBypassed(env))
22
+ return { ran: [], failures: [], bypassed: !0 };
23
+ const scripts = options.scripts ?? readPinnedChecks(options.cwd);
24
+ if (scripts.length === 0)
25
+ return { ran: [], failures: [], bypassed: !1 };
26
+ const results = await Promise.all(scripts.map(async (script) => {
27
+ const proc = Bun.spawn(["bun", "run", script], {
28
+ cwd: options.cwd,
29
+ stdout: "pipe",
30
+ stderr: "pipe"
31
+ }), [stdout, stderr, exitCode] = await Promise.all([
32
+ new Response(proc.stdout).text(),
33
+ new Response(proc.stderr).text(),
34
+ proc.exited
35
+ ]);
36
+ return { script, exitCode, output: `${stdout}${stderr}`.trim() };
37
+ }));
38
+ return {
39
+ ran: scripts,
40
+ failures: results.filter((r) => r.exitCode !== 0).map((r) => ({ script: r.script, output: r.output })),
41
+ bypassed: !1
42
+ };
43
+ }
44
+ export function formatPreflightFailure(failures) {
45
+ const lines = [
46
+ `Release blocked: ${failures.length} pinned check${failures.length === 1 ? "" : "s"} failed.`,
47
+ ""
48
+ ];
49
+ for (const failure of failures) {
50
+ lines.push(` ${failure.script}`);
51
+ const informative = failure.output.split(`
52
+ `).map((line) => line.trim()).filter((line) => line && !line.startsWith("[env]") && !line.startsWith("$ ") && !line.startsWith("error: script"));
53
+ for (const line of informative.slice(0, 4))
54
+ lines.push(` ${line}`);
55
+ lines.push("");
56
+ }
57
+ lines.push("Nothing was bumped, committed, or tagged.");
58
+ lines.push(`Regenerate the affected artifacts and retry, or set ${BYPASS_ENV}=1 to release anyway.`);
59
+ return lines.join(`
60
+ `);
61
+ }
package/dist/release.js CHANGED
@@ -4,13 +4,21 @@ import { Action } from "@stacksjs/enums";
4
4
  import { log } from "@stacksjs/logging";
5
5
  import { projectPath } from "@stacksjs/path";
6
6
  import { runActions } from ".";
7
+ import { BYPASS_ENV, formatPreflightFailure, runPinnedChecks } from "./release-preflight";
7
8
  const raw = parseOptions() ?? {}, passthrough = {};
8
9
  for (const [k, v] of Object.entries(raw)) {
9
10
  if (k === "--" || k === "_")
10
11
  continue;
11
12
  passthrough[k] = v;
12
13
  }
13
- const isDryRun = passthrough.dryRun === !0 || passthrough.dryRun === "true", actions = isDryRun ? [Action.GenerateLibraryEntries, Action.Bump] : [Action.GenerateLibraryEntries, Action.LintFix, Action.Bump], result = await runActions(actions, {
14
+ const isDryRun = passthrough.dryRun === !0 || passthrough.dryRun === "true", actions = isDryRun ? [Action.GenerateLibraryEntries, Action.Bump] : [Action.GenerateLibraryEntries, Action.LintFix, Action.Bump], preflight = await runPinnedChecks({ cwd: projectPath() });
15
+ if (preflight.bypassed)
16
+ log.warn(`${BYPASS_ENV} is set, so the pinned checks were skipped for this release.`);
17
+ else if (preflight.failures.length > 0) {
18
+ log.error(formatPreflightFailure(preflight.failures));
19
+ process.exit(1);
20
+ }
21
+ const result = await runActions(actions, {
14
22
  cwd: projectPath(),
15
23
  ...passthrough
16
24
  });
package/dist/templates.js CHANGED
@@ -83,17 +83,8 @@ const heading = 'Hello World page created'
83
83
  <p>Visit /{0}</p>
84
84
  </div>
85
85
  </template>`,
86
- function: `// reactive state
87
- const {0} = ref(0)
88
-
89
- // functions that mutate state and trigger updates
90
- function increment() {
91
- {0}.value++
92
- }
93
-
94
- export {
95
- {0},
96
- increment,
86
+ function: `export function {0}(): void {
87
+ // Add function logic here.
97
88
  }`,
98
89
  language: `button:
99
90
  text: Copy`,
@@ -112,7 +103,7 @@ function send(): {0} {
112
103
 
113
104
  /**
114
105
  * Props passed into the {0} email. Add the fields your template
115
- * needs and they'll flow through to the stx template's \`props\` \u2014
106
+ * needs and they'll flow through to the stx template's \`props\`.
116
107
  * \`Mailable<{0}Props>\` ensures \`.template()\` and \`this.props\`
117
108
  * type-check against this shape (stacksjs/stacks#1903).
118
109
  */
@@ -124,7 +115,7 @@ export interface {0}Props extends Record<string, unknown> {
124
115
  }
125
116
 
126
117
  /**
127
- * {0} mailable. Subclass of \`Mailable<{0}Props>\` \u2014 \`build()\` wires the
118
+ * {0} mailable. Subclass of \`Mailable<{0}Props>\`. \`build()\` wires the
128
119
  * recipient / subject / template (props typed against \`{0}Props\`),
129
120
  * then \`send()\` (inherited) dispatches via the configured mail driver.
130
121
  *
@@ -149,7 +140,7 @@ export class {0} extends Mailable<{0}Props> {
149
140
  }
150
141
  }`,
151
142
  mailTemplate: `<script server>
152
- // Generated by \`buddy make:mail {0}\`. Edit freely \u2014 \`props\` is the
143
+ // Generated by \`buddy make:mail {0}\`. Edit freely. \`props\` is the
153
144
  // object passed by the Mailable's \`build()\`.
154
145
  const appName = props.appName || 'Stacks'
155
146
  const appUrl = props.appUrl || 'https://stacksjs.com'
@@ -240,14 +231,10 @@ export default defineModel({
240
231
  // your attributes here
241
232
  },
242
233
  } as const)`,
243
- migration: `import type { Database } from '@stacksjs/database'
244
-
245
- export async function up(db: Database): Promise<void> {
246
- await db.schema
247
- .createTable('{0}')
248
- .addColumn('id', 'integer', col => col.autoIncrement().primaryKey())
249
- .execute()
250
- }`,
234
+ migration: `CREATE TABLE {0} (
235
+ {1}
236
+ );
237
+ `,
251
238
  stackPackageJson: `{
252
239
  "name": "{0}",
253
240
  "version": "0.0.1",
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/actions",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.70.228",
5
+ "version": "0.70.230",
6
6
  "description": "The Stacks actions.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -62,31 +62,32 @@
62
62
  "prepublishOnly": "bun run build"
63
63
  },
64
64
  "dependencies": {
65
- "@stacksjs/config": "0.70.228",
65
+ "@stacksjs/config": "0.70.230",
66
66
  "@stacksjs/bumpx": "^0.2.6",
67
67
  "@stacksjs/bunpress": "^0.1.18",
68
68
  "@stacksjs/logsmith": "^0.2.3",
69
- "@stacksjs/registry": "0.70.228",
69
+ "@stacksjs/registry": "0.70.230",
70
+ "@stacksjs/stx": "^0.2.148",
70
71
  "@stacksjs/ts-cloud": "^0.7.92",
71
72
  "@stacksjs/ts-md": "^0.1.1"
72
73
  },
73
74
  "devDependencies": {
74
- "@stacksjs/api": "0.70.228",
75
- "@stacksjs/cli": "0.70.228",
76
- "@stacksjs/database": "0.70.228",
75
+ "@stacksjs/api": "0.70.230",
76
+ "@stacksjs/cli": "0.70.230",
77
+ "@stacksjs/database": "0.70.230",
77
78
  "@stacksjs/tlsx": "^0.13.2",
78
79
  "better-dx": "^0.2.17",
79
- "@stacksjs/dns": "0.70.228",
80
- "@stacksjs/enums": "0.70.228",
81
- "@stacksjs/env": "0.70.228",
82
- "@stacksjs/error-handling": "0.70.228",
83
- "@stacksjs/logging": "0.70.228",
84
- "@stacksjs/path": "0.70.228",
85
- "@stacksjs/security": "0.70.228",
86
- "@stacksjs/storage": "0.70.228",
87
- "@stacksjs/strings": "0.70.228",
88
- "@stacksjs/utils": "0.70.228",
89
- "@stacksjs/validation": "0.70.228"
80
+ "@stacksjs/dns": "0.70.230",
81
+ "@stacksjs/enums": "0.70.230",
82
+ "@stacksjs/env": "0.70.230",
83
+ "@stacksjs/error-handling": "0.70.230",
84
+ "@stacksjs/logging": "0.70.230",
85
+ "@stacksjs/path": "0.70.230",
86
+ "@stacksjs/security": "0.70.230",
87
+ "@stacksjs/storage": "0.70.230",
88
+ "@stacksjs/strings": "0.70.230",
89
+ "@stacksjs/utils": "0.70.230",
90
+ "@stacksjs/validation": "0.70.230"
90
91
  },
91
92
  "peerDependencies": {
92
93
  "pickier": "^0.1.35"
@@ -1,4 +0,0 @@
1
- export declare function hoistDashboardGlobals(opts?: HoistOptions): Promise<void>;
2
- declare interface HoistOptions {
3
- verbose?: boolean
4
- }
@@ -1,89 +0,0 @@
1
- import { existsSync, readdirSync, statSync } from "node:fs";
2
- import { join } from "node:path";
3
- import process from "node:process";
4
- import { projectPath, storagePath } from "@stacksjs/path";
5
- const HELPER_DIRS = [
6
- storagePath("framework/defaults/resources/functions/dashboard"),
7
- projectPath("resources/functions"),
8
- projectPath("app/Helpers")
9
- ];
10
- export async function hoistDashboardGlobals(opts = {}) {
11
- const g = globalThis, collisions = [];
12
- let hoisted = 0;
13
- for (const dir of HELPER_DIRS) {
14
- if (!existsSync(dir))
15
- continue;
16
- let entries;
17
- try {
18
- entries = readdirSync(dir);
19
- } catch {
20
- continue;
21
- }
22
- for (const entry of entries) {
23
- const full = join(dir, entry);
24
- let s;
25
- try {
26
- s = statSync(full);
27
- } catch {
28
- continue;
29
- }
30
- if (s.isDirectory()) {
31
- let subEntries;
32
- try {
33
- subEntries = readdirSync(full);
34
- } catch {
35
- continue;
36
- }
37
- for (const sub of subEntries) {
38
- if (!isImportable(sub))
39
- continue;
40
- const subFull = join(full, sub), r = await hoistFile(subFull, g, opts.verbose);
41
- hoisted += r.added;
42
- collisions.push(...r.collisions);
43
- }
44
- continue;
45
- }
46
- if (!isImportable(entry))
47
- continue;
48
- const r = await hoistFile(full, g, opts.verbose);
49
- hoisted += r.added;
50
- collisions.push(...r.collisions);
51
- }
52
- }
53
- if (opts.verbose)
54
- process.stdout.write(`[dashboard] hoisted ${hoisted} helper globals` + (collisions.length > 0 ? ` (skipped ${collisions.length} collisions: ${collisions.slice(0, 5).join(", ")}\u2026)` : "") + `
55
- `);
56
- }
57
- function isImportable(name) {
58
- if (!/\.(?:ts|tsx|js|mjs)$/.test(name))
59
- return !1;
60
- if (name.startsWith("_"))
61
- return !1;
62
- if (name.endsWith(".test.ts") || name.endsWith(".spec.ts"))
63
- return !1;
64
- if (name.endsWith(".d.ts"))
65
- return !1;
66
- return !0;
67
- }
68
- async function hoistFile(file, g, _verbose) {
69
- let mod;
70
- try {
71
- mod = await import(file);
72
- } catch {
73
- return { added: 0, collisions: [] };
74
- }
75
- const collisions = [];
76
- let added = 0;
77
- for (const [name, value] of Object.entries(mod)) {
78
- if (name === "default" || name.startsWith("_"))
79
- continue;
80
- if (typeof value === "function" || value && typeof value === "object") {
81
- if (g[name] === void 0) {
82
- g[name] = value;
83
- added++;
84
- } else if (g[name] !== value)
85
- collisions.push(name);
86
- }
87
- }
88
- return { added, collisions };
89
- }