@stacksjs/actions 0.70.257 → 0.70.259
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.js +1 -80
- package/dist/actions.js +1 -2
- package/dist/add.js +1 -20
- package/dist/ai/request-model-access.js +1 -10
- package/dist/auth/client.js +2 -44
- package/dist/auth/prune.js +1 -35
- package/dist/auth/setup.js +33 -153
- package/dist/auth/token.js +1 -10
- package/dist/blog-admin.js +3 -151
- package/dist/blog.js +33 -271
- package/dist/build/cli.js +1 -6
- package/dist/build/component-library.js +1 -36
- package/dist/build/component-libs.js +1 -2
- package/dist/build/core.js +1 -55
- package/dist/build/desktop.js +4 -61
- package/dist/build/dmg.js +4 -68
- package/dist/build/docs.js +1 -5
- package/dist/build/frontend-static.js +6 -122
- package/dist/build/server.js +1 -6
- package/dist/build/stacks.js +1 -8
- package/dist/build/views.js +1 -16
- package/dist/build-web-component-lib.js +1 -2
- package/dist/build.js +1 -57
- package/dist/bump.js +9 -210
- package/dist/changelog.js +1 -27
- package/dist/check/ports.js +1 -16
- package/dist/clean.js +1 -4
- package/dist/commit.js +1 -12
- package/dist/copy-types.js +1 -9
- package/dist/database/seed.js +1 -26
- package/dist/deploy/create-receipt-rule.js +1 -36
- package/dist/deploy/index.js +29 -1306
- package/dist/dev/api.js +3 -94
- package/dist/dev/components.js +1 -7
- package/dist/dev/csrf.js +1 -28
- package/dist/dev/dashboard-request-routing.js +1 -10
- package/dist/dev/dashboard-utils.js +1 -380
- package/dist/dev/dashboard.js +7 -422
- package/dist/dev/desktop.js +1 -1
- package/dist/dev/docs.js +1 -24
- package/dist/dev/exit-with-parent.d.ts +6 -0
- package/dist/dev/exit-with-parent.js +1 -0
- package/dist/dev/index.js +1 -29
- package/dist/dev/migrate-watcher.js +1 -74
- package/dist/dev/system-tray.js +2 -172
- package/dist/dev/views.js +1 -169
- package/dist/discover-packages.js +1 -32
- package/dist/domains/add.js +1 -61
- package/dist/domains/purchase.js +1 -66
- package/dist/domains/remove.js +1 -24
- package/dist/examples.js +1 -34
- package/dist/find-projects.js +1 -16
- package/dist/fresh.js +1 -17
- package/dist/generate/action-types.js +3 -9
- package/dist/generate/component-meta.js +1 -9
- package/dist/generate/custom-cli-file.js +2 -20
- package/dist/generate/env-files.js +5 -46
- package/dist/generate/ide-helpers.js +1 -8
- package/dist/generate/images.js +1 -26
- package/dist/generate/index.js +1 -166
- package/dist/generate/lib-entries.js +1 -16
- package/dist/generate/pantry-file.js +1 -46
- package/dist/generate/symlink-core.js +1 -2
- package/dist/generate/types.js +1 -3
- package/dist/generate/vschema.js +2 -47
- package/dist/generate/vscode-custom-data.js +1 -9
- package/dist/helpers/api-host.js +1 -7
- package/dist/helpers/component-meta.js +5 -295
- package/dist/helpers/index.js +1 -1
- package/dist/helpers/lib-entries.js +3 -73
- package/dist/helpers/package-json.js +2 -34
- package/dist/helpers/utils.js +1 -130
- package/dist/helpers/vscode-custom-data.js +3 -57
- package/dist/index.d.ts +4 -0
- package/dist/index.js +1 -50
- package/dist/key-generate.js +1 -24
- package/dist/lint/fix.js +1 -4
- package/dist/lint/index.js +1 -4
- package/dist/lint/lint.js +1 -34
- package/dist/lint/stx-gate.d.ts +36 -0
- package/dist/lint/stx-gate.js +3 -0
- package/dist/make-command.js +4 -55
- package/dist/make-job.js +3 -29
- package/dist/make-policy.js +4 -53
- package/dist/make-resource.js +3 -33
- package/dist/make.js +7 -323
- package/dist/migrate/database.js +1 -16
- package/dist/migrate/fresh.js +1 -36
- package/dist/prepublish.js +1 -16
- package/dist/queue/clear.js +1 -42
- package/dist/queue/dlq-purge.js +1 -28
- package/dist/queue/dlq-retry.js +1 -35
- package/dist/queue/dlq.js +4 -55
- package/dist/queue/failed.js +4 -69
- package/dist/queue/flush.js +2 -49
- package/dist/queue/inspect.js +7 -154
- package/dist/queue/list.js +4 -69
- package/dist/queue/monitor.js +5 -94
- package/dist/queue/pause.js +1 -28
- package/dist/queue/quarantine.js +2 -42
- package/dist/queue/resume.js +1 -27
- package/dist/queue/retry.js +1 -41
- package/dist/queue/schedule-list.js +4 -33
- package/dist/queue/schedule.js +1 -12
- package/dist/queue/status.js +4 -68
- package/dist/queue/table.js +1 -10
- package/dist/queue/unquarantine.js +1 -27
- package/dist/queue/work.js +1 -57
- package/dist/release-preflight.js +3 -61
- package/dist/release.js +1 -29
- package/dist/route/list.js +2 -78
- package/dist/run-action.js +1 -1
- package/dist/saas/setup.js +1 -9
- package/dist/scaffold-crud.js +12 -137
- package/dist/schedule/run.js +1 -7
- package/dist/search/flush.js +1 -10
- package/dist/search/import.js +1 -10
- package/dist/search/settings-list.js +1 -10
- package/dist/search/settings.js +1 -9
- package/dist/serve/api.js +1 -37
- package/dist/setup/index.js +1 -1
- package/dist/setup/ssl.js +2 -268
- package/dist/stacks.js +1 -316
- package/dist/templates.js +20 -40
- package/dist/test/feature.js +1 -2
- package/dist/test/index.js +1 -2
- package/dist/test/runner.js +1 -38
- package/dist/test/runner.test.js +1 -29
- package/dist/test/ui.js +1 -2
- package/dist/test/unit.js +1 -2
- package/dist/typecheck.js +1 -4
- package/dist/types.js +1 -16
- package/dist/upgrade/binary.js +1 -29
- package/dist/upgrade/framework-hooks.js +1 -40
- package/dist/upgrade/framework-utils.js +2 -259
- package/dist/upgrade/framework.js +11 -484
- package/dist/upgrade/index.js +1 -17
- package/dist/upgrade/package-project.js +1 -150
- package/dist/upgrade/packages.js +17 -243
- package/dist/upgrade/shell.js +3 -40
- package/dist/upgrade.js +1 -38
- package/package.json +19 -19
package/dist/scaffold-crud.js
CHANGED
|
@@ -1,88 +1,6 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import { writeTextFile } from "@stacksjs/storage";
|
|
5
|
-
import { isDryRunActive } from "./make";
|
|
6
|
-
const TYPE_ALIASES = {
|
|
7
|
-
str: "string",
|
|
8
|
-
string: "string",
|
|
9
|
-
varchar: "string",
|
|
10
|
-
text: "text",
|
|
11
|
-
longtext: "text",
|
|
12
|
-
int: "number",
|
|
13
|
-
integer: "number",
|
|
14
|
-
number: "number",
|
|
15
|
-
num: "number",
|
|
16
|
-
bool: "boolean",
|
|
17
|
-
boolean: "boolean",
|
|
18
|
-
date: "date",
|
|
19
|
-
datetime: "date",
|
|
20
|
-
json: "json"
|
|
21
|
-
};
|
|
22
|
-
export function parseFields(input) {
|
|
23
|
-
if (!input)
|
|
24
|
-
return [];
|
|
25
|
-
const parts = input.split(",").map((p) => p.trim()).filter(Boolean), out = [];
|
|
26
|
-
for (const part of parts) {
|
|
27
|
-
const [rawName, rawType = "string"] = part.split(":"), name = rawName?.trim();
|
|
28
|
-
if (!name)
|
|
29
|
-
continue;
|
|
30
|
-
const type = TYPE_ALIASES[rawType.trim().toLowerCase()] ?? "string";
|
|
31
|
-
out.push({ name, type });
|
|
32
|
-
}
|
|
33
|
-
return out;
|
|
34
|
-
}
|
|
35
|
-
function pluralize(word) {
|
|
36
|
-
if (!word)
|
|
37
|
-
return word;
|
|
38
|
-
const lower = word.toLowerCase();
|
|
39
|
-
if (lower.endsWith("s") || lower.endsWith("x") || lower.endsWith("z") || lower.endsWith("ch") || lower.endsWith("sh"))
|
|
40
|
-
return `${word}es`;
|
|
41
|
-
if (lower.endsWith("y") && !/[aeiou]y$/.test(lower))
|
|
42
|
-
return `${word.slice(0, -1)}ies`;
|
|
43
|
-
return `${word}s`;
|
|
44
|
-
}
|
|
45
|
-
function pascalCase(name) {
|
|
46
|
-
return name.replace(/(^|[-_\s])(\w)/g, (_, __, c) => String(c).toUpperCase());
|
|
47
|
-
}
|
|
48
|
-
function snakeCase(name) {
|
|
49
|
-
return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[-\s]+/g, "_").toLowerCase();
|
|
50
|
-
}
|
|
51
|
-
function attributeBlock(fields) {
|
|
52
|
-
if (fields.length === 0)
|
|
53
|
-
return " title: { type: 'string', fillable: true, validation: { rule: schema.string().required() } },";
|
|
54
|
-
return fields.map((f) => {
|
|
55
|
-
const t = f.type, rule = t === "number" ? "schema.number()" : t === "boolean" ? "schema.boolean()" : t === "date" ? "schema.date()" : t === "json" ? "schema.object({})" : "schema.string()", dbType = t === "number" ? "number" : t === "boolean" ? "boolean" : t === "date" ? "date" : t === "json" ? "json" : "string";
|
|
56
|
-
return ` ${f.name}: { type: '${dbType}', fillable: true, validation: { rule: ${rule} } },`;
|
|
57
|
-
}).join(`
|
|
58
|
-
`);
|
|
59
|
-
}
|
|
60
|
-
function migrationColumns(fields) {
|
|
61
|
-
if (fields.length === 0)
|
|
62
|
-
return " .addColumn('title', 'varchar(255)', col => col.notNull())";
|
|
63
|
-
return fields.map((f) => {
|
|
64
|
-
switch (f.type) {
|
|
65
|
-
case "number":
|
|
66
|
-
return ` .addColumn('${f.name}', 'integer')`;
|
|
67
|
-
case "boolean":
|
|
68
|
-
return ` .addColumn('${f.name}', 'boolean', col => col.defaultTo(false))`;
|
|
69
|
-
case "text":
|
|
70
|
-
return ` .addColumn('${f.name}', 'text')`;
|
|
71
|
-
case "date":
|
|
72
|
-
return ` .addColumn('${f.name}', 'timestamp')`;
|
|
73
|
-
case "json":
|
|
74
|
-
return ` .addColumn('${f.name}', 'text')`;
|
|
75
|
-
default:
|
|
76
|
-
return ` .addColumn('${f.name}', 'varchar(255)')`;
|
|
77
|
-
}
|
|
78
|
-
}).join(`
|
|
79
|
-
`);
|
|
80
|
-
}
|
|
81
|
-
function actionStub(name, kind, fields) {
|
|
82
|
-
const Model = pascalCase(name);
|
|
83
|
-
switch (kind) {
|
|
84
|
-
case "Index":
|
|
85
|
-
return `import { Action } from '@stacksjs/actions'
|
|
1
|
+
import{italic}from"@stacksjs/cli";import{log}from"@stacksjs/logging";import{path as p}from"@stacksjs/path";import{writeTextFile}from"@stacksjs/storage";import{isDryRunActive}from"./make";const TYPE_ALIASES={str:"string",string:"string",varchar:"string",text:"text",longtext:"text",int:"number",integer:"number",number:"number",num:"number",bool:"boolean",boolean:"boolean",date:"date",datetime:"date",json:"json"};export function parseFields(input){if(!input)return[];const parts=input.split(",").map((p)=>p.trim()).filter(Boolean),out=[];for(const part of parts){const[rawName,rawType="string"]=part.split(":"),name=rawName?.trim();if(!name)continue;const type=TYPE_ALIASES[rawType.trim().toLowerCase()]??"string";out.push({name,type})}return out}function pluralize(word){if(!word)return word;const lower=word.toLowerCase();if(lower.endsWith("s")||lower.endsWith("x")||lower.endsWith("z")||lower.endsWith("ch")||lower.endsWith("sh"))return`${word}es`;if(lower.endsWith("y")&&!/[aeiou]y$/.test(lower))return`${word.slice(0,-1)}ies`;return`${word}s`}function pascalCase(name){return name.replace(/(^|[-_\s])(\w)/g,(_,__,c)=>String(c).toUpperCase())}function snakeCase(name){return name.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[-\s]+/g,"_").toLowerCase()}function attributeBlock(fields){if(fields.length===0)return" title: { type: 'string', fillable: true, validation: { rule: schema.string().required() } },";return fields.map((f)=>{const t=f.type,rule=t==="number"?"schema.number()":t==="boolean"?"schema.boolean()":t==="date"?"schema.date()":t==="json"?"schema.object({})":"schema.string()",dbType=t==="number"?"number":t==="boolean"?"boolean":t==="date"?"date":t==="json"?"json":"string";return` ${f.name}: { type: '${dbType}', fillable: true, validation: { rule: ${rule} } },`}).join(`
|
|
2
|
+
`)}function migrationColumns(fields){if(fields.length===0)return" .addColumn('title', 'varchar(255)', col => col.notNull())";return fields.map((f)=>{switch(f.type){case"number":return` .addColumn('${f.name}', 'integer')`;case"boolean":return` .addColumn('${f.name}', 'boolean', col => col.defaultTo(false))`;case"text":return` .addColumn('${f.name}', 'text')`;case"date":return` .addColumn('${f.name}', 'timestamp')`;case"json":return` .addColumn('${f.name}', 'text')`;default:return` .addColumn('${f.name}', 'varchar(255)')`}}).join(`
|
|
3
|
+
`)}function actionStub(name,kind,fields){const Model=pascalCase(name);switch(kind){case"Index":return`import { Action } from '@stacksjs/actions'
|
|
86
4
|
import ${Model} from '~/app/Models/${Model}'
|
|
87
5
|
|
|
88
6
|
export default new Action({
|
|
@@ -92,9 +10,7 @@ export default new Action({
|
|
|
92
10
|
async handle() {
|
|
93
11
|
return await ${Model}.all()
|
|
94
12
|
},
|
|
95
|
-
})`;
|
|
96
|
-
case "Show":
|
|
97
|
-
return `import { Action } from '@stacksjs/actions'
|
|
13
|
+
})`;case"Show":return`import { Action } from '@stacksjs/actions'
|
|
98
14
|
import ${Model} from '~/app/Models/${Model}'
|
|
99
15
|
|
|
100
16
|
export default new Action({
|
|
@@ -105,10 +21,7 @@ export default new Action({
|
|
|
105
21
|
const id = Number(request.get('id'))
|
|
106
22
|
return await ${Model}.findOrFail(id)
|
|
107
23
|
},
|
|
108
|
-
})`;
|
|
109
|
-
case "Store": {
|
|
110
|
-
const keys = (fields.length > 0 ? fields : [{ name: "title", type: "string" }]).map((f) => `'${f.name}'`).join(", ");
|
|
111
|
-
return `import { Action } from '@stacksjs/actions'
|
|
24
|
+
})`;case"Store":{const keys=(fields.length>0?fields:[{name:"title",type:"string"}]).map((f)=>`'${f.name}'`).join(", ");return`import { Action } from '@stacksjs/actions'
|
|
112
25
|
import ${Model} from '~/app/Models/${Model}'
|
|
113
26
|
|
|
114
27
|
export default new Action({
|
|
@@ -119,11 +32,7 @@ export default new Action({
|
|
|
119
32
|
const data = request.only([${keys}])
|
|
120
33
|
return await ${Model}.create(data)
|
|
121
34
|
},
|
|
122
|
-
})
|
|
123
|
-
}
|
|
124
|
-
case "Update": {
|
|
125
|
-
const keys = (fields.length > 0 ? fields : [{ name: "title", type: "string" }]).map((f) => `'${f.name}'`).join(", ");
|
|
126
|
-
return `import { Action } from '@stacksjs/actions'
|
|
35
|
+
})`}case"Update":{const keys=(fields.length>0?fields:[{name:"title",type:"string"}]).map((f)=>`'${f.name}'`).join(", ");return`import { Action } from '@stacksjs/actions'
|
|
127
36
|
import ${Model} from '~/app/Models/${Model}'
|
|
128
37
|
|
|
129
38
|
export default new Action({
|
|
@@ -135,10 +44,7 @@ export default new Action({
|
|
|
135
44
|
const data = request.only([${keys}])
|
|
136
45
|
return await ${Model}.update(id, data)
|
|
137
46
|
},
|
|
138
|
-
})
|
|
139
|
-
}
|
|
140
|
-
case "Destroy":
|
|
141
|
-
return `import { Action } from '@stacksjs/actions'
|
|
47
|
+
})`}case"Destroy":return`import { Action } from '@stacksjs/actions'
|
|
142
48
|
import ${Model} from '~/app/Models/${Model}'
|
|
143
49
|
|
|
144
50
|
export default new Action({
|
|
@@ -150,11 +56,7 @@ export default new Action({
|
|
|
150
56
|
const deleted = await ${Model}.delete(id)
|
|
151
57
|
return { deleted }
|
|
152
58
|
},
|
|
153
|
-
})
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
function modelStub(name, fields) {
|
|
157
|
-
return `import { defineModel } from '@stacksjs/orm'
|
|
59
|
+
})`}}function modelStub(name,fields){return`import { defineModel } from '@stacksjs/orm'
|
|
158
60
|
import { schema } from '@stacksjs/validation'
|
|
159
61
|
|
|
160
62
|
export default defineModel({
|
|
@@ -165,10 +67,7 @@ ${attributeBlock(fields)}
|
|
|
165
67
|
},
|
|
166
68
|
traits: { useTimestamps: true, useUuid: false },
|
|
167
69
|
} as const)
|
|
168
|
-
|
|
169
|
-
}
|
|
170
|
-
function migrationStub(name, fields) {
|
|
171
|
-
return `import type { Database } from '@stacksjs/database'
|
|
70
|
+
`}function migrationStub(name,fields){return`import type { Database } from '@stacksjs/database'
|
|
172
71
|
import { sql } from '@stacksjs/database'
|
|
173
72
|
|
|
174
73
|
export async function up(db: Database<any>) {
|
|
@@ -180,32 +79,8 @@ ${migrationColumns(fields)}
|
|
|
180
79
|
.addColumn('updated_at', 'timestamp')
|
|
181
80
|
.execute()
|
|
182
81
|
}
|
|
183
|
-
|
|
184
|
-
}
|
|
185
|
-
async function writeFile(path, contents) {
|
|
186
|
-
if (isDryRunActive()) {
|
|
187
|
-
const lines = contents.split(`
|
|
188
|
-
`);
|
|
189
|
-
log.info(`[dry-run] would write ${path} (${lines.length} lines)`);
|
|
190
|
-
process.stdout.write(`${lines.slice(0, 60).map((l) => ` ${l}`).join(`
|
|
82
|
+
`}async function writeFile(path,contents){if(isDryRunActive()){const lines=contents.split(`
|
|
83
|
+
`);log.info(`[dry-run] would write ${path} (${lines.length} lines)`);process.stdout.write(`${lines.slice(0,60).map((l)=>` ${l}`).join(`
|
|
191
84
|
`)}
|
|
192
85
|
|
|
193
|
-
`);
|
|
194
|
-
return;
|
|
195
|
-
}
|
|
196
|
-
await writeTextFile({ path, data: contents });
|
|
197
|
-
}
|
|
198
|
-
export async function scaffoldCrud(name, options) {
|
|
199
|
-
const Model = pascalCase(name);
|
|
200
|
-
if (!Model)
|
|
201
|
-
throw Error("scaffold:crud requires a non-empty resource name");
|
|
202
|
-
const fields = parseFields(options.fields);
|
|
203
|
-
log.info(`Scaffolding CRUD for ${italic(Model)} (${fields.length || "no"} fields)`);
|
|
204
|
-
await writeFile(p.userModelsPath(`${Model}.ts`), modelStub(Model, fields));
|
|
205
|
-
const migrationName = `${Date.now().toString()}-create-${pluralize(snakeCase(name))}-table.ts`;
|
|
206
|
-
await writeFile(p.userMigrationsPath(migrationName), migrationStub(name, fields));
|
|
207
|
-
for (const kind of ["Index", "Show", "Store", "Update", "Destroy"])
|
|
208
|
-
await writeFile(p.userActionsPath(`${Model}${kind}Action.ts`), actionStub(name, kind, fields));
|
|
209
|
-
log.success(`CRUD scaffold complete: model + migration + 5 actions for ${Model}`);
|
|
210
|
-
log.info(`Next: register \`route.resource('${pluralize(snakeCase(name))}', '${Model}')\` in routes/api.ts`);
|
|
211
|
-
}
|
|
86
|
+
`);return}await writeTextFile({path,data:contents})}export async function scaffoldCrud(name,options){const Model=pascalCase(name);if(!Model)throw Error("scaffold:crud requires a non-empty resource name");const fields=parseFields(options.fields);log.info(`Scaffolding CRUD for ${italic(Model)} (${fields.length||"no"} fields)`);await writeFile(p.userModelsPath(`${Model}.ts`),modelStub(Model,fields));const migrationName=`${Date.now().toString()}-create-${pluralize(snakeCase(name))}-table.ts`;await writeFile(p.userMigrationsPath(migrationName),migrationStub(name,fields));for(const kind of["Index","Show","Store","Update","Destroy"])await writeFile(p.userActionsPath(`${Model}${kind}Action.ts`),actionStub(name,kind,fields));log.success(`CRUD scaffold complete: model + migration + 5 actions for ${Model}`);log.info(`Next: register \`route.resource('${pluralize(snakeCase(name))}', '${Model}')\` in routes/api.ts`)}
|
package/dist/schedule/run.js
CHANGED
|
@@ -1,7 +1 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { runScheduler } from "@stacksjs/scheduler";
|
|
3
|
-
const result = await runScheduler();
|
|
4
|
-
if (result?.isErr) {
|
|
5
|
-
console.error(result.error);
|
|
6
|
-
log.error("Schedule run failed", result.error);
|
|
7
|
-
}
|
|
1
|
+
import{log}from"@stacksjs/logging";import{runScheduler}from"@stacksjs/scheduler";const result=await runScheduler();if(result?.isErr){console.error(result.error);log.error("Schedule run failed",result.error)}
|
package/dist/search/flush.js
CHANGED
|
@@ -1,10 +1 @@
|
|
|
1
|
-
import process from
|
|
2
|
-
import { parseOptions } from "@stacksjs/cli";
|
|
3
|
-
import { log } from "@stacksjs/logging";
|
|
4
|
-
import { flushModelDocuments } from "@stacksjs/search-engine";
|
|
5
|
-
const options = parseOptions(), modelOption = options.model, result = await flushModelDocuments(modelOption);
|
|
6
|
-
if (result?.isErr) {
|
|
7
|
-
console.error(result.error);
|
|
8
|
-
log.error("Flushing search engine failed", result.error);
|
|
9
|
-
}
|
|
10
|
-
process.exit(0);
|
|
1
|
+
import process from"node:process";import{parseOptions}from"@stacksjs/cli";import{log}from"@stacksjs/logging";import{flushModelDocuments}from"@stacksjs/search-engine";const options=parseOptions(),modelOption=options.model,result=await flushModelDocuments(modelOption);if(result?.isErr){console.error(result.error);log.error("Flushing search engine failed",result.error)}process.exit(0);
|
package/dist/search/import.js
CHANGED
|
@@ -1,10 +1 @@
|
|
|
1
|
-
import process from
|
|
2
|
-
import { parseOptions } from "@stacksjs/cli";
|
|
3
|
-
import { log } from "@stacksjs/logging";
|
|
4
|
-
import { importModelDocuments } from "@stacksjs/search-engine";
|
|
5
|
-
const options = parseOptions(), modelOption = options.model, result = await importModelDocuments(modelOption);
|
|
6
|
-
if (result?.isErr) {
|
|
7
|
-
console.error(result.error);
|
|
8
|
-
log.error("Import to search engine failed", result.error);
|
|
9
|
-
}
|
|
10
|
-
process.exit(0);
|
|
1
|
+
import process from"node:process";import{parseOptions}from"@stacksjs/cli";import{log}from"@stacksjs/logging";import{importModelDocuments}from"@stacksjs/search-engine";const options=parseOptions(),modelOption=options.model,result=await importModelDocuments(modelOption);if(result?.isErr){console.error(result.error);log.error("Import to search engine failed",result.error)}process.exit(0);
|
|
@@ -1,10 +1 @@
|
|
|
1
|
-
import process from
|
|
2
|
-
import { parseOptions } from "@stacksjs/cli";
|
|
3
|
-
import { log } from "@stacksjs/logging";
|
|
4
|
-
import { listIndexSettings } from "@stacksjs/search-engine";
|
|
5
|
-
const options = parseOptions(), modelOption = options.model, result = await listIndexSettings(modelOption);
|
|
6
|
-
if (result?.isErr) {
|
|
7
|
-
console.error(result.error);
|
|
8
|
-
log.error("Listing index settings failed", result.error);
|
|
9
|
-
}
|
|
10
|
-
process.exit(0);
|
|
1
|
+
import process from"node:process";import{parseOptions}from"@stacksjs/cli";import{log}from"@stacksjs/logging";import{listIndexSettings}from"@stacksjs/search-engine";const options=parseOptions(),modelOption=options.model,result=await listIndexSettings(modelOption);if(result?.isErr){console.error(result.error);log.error("Listing index settings failed",result.error)}process.exit(0);
|
package/dist/search/settings.js
CHANGED
|
@@ -1,9 +1 @@
|
|
|
1
|
-
import process from
|
|
2
|
-
import { log } from "@stacksjs/logging";
|
|
3
|
-
import { updateIndexSettings } from "@stacksjs/search-engine";
|
|
4
|
-
const result = await updateIndexSettings();
|
|
5
|
-
if (result?.isErr) {
|
|
6
|
-
console.error(result.error);
|
|
7
|
-
log.error("generateMigrations failed", result.error);
|
|
8
|
-
}
|
|
9
|
-
process.exit(0);
|
|
1
|
+
import process from"node:process";import{log}from"@stacksjs/logging";import{updateIndexSettings}from"@stacksjs/search-engine";const result=await updateIndexSettings();if(result?.isErr){console.error(result.error);log.error("generateMigrations failed",result.error)}process.exit(0);
|
package/dist/serve/api.js
CHANGED
|
@@ -1,37 +1 @@
|
|
|
1
|
-
import { existsSync }
|
|
2
|
-
import { dirname, join } from "node:path";
|
|
3
|
-
import process from "node:process";
|
|
4
|
-
import { config, overridesReady } from "@stacksjs/config";
|
|
5
|
-
import { log } from "@stacksjs/logging";
|
|
6
|
-
import { frameworkPath } from "@stacksjs/path";
|
|
7
|
-
import { route } from "@stacksjs/router";
|
|
8
|
-
import { resolveApiHost } from "../helpers/api-host";
|
|
9
|
-
function resolveDefaultsFile(rel) {
|
|
10
|
-
const vendored = frameworkPath(`defaults/${rel}`);
|
|
11
|
-
if (existsSync(vendored))
|
|
12
|
-
return vendored;
|
|
13
|
-
try {
|
|
14
|
-
const pkgJson = Bun.resolveSync("@stacksjs/defaults/package.json", process.cwd());
|
|
15
|
-
return join(dirname(pkgJson), rel);
|
|
16
|
-
} catch {
|
|
17
|
-
return vendored;
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
await overridesReady;
|
|
21
|
-
const port = Number(process.env.PORT) || config.ports?.api || 3008, hostname = resolveApiHost();
|
|
22
|
-
log.info("[Stacks API] Starting server...");
|
|
23
|
-
log.info(`[Stacks API] Environment: ${process.env.APP_ENV || "development"}`);
|
|
24
|
-
const corsMod = await import(resolveDefaultsFile("app/Middleware/Cors.ts")), corsMiddleware = corsMod.default;
|
|
25
|
-
route.use(corsMiddleware.toRouterHandler());
|
|
26
|
-
await route.importRoutes();
|
|
27
|
-
const isDeployed = ["production", "staging", "development"].includes((process.env.APP_ENV || "").toLowerCase()), server = await route.serve({
|
|
28
|
-
port,
|
|
29
|
-
hostname,
|
|
30
|
-
reusePort: isDeployed
|
|
31
|
-
});
|
|
32
|
-
process.on("SIGTERM", () => {
|
|
33
|
-
const graceMs = Number(process.env.SHUTDOWN_GRACE_MS) || 15000;
|
|
34
|
-
setTimeout(() => process.exit(0), graceMs).unref();
|
|
35
|
-
Promise.resolve(server?.stop()).then(() => process.exit(0));
|
|
36
|
-
});
|
|
37
|
-
log.info(`[Stacks API] Server running at http://${hostname}:${port}`);
|
|
1
|
+
import{existsSync}from"node:fs";import{dirname,join}from"node:path";import process from"node:process";import{config,overridesReady}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{frameworkPath}from"@stacksjs/path";import{route}from"@stacksjs/router";import{resolveApiHost}from"../helpers/api-host";function resolveDefaultsFile(rel){const vendored=frameworkPath(`defaults/${rel}`);if(existsSync(vendored))return vendored;try{const pkgJson=Bun.resolveSync("@stacksjs/defaults/package.json",process.cwd());return join(dirname(pkgJson),rel)}catch{return vendored}}await overridesReady;const port=Number(process.env.PORT)||config.ports?.api||3008,hostname=resolveApiHost();log.info("[Stacks API] Starting server...");log.info(`[Stacks API] Environment: ${process.env.APP_ENV||"development"}`);const corsMod=await import(resolveDefaultsFile("app/Middleware/Cors.ts")),corsMiddleware=corsMod.default;route.use(corsMiddleware.toRouterHandler());await route.importRoutes();const isDeployed=["production","staging","development"].includes((process.env.APP_ENV||"").toLowerCase()),server=await route.serve({port,hostname,reusePort:isDeployed});process.on("SIGTERM",()=>{const graceMs=Number(process.env.SHUTDOWN_GRACE_MS)||15000;setTimeout(()=>process.exit(0),graceMs).unref();Promise.resolve(server?.stop()).then(()=>process.exit(0))});log.info(`[Stacks API] Server running at http://${hostname}:${port}`);
|
package/dist/setup/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export
|
|
1
|
+
export*from"./ssl";
|
package/dist/setup/ssl.js
CHANGED
|
@@ -1,271 +1,5 @@
|
|
|
1
|
-
import
|
|
2
|
-
import fs from "node:fs";
|
|
3
|
-
import os from "node:os";
|
|
4
|
-
import path from "node:path";
|
|
5
|
-
import process from "node:process";
|
|
6
|
-
import { log } from "@stacksjs/cli";
|
|
7
|
-
const HOSTS_FILE = process.platform === "win32" ? path.join(process.env.windir || "C:\\Windows", "System32", "drivers", "etc", "hosts") : "/etc/hosts", SSL_DIR = path.join(os.homedir(), ".stacks", "ssl");
|
|
8
|
-
function isInteractiveTerminal() {
|
|
9
|
-
return process.stdin.isTTY === !0 && process.stdout.isTTY === !0;
|
|
10
|
-
}
|
|
11
|
-
function getSudoPassword() {
|
|
12
|
-
return process.env.SUDO_PASSWORD;
|
|
13
|
-
}
|
|
14
|
-
function canRunSudo() {
|
|
15
|
-
return isInteractiveTerminal() || !!getSudoPassword();
|
|
16
|
-
}
|
|
17
|
-
export function isDomainInHosts(domain) {
|
|
18
|
-
try {
|
|
19
|
-
const hostsContent = fs.readFileSync(HOSTS_FILE, "utf-8");
|
|
20
|
-
return hostsContent.includes(`127.0.0.1 ${domain}`) || hostsContent.includes(`::1 ${domain}`);
|
|
21
|
-
} catch {
|
|
22
|
-
if (process.platform !== "win32") {
|
|
23
|
-
const sudoPassword = getSudoPassword();
|
|
24
|
-
if (sudoPassword)
|
|
25
|
-
try {
|
|
26
|
-
const result = execSync(`echo '${sudoPassword}' | sudo -S cat "${HOSTS_FILE}" 2>/dev/null`, { encoding: "utf-8" });
|
|
27
|
-
return result.includes(`127.0.0.1 ${domain}`) || result.includes(`::1 ${domain}`);
|
|
28
|
-
} catch {
|
|
29
|
-
return !1;
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
return !1;
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
export async function addDomainToHosts(domain, verbose) {
|
|
36
|
-
if (isDomainInHosts(domain)) {
|
|
37
|
-
if (verbose)
|
|
38
|
-
log.info(`${domain} already in hosts file`);
|
|
39
|
-
return !0;
|
|
40
|
-
}
|
|
41
|
-
const hostsEntry = `
|
|
1
|
+
import{execSync,spawn}from"node:child_process";import fs from"node:fs";import os from"node:os";import path from"node:path";import process from"node:process";import{log}from"@stacksjs/cli";const HOSTS_FILE=process.platform==="win32"?path.join(process.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",SSL_DIR=path.join(os.homedir(),".stacks","ssl");function isInteractiveTerminal(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function getSudoPassword(){return process.env.SUDO_PASSWORD}function canRunSudo(){return isInteractiveTerminal()||!!getSudoPassword()}export function isDomainInHosts(domain){try{const hostsContent=fs.readFileSync(HOSTS_FILE,"utf-8");return hostsContent.includes(`127.0.0.1 ${domain}`)||hostsContent.includes(`::1 ${domain}`)}catch{if(process.platform!=="win32"){const sudoPassword=getSudoPassword();if(sudoPassword)try{const result=execSync(`echo '${sudoPassword}' | sudo -S cat "${HOSTS_FILE}" 2>/dev/null`,{encoding:"utf-8"});return result.includes(`127.0.0.1 ${domain}`)||result.includes(`::1 ${domain}`)}catch{return!1}}return!1}}export async function addDomainToHosts(domain,verbose){if(isDomainInHosts(domain)){if(verbose)log.info(`${domain} already in hosts file`);return!0}const hostsEntry=`
|
|
42
2
|
# Added by Stacks
|
|
43
3
|
127.0.0.1 ${domain}
|
|
44
4
|
::1 ${domain}
|
|
45
|
-
`;
|
|
46
|
-
if (process.platform === "win32") {
|
|
47
|
-
log.warn("Please add this to your hosts file manually:");
|
|
48
|
-
log.warn(`127.0.0.1 ${domain}`);
|
|
49
|
-
log.warn(`::1 ${domain}`);
|
|
50
|
-
log.warn(`File location: ${HOSTS_FILE}`);
|
|
51
|
-
return !1;
|
|
52
|
-
}
|
|
53
|
-
if (!canRunSudo()) {
|
|
54
|
-
if (verbose) {
|
|
55
|
-
log.warn(`Cannot add ${domain} to hosts file (non-interactive mode and no SUDO_PASSWORD set)`);
|
|
56
|
-
log.info("Run `buddy setup:ssl` in a terminal or set SUDO_PASSWORD environment variable");
|
|
57
|
-
}
|
|
58
|
-
return !1;
|
|
59
|
-
}
|
|
60
|
-
const sudoPassword = getSudoPassword();
|
|
61
|
-
return new Promise((resolve) => {
|
|
62
|
-
let child;
|
|
63
|
-
if (sudoPassword)
|
|
64
|
-
child = spawn("sh", ["-c", `echo '${sudoPassword}' | sudo -S sh -c "echo '${hostsEntry}' >> '${HOSTS_FILE}'"`], {
|
|
65
|
-
stdio: ["pipe", "inherit", "inherit"]
|
|
66
|
-
});
|
|
67
|
-
else
|
|
68
|
-
child = spawn("sudo", ["sh", "-c", `echo '${hostsEntry}' >> "${HOSTS_FILE}"`], {
|
|
69
|
-
stdio: "inherit"
|
|
70
|
-
});
|
|
71
|
-
child.on("close", (code) => {
|
|
72
|
-
if (code === 0) {
|
|
73
|
-
if (verbose)
|
|
74
|
-
log.success(`Added ${domain} to hosts file`);
|
|
75
|
-
resolve(!0);
|
|
76
|
-
} else {
|
|
77
|
-
if (verbose) {
|
|
78
|
-
log.error(`Failed to add ${domain} to hosts file`);
|
|
79
|
-
log.warn(`Manually add: 127.0.0.1 ${domain}`);
|
|
80
|
-
}
|
|
81
|
-
resolve(!1);
|
|
82
|
-
}
|
|
83
|
-
});
|
|
84
|
-
child.on("error", () => {
|
|
85
|
-
log.error("Failed to run sudo command");
|
|
86
|
-
resolve(!1);
|
|
87
|
-
});
|
|
88
|
-
});
|
|
89
|
-
}
|
|
90
|
-
export function sslCertificatesExist(domain) {
|
|
91
|
-
const certPath = path.join(SSL_DIR, `${domain}.crt`), keyPath = path.join(SSL_DIR, `${domain}.key`), caPath = path.join(SSL_DIR, `${domain}.ca.crt`);
|
|
92
|
-
return fs.existsSync(certPath) && fs.existsSync(keyPath) && fs.existsSync(caPath);
|
|
93
|
-
}
|
|
94
|
-
export function isCertificateTrusted(domain) {
|
|
95
|
-
if (process.platform !== "darwin")
|
|
96
|
-
return !0;
|
|
97
|
-
const certPath = path.join(SSL_DIR, `${domain}.crt`);
|
|
98
|
-
if (!fs.existsSync(certPath))
|
|
99
|
-
return !1;
|
|
100
|
-
try {
|
|
101
|
-
const fingerprint = execSync(`openssl x509 -noout -fingerprint -sha256 -in "${certPath}"`, { encoding: "utf-8" }), eqIdx = fingerprint.indexOf("="), fingerprintValue = eqIdx >= 0 ? fingerprint.slice(eqIdx + 1).trim() : "";
|
|
102
|
-
if (!fingerprintValue)
|
|
103
|
-
return !1;
|
|
104
|
-
return execSync("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true", { encoding: "utf-8" }).includes(fingerprintValue);
|
|
105
|
-
} catch {
|
|
106
|
-
return !1;
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
export async function trustCertificate(domain, verbose) {
|
|
110
|
-
const caCertPath = path.join(SSL_DIR, `${domain}.ca.crt`), certPath = path.join(SSL_DIR, `${domain}.crt`);
|
|
111
|
-
if (!fs.existsSync(caCertPath)) {
|
|
112
|
-
log.error(`CA certificate not found: ${caCertPath}`);
|
|
113
|
-
return !1;
|
|
114
|
-
}
|
|
115
|
-
if (isCertificateTrusted(domain)) {
|
|
116
|
-
if (verbose)
|
|
117
|
-
log.info("Certificate is already trusted, skipping trust step");
|
|
118
|
-
return !0;
|
|
119
|
-
}
|
|
120
|
-
if (!canRunSudo()) {
|
|
121
|
-
if (verbose) {
|
|
122
|
-
log.warn("Cannot trust certificate (non-interactive mode and no SUDO_PASSWORD set)");
|
|
123
|
-
log.info("Run `buddy setup:ssl` in a terminal or set SUDO_PASSWORD environment variable");
|
|
124
|
-
}
|
|
125
|
-
return !1;
|
|
126
|
-
}
|
|
127
|
-
const sudoPassword = getSudoPassword();
|
|
128
|
-
if (process.platform === "darwin")
|
|
129
|
-
return new Promise((resolve) => {
|
|
130
|
-
const combinedCommand = `security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain '${caCertPath}' && security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain '${certPath}'`;
|
|
131
|
-
let child;
|
|
132
|
-
if (sudoPassword)
|
|
133
|
-
child = spawn("sh", ["-c", `echo '${sudoPassword}' | sudo -S sh -c "${combinedCommand}"`], {
|
|
134
|
-
stdio: ["pipe", "inherit", "inherit"]
|
|
135
|
-
});
|
|
136
|
-
else
|
|
137
|
-
child = spawn("sudo", ["sh", "-c", combinedCommand], {
|
|
138
|
-
stdio: "inherit"
|
|
139
|
-
});
|
|
140
|
-
child.on("close", (code) => {
|
|
141
|
-
if (code === 0) {
|
|
142
|
-
try {
|
|
143
|
-
execSync(`security add-trusted-cert -d -r trustRoot -k ~/Library/Keychains/login.keychain-db "${certPath}" 2>/dev/null || true`);
|
|
144
|
-
} catch {}
|
|
145
|
-
resolve(!0);
|
|
146
|
-
} else {
|
|
147
|
-
if (verbose) {
|
|
148
|
-
log.warn("Could not trust certificate automatically");
|
|
149
|
-
log.info(` sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "${caCertPath}"`);
|
|
150
|
-
}
|
|
151
|
-
resolve(!1);
|
|
152
|
-
}
|
|
153
|
-
});
|
|
154
|
-
child.on("error", () => {
|
|
155
|
-
log.error("Failed to run sudo command");
|
|
156
|
-
resolve(!1);
|
|
157
|
-
});
|
|
158
|
-
});
|
|
159
|
-
else if (process.platform === "linux")
|
|
160
|
-
return new Promise((resolve) => {
|
|
161
|
-
const linuxCommands = `mkdir -p /usr/local/share/ca-certificates/stacks && cp '${caCertPath}' /usr/local/share/ca-certificates/stacks/ && update-ca-certificates`;
|
|
162
|
-
let child;
|
|
163
|
-
if (sudoPassword)
|
|
164
|
-
child = spawn("sh", ["-c", `echo '${sudoPassword}' | sudo -S sh -c "${linuxCommands}"`], {
|
|
165
|
-
stdio: ["pipe", "inherit", "inherit"]
|
|
166
|
-
});
|
|
167
|
-
else
|
|
168
|
-
child = spawn("sudo", ["sh", "-c", linuxCommands], {
|
|
169
|
-
stdio: "inherit"
|
|
170
|
-
});
|
|
171
|
-
child.on("close", (code) => {
|
|
172
|
-
if (code === 0) {
|
|
173
|
-
log.success("Certificate trusted");
|
|
174
|
-
resolve(!0);
|
|
175
|
-
} else {
|
|
176
|
-
log.warn("Could not trust certificate automatically");
|
|
177
|
-
resolve(!1);
|
|
178
|
-
}
|
|
179
|
-
});
|
|
180
|
-
child.on("error", () => resolve(!1));
|
|
181
|
-
});
|
|
182
|
-
else if (process.platform === "win32") {
|
|
183
|
-
log.warn("Please manually trust the certificate in Windows:");
|
|
184
|
-
log.warn(` 1. Double-click: ${caCertPath}`);
|
|
185
|
-
log.warn(' 2. Click "Install Certificate"');
|
|
186
|
-
log.warn(' 3. Select "Local Machine" and place in "Trusted Root Certification Authorities"');
|
|
187
|
-
return !1;
|
|
188
|
-
}
|
|
189
|
-
return !1;
|
|
190
|
-
}
|
|
191
|
-
export async function generateCertificates(domain, verbose) {
|
|
192
|
-
try {
|
|
193
|
-
const tlsxModule = await import("@stacksjs/tlsx"), { generateCertificate, createRootCA } = tlsxModule, _httpsConfig = tlsxModule.httpsConfig;
|
|
194
|
-
if (!fs.existsSync(SSL_DIR))
|
|
195
|
-
fs.mkdirSync(SSL_DIR, { recursive: !0 });
|
|
196
|
-
const config = {
|
|
197
|
-
domain,
|
|
198
|
-
hostCertCN: domain,
|
|
199
|
-
basePath: SSL_DIR,
|
|
200
|
-
caCertPath: path.join(SSL_DIR, `${domain}.ca.crt`),
|
|
201
|
-
certPath: path.join(SSL_DIR, `${domain}.crt`),
|
|
202
|
-
keyPath: path.join(SSL_DIR, `${domain}.key`),
|
|
203
|
-
altNameIPs: ["127.0.0.1", "::1"],
|
|
204
|
-
altNameURIs: ["localhost", domain],
|
|
205
|
-
organizationName: "Stacks Development",
|
|
206
|
-
countryName: "US",
|
|
207
|
-
stateName: "California",
|
|
208
|
-
localityName: "Playa Vista",
|
|
209
|
-
commonName: domain,
|
|
210
|
-
validityDays: 825,
|
|
211
|
-
verbose: verbose || !1,
|
|
212
|
-
subjectAltNames: [
|
|
213
|
-
{ type: 2, value: domain },
|
|
214
|
-
{ type: 2, value: `*.${domain.split(".").slice(1).join(".")}` },
|
|
215
|
-
{ type: 2, value: "localhost" },
|
|
216
|
-
{ type: 2, value: "*.localhost" }
|
|
217
|
-
]
|
|
218
|
-
};
|
|
219
|
-
if (verbose)
|
|
220
|
-
log.info("Generating Root CA certificate...");
|
|
221
|
-
const caCert = await createRootCA(config);
|
|
222
|
-
if (verbose)
|
|
223
|
-
log.info(`Generating host certificate for ${domain}...`);
|
|
224
|
-
const hostCert = await generateCertificate({
|
|
225
|
-
...config,
|
|
226
|
-
rootCA: {
|
|
227
|
-
certificate: caCert.certificate,
|
|
228
|
-
privateKey: caCert.privateKey
|
|
229
|
-
}
|
|
230
|
-
});
|
|
231
|
-
fs.writeFileSync(config.caCertPath, caCert.certificate);
|
|
232
|
-
fs.writeFileSync(config.certPath, hostCert.certificate);
|
|
233
|
-
fs.writeFileSync(config.keyPath, hostCert.privateKey);
|
|
234
|
-
if (verbose)
|
|
235
|
-
log.success(`SSL certificates generated for ${domain}`);
|
|
236
|
-
return !0;
|
|
237
|
-
} catch (error) {
|
|
238
|
-
log.error(`Failed to generate certificates: ${error}`);
|
|
239
|
-
return !1;
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
export async function setupSSL(options = {}) {
|
|
243
|
-
const domain = options.domain || process.env.APP_URL?.replace(/^https?:\/\//, "") || "stacks.localhost";
|
|
244
|
-
if (domain === "localhost" || domain.startsWith("localhost:")) {
|
|
245
|
-
log.info("Skipping SSL setup for localhost");
|
|
246
|
-
return !0;
|
|
247
|
-
}
|
|
248
|
-
let success = !0;
|
|
249
|
-
if (!options.skipHosts) {
|
|
250
|
-
if (!await addDomainToHosts(domain, options.verbose) && options.verbose)
|
|
251
|
-
log.warn("Hosts file not updated - you may need to add the entry manually");
|
|
252
|
-
}
|
|
253
|
-
if (!sslCertificatesExist(domain)) {
|
|
254
|
-
if (options.verbose)
|
|
255
|
-
log.info("Generating SSL certificates...");
|
|
256
|
-
if (!await generateCertificates(domain, options.verbose)) {
|
|
257
|
-
log.error("Failed to generate SSL certificates");
|
|
258
|
-
return !1;
|
|
259
|
-
}
|
|
260
|
-
}
|
|
261
|
-
if (!options.skipTrust && !isCertificateTrusted(domain)) {
|
|
262
|
-
if (!await trustCertificate(domain, options.verbose)) {
|
|
263
|
-
log.warn("Certificate not trusted - you may see browser warnings");
|
|
264
|
-
success = !1;
|
|
265
|
-
}
|
|
266
|
-
}
|
|
267
|
-
return success;
|
|
268
|
-
}
|
|
269
|
-
export function isSSLSetupComplete(domain) {
|
|
270
|
-
return isDomainInHosts(domain) && sslCertificatesExist(domain);
|
|
271
|
-
}
|
|
5
|
+
`;if(process.platform==="win32"){log.warn("Please add this to your hosts file manually:");log.warn(`127.0.0.1 ${domain}`);log.warn(`::1 ${domain}`);log.warn(`File location: ${HOSTS_FILE}`);return!1}if(!canRunSudo()){if(verbose){log.warn(`Cannot add ${domain} to hosts file (non-interactive mode and no SUDO_PASSWORD set)`);log.info("Run `buddy setup:ssl` in a terminal or set SUDO_PASSWORD environment variable")}return!1}const sudoPassword=getSudoPassword();return new Promise((resolve)=>{let child;if(sudoPassword)child=spawn("sh",["-c",`echo '${sudoPassword}' | sudo -S sh -c "echo '${hostsEntry}' >> '${HOSTS_FILE}'"`],{stdio:["pipe","inherit","inherit"]});else child=spawn("sudo",["sh","-c",`echo '${hostsEntry}' >> "${HOSTS_FILE}"`],{stdio:"inherit"});child.on("close",(code)=>{if(code===0){if(verbose)log.success(`Added ${domain} to hosts file`);resolve(!0)}else{if(verbose){log.error(`Failed to add ${domain} to hosts file`);log.warn(`Manually add: 127.0.0.1 ${domain}`)}resolve(!1)}});child.on("error",()=>{log.error("Failed to run sudo command");resolve(!1)})})}export function sslCertificatesExist(domain){const certPath=path.join(SSL_DIR,`${domain}.crt`),keyPath=path.join(SSL_DIR,`${domain}.key`),caPath=path.join(SSL_DIR,`${domain}.ca.crt`);return fs.existsSync(certPath)&&fs.existsSync(keyPath)&&fs.existsSync(caPath)}export function isCertificateTrusted(domain){if(process.platform!=="darwin")return!0;const certPath=path.join(SSL_DIR,`${domain}.crt`);if(!fs.existsSync(certPath))return!1;try{const fingerprint=execSync(`openssl x509 -noout -fingerprint -sha256 -in "${certPath}"`,{encoding:"utf-8"}),eqIdx=fingerprint.indexOf("="),fingerprintValue=eqIdx>=0?fingerprint.slice(eqIdx+1).trim():"";if(!fingerprintValue)return!1;return execSync("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true",{encoding:"utf-8"}).includes(fingerprintValue)}catch{return!1}}export async function trustCertificate(domain,verbose){const caCertPath=path.join(SSL_DIR,`${domain}.ca.crt`),certPath=path.join(SSL_DIR,`${domain}.crt`);if(!fs.existsSync(caCertPath)){log.error(`CA certificate not found: ${caCertPath}`);return!1}if(isCertificateTrusted(domain)){if(verbose)log.info("Certificate is already trusted, skipping trust step");return!0}if(!canRunSudo()){if(verbose){log.warn("Cannot trust certificate (non-interactive mode and no SUDO_PASSWORD set)");log.info("Run `buddy setup:ssl` in a terminal or set SUDO_PASSWORD environment variable")}return!1}const sudoPassword=getSudoPassword();if(process.platform==="darwin")return new Promise((resolve)=>{const combinedCommand=`security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain '${caCertPath}' && security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain '${certPath}'`;let child;if(sudoPassword)child=spawn("sh",["-c",`echo '${sudoPassword}' | sudo -S sh -c "${combinedCommand}"`],{stdio:["pipe","inherit","inherit"]});else child=spawn("sudo",["sh","-c",combinedCommand],{stdio:"inherit"});child.on("close",(code)=>{if(code===0){try{execSync(`security add-trusted-cert -d -r trustRoot -k ~/Library/Keychains/login.keychain-db "${certPath}" 2>/dev/null || true`)}catch{}resolve(!0)}else{if(verbose){log.warn("Could not trust certificate automatically");log.info(` sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "${caCertPath}"`)}resolve(!1)}});child.on("error",()=>{log.error("Failed to run sudo command");resolve(!1)})});else if(process.platform==="linux")return new Promise((resolve)=>{const linuxCommands=`mkdir -p /usr/local/share/ca-certificates/stacks && cp '${caCertPath}' /usr/local/share/ca-certificates/stacks/ && update-ca-certificates`;let child;if(sudoPassword)child=spawn("sh",["-c",`echo '${sudoPassword}' | sudo -S sh -c "${linuxCommands}"`],{stdio:["pipe","inherit","inherit"]});else child=spawn("sudo",["sh","-c",linuxCommands],{stdio:"inherit"});child.on("close",(code)=>{if(code===0){log.success("Certificate trusted");resolve(!0)}else{log.warn("Could not trust certificate automatically");resolve(!1)}});child.on("error",()=>resolve(!1))});else if(process.platform==="win32"){log.warn("Please manually trust the certificate in Windows:");log.warn(` 1. Double-click: ${caCertPath}`);log.warn(' 2. Click "Install Certificate"');log.warn(' 3. Select "Local Machine" and place in "Trusted Root Certification Authorities"');return!1}return!1}export async function generateCertificates(domain,verbose){try{const tlsxModule=await import("@stacksjs/tlsx"),{generateCertificate,createRootCA}=tlsxModule,_httpsConfig=tlsxModule.httpsConfig;if(!fs.existsSync(SSL_DIR))fs.mkdirSync(SSL_DIR,{recursive:!0});const config={domain,hostCertCN:domain,basePath:SSL_DIR,caCertPath:path.join(SSL_DIR,`${domain}.ca.crt`),certPath:path.join(SSL_DIR,`${domain}.crt`),keyPath:path.join(SSL_DIR,`${domain}.key`),altNameIPs:["127.0.0.1","::1"],altNameURIs:["localhost",domain],organizationName:"Stacks Development",countryName:"US",stateName:"California",localityName:"Playa Vista",commonName:domain,validityDays:825,verbose:verbose||!1,subjectAltNames:[{type:2,value:domain},{type:2,value:`*.${domain.split(".").slice(1).join(".")}`},{type:2,value:"localhost"},{type:2,value:"*.localhost"}]};if(verbose)log.info("Generating Root CA certificate...");const caCert=await createRootCA(config);if(verbose)log.info(`Generating host certificate for ${domain}...`);const hostCert=await generateCertificate({...config,rootCA:{certificate:caCert.certificate,privateKey:caCert.privateKey}});fs.writeFileSync(config.caCertPath,caCert.certificate);fs.writeFileSync(config.certPath,hostCert.certificate);fs.writeFileSync(config.keyPath,hostCert.privateKey);if(verbose)log.success(`SSL certificates generated for ${domain}`);return!0}catch(error){log.error(`Failed to generate certificates: ${error}`);return!1}}export async function setupSSL(options={}){const domain=options.domain||process.env.APP_URL?.replace(/^https?:\/\//,"")||"stacks.localhost";if(domain==="localhost"||domain.startsWith("localhost:")){log.info("Skipping SSL setup for localhost");return!0}let success=!0;if(!options.skipHosts){if(!await addDomainToHosts(domain,options.verbose)&&options.verbose)log.warn("Hosts file not updated - you may need to add the entry manually")}if(!sslCertificatesExist(domain)){if(options.verbose)log.info("Generating SSL certificates...");if(!await generateCertificates(domain,options.verbose)){log.error("Failed to generate SSL certificates");return!1}}if(!options.skipTrust&&!isCertificateTrusted(domain)){if(!await trustCertificate(domain,options.verbose)){log.warn("Certificate not trusted - you may see browser warnings");success=!1}}return success}export function isSSLSetupComplete(domain){return isDomainInHosts(domain)&&sslCertificatesExist(domain)}
|