@weft-framework/server 0.0.0-stage → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +4 -2
  3. package/dist/account.d.ts +124 -0
  4. package/dist/account.js +344 -0
  5. package/dist/action.d.ts +43 -0
  6. package/dist/action.js +135 -0
  7. package/dist/admin.d.ts +99 -0
  8. package/dist/admin.js +431 -0
  9. package/dist/api.d.ts +21 -0
  10. package/dist/api.js +72 -0
  11. package/dist/app.d.ts +202 -0
  12. package/dist/app.js +3692 -0
  13. package/dist/assets.d.ts +4 -0
  14. package/dist/assets.js +91 -0
  15. package/dist/auth.d.ts +150 -0
  16. package/dist/auth.js +215 -0
  17. package/dist/backup.d.ts +46 -0
  18. package/dist/backup.js +345 -0
  19. package/dist/build.d.ts +33 -0
  20. package/dist/build.js +274 -0
  21. package/dist/bun.d.ts +30 -0
  22. package/dist/bun.js +53 -0
  23. package/dist/calendar.d.ts +161 -0
  24. package/dist/calendar.js +690 -0
  25. package/dist/compiler.d.ts +13 -0
  26. package/dist/compiler.js +58 -0
  27. package/dist/compress.d.ts +6 -0
  28. package/dist/compress.js +78 -0
  29. package/dist/config.d.ts +26 -0
  30. package/dist/config.js +317 -0
  31. package/dist/context.d.ts +9 -0
  32. package/dist/context.js +1 -0
  33. package/dist/contract.d.ts +18 -0
  34. package/dist/contract.js +171 -0
  35. package/dist/datamap.d.ts +24 -0
  36. package/dist/datamap.js +365 -0
  37. package/dist/db-backup.d.ts +27 -0
  38. package/dist/db-backup.js +115 -0
  39. package/dist/dev-events.d.ts +14 -0
  40. package/dist/dev-events.js +135 -0
  41. package/dist/dev.d.ts +1 -0
  42. package/dist/dev.js +240 -0
  43. package/dist/devtools-client.d.ts +1 -0
  44. package/dist/devtools-client.js +362 -0
  45. package/dist/devtools.d.ts +87 -0
  46. package/dist/devtools.js +68 -0
  47. package/dist/edge.d.ts +3 -0
  48. package/dist/edge.js +7 -0
  49. package/dist/email-signin.d.ts +92 -0
  50. package/dist/email-signin.js +259 -0
  51. package/dist/env.d.ts +1 -0
  52. package/dist/env.js +15 -0
  53. package/dist/explain.d.ts +12 -0
  54. package/dist/explain.js +217 -0
  55. package/dist/files.d.ts +6 -0
  56. package/dist/files.js +170 -0
  57. package/dist/grants.d.ts +69 -0
  58. package/dist/grants.js +206 -0
  59. package/dist/image/bitmap.d.ts +11 -0
  60. package/dist/image/bitmap.js +172 -0
  61. package/dist/image/jpeg.d.ts +10 -0
  62. package/dist/image/jpeg.js +697 -0
  63. package/dist/image/png.d.ts +8 -0
  64. package/dist/image/png.js +282 -0
  65. package/dist/image/transform.d.ts +20 -0
  66. package/dist/image/transform.js +52 -0
  67. package/dist/image/worker.d.ts +1 -0
  68. package/dist/image/worker.js +11 -0
  69. package/dist/images.d.ts +39 -0
  70. package/dist/images.js +283 -0
  71. package/dist/index.d.ts +64 -0
  72. package/dist/index.js +31 -0
  73. package/dist/inspect-hub.d.ts +42 -0
  74. package/dist/inspect-hub.js +14 -0
  75. package/dist/inspector.d.ts +51 -0
  76. package/dist/inspector.js +193 -0
  77. package/dist/job-admin.d.ts +55 -0
  78. package/dist/job-admin.js +89 -0
  79. package/dist/jobs.d.ts +222 -0
  80. package/dist/jobs.js +789 -0
  81. package/dist/live.d.ts +72 -0
  82. package/dist/live.js +481 -0
  83. package/dist/load-config.d.ts +2 -0
  84. package/dist/load-config.js +41 -0
  85. package/dist/log.d.ts +20 -0
  86. package/dist/log.js +143 -0
  87. package/dist/mail.d.ts +189 -0
  88. package/dist/mail.js +999 -0
  89. package/dist/media.d.ts +129 -0
  90. package/dist/media.js +470 -0
  91. package/dist/meta.d.ts +54 -0
  92. package/dist/meta.js +146 -0
  93. package/dist/middleware.d.ts +20 -0
  94. package/dist/middleware.js +101 -0
  95. package/dist/migrate.d.ts +12 -0
  96. package/dist/migrate.js +88 -0
  97. package/dist/node.d.ts +26 -0
  98. package/dist/node.js +96 -0
  99. package/dist/notice.d.ts +21 -0
  100. package/dist/notice.js +48 -0
  101. package/dist/npm.d.ts +16 -0
  102. package/dist/npm.js +347 -0
  103. package/dist/oauth.d.ts +76 -0
  104. package/dist/oauth.js +408 -0
  105. package/dist/otel.d.ts +57 -0
  106. package/dist/otel.js +293 -0
  107. package/dist/passkey.d.ts +99 -0
  108. package/dist/passkey.js +572 -0
  109. package/dist/password.d.ts +8 -0
  110. package/dist/password.js +65 -0
  111. package/dist/pdf.d.ts +46 -0
  112. package/dist/pdf.js +332 -0
  113. package/dist/personal-data.d.ts +22 -0
  114. package/dist/personal-data.js +148 -0
  115. package/dist/pointers.d.ts +9 -0
  116. package/dist/pointers.js +148 -0
  117. package/dist/postcss.d.ts +3 -0
  118. package/dist/postcss.js +89 -0
  119. package/dist/presence.d.ts +27 -0
  120. package/dist/presence.js +161 -0
  121. package/dist/preview.d.ts +25 -0
  122. package/dist/preview.js +353 -0
  123. package/dist/production.d.ts +16 -0
  124. package/dist/production.js +119 -0
  125. package/dist/project.d.ts +23 -0
  126. package/dist/project.js +536 -0
  127. package/dist/regions.d.ts +47 -0
  128. package/dist/regions.js +511 -0
  129. package/dist/replay.d.ts +44 -0
  130. package/dist/replay.js +259 -0
  131. package/dist/router.d.ts +29 -0
  132. package/dist/router.js +146 -0
  133. package/dist/rules-diff.d.ts +18 -0
  134. package/dist/rules-diff.js +165 -0
  135. package/dist/rules-test.d.ts +17 -0
  136. package/dist/rules-test.js +108 -0
  137. package/dist/saml.d.ts +160 -0
  138. package/dist/saml.js +959 -0
  139. package/dist/seal.d.ts +35 -0
  140. package/dist/seal.js +107 -0
  141. package/dist/secret.d.ts +14 -0
  142. package/dist/secret.js +110 -0
  143. package/dist/security.d.ts +53 -0
  144. package/dist/security.js +250 -0
  145. package/dist/seed.d.ts +16 -0
  146. package/dist/seed.js +94 -0
  147. package/dist/seo.d.ts +42 -0
  148. package/dist/seo.js +175 -0
  149. package/dist/settings.d.ts +79 -0
  150. package/dist/settings.js +212 -0
  151. package/dist/shared.d.ts +15 -0
  152. package/dist/shared.js +283 -0
  153. package/dist/shell.d.ts +12 -0
  154. package/dist/shell.js +118 -0
  155. package/dist/storage.d.ts +13 -0
  156. package/dist/storage.js +55 -0
  157. package/dist/support.d.ts +83 -0
  158. package/dist/support.js +236 -0
  159. package/dist/sync.d.ts +35 -0
  160. package/dist/sync.js +167 -0
  161. package/dist/tailwind.d.ts +14 -0
  162. package/dist/tailwind.js +117 -0
  163. package/dist/two-factor.d.ts +103 -0
  164. package/dist/two-factor.js +435 -0
  165. package/dist/uploads.d.ts +185 -0
  166. package/dist/uploads.js +991 -0
  167. package/dist/webhooks.d.ts +169 -0
  168. package/dist/webhooks.js +758 -0
  169. package/dist/webpush.d.ts +97 -0
  170. package/dist/webpush.js +372 -0
  171. package/dist/wizard.d.ts +141 -0
  172. package/dist/wizard.js +410 -0
  173. package/dist/workflows.d.ts +134 -0
  174. package/dist/workflows.js +511 -0
  175. package/package.json +186 -4
@@ -0,0 +1,89 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { existsSync } from "node:fs";
10
+ import { createRequire } from "node:module";
11
+ import { join } from "node:path";
12
+ import { pathToFileURL } from "node:url";
13
+ import { StyleError } from "./tailwind.js";
14
+ const CONFIGS = ["postcss.config.js", "postcss.config.mjs", "postcss.config.cjs"];
15
+ const TAILWIND_PLUGINS = new Set(["@tailwindcss/postcss", "tailwindcss"]);
16
+ export function postcssConfig(root) {
17
+ for (const name of CONFIGS) {
18
+ const file = join(root, name);
19
+ if (existsSync(file))
20
+ return file;
21
+ }
22
+ return null;
23
+ }
24
+ const unwrap = (m) => (m && "default" in m ? m.default : m);
25
+ export async function loadPostcss(root, production) {
26
+ const file = postcssConfig(root);
27
+ if (!file)
28
+ return null;
29
+ const name = file.slice(root.length + 1);
30
+ const req = createRequire(join(root, "package.json"));
31
+ let postcssPath;
32
+ try {
33
+ postcssPath = req.resolve("postcss");
34
+ }
35
+ catch {
36
+ throw new StyleError(`${name} found, but postcss is not installed; add it: \`npm install -D postcss\``);
37
+ }
38
+ const postcss = unwrap(await import(__rewriteRelativeImportExtension(pathToFileURL(postcssPath).href)));
39
+ let config;
40
+ try {
41
+ config = unwrap(await import(__rewriteRelativeImportExtension(`${pathToFileURL(file).href}?t=${Date.now()}`)));
42
+ if (typeof config === "function") {
43
+ config = await config({ env: production ? "production" : "development", file });
44
+ }
45
+ }
46
+ catch (err) {
47
+ throw new StyleError(`${name}: ${err.message}`);
48
+ }
49
+ const plugins = [];
50
+ const raw = config?.plugins ?? [];
51
+ if (Array.isArray(raw)) {
52
+ for (const p of raw) {
53
+ if (!p)
54
+ continue;
55
+ const id = p.postcssPlugin;
56
+ if (id !== undefined && /^(@tailwindcss\/postcss|tailwindcss)$/.test(id))
57
+ continue;
58
+ plugins.push(p);
59
+ }
60
+ }
61
+ else if (typeof raw === "object") {
62
+ for (const [plugin, opts] of Object.entries(raw)) {
63
+ if (opts === false || TAILWIND_PLUGINS.has(plugin))
64
+ continue;
65
+ let factory;
66
+ try {
67
+ factory = unwrap(await import(__rewriteRelativeImportExtension(pathToFileURL(req.resolve(plugin)).href)));
68
+ }
69
+ catch {
70
+ throw new StyleError(`${name} uses ${plugin}, but it is not installed; add it: \`npm install -D ${plugin}\``);
71
+ }
72
+ plugins.push(typeof factory === "function" ? factory(opts === true ? {} : opts) : factory);
73
+ }
74
+ }
75
+ else {
76
+ throw new StyleError(`${name}: \`plugins\` must be an object or an array`);
77
+ }
78
+ if (plugins.length === 0)
79
+ return null;
80
+ const processor = postcss(plugins);
81
+ return async (css, from) => {
82
+ try {
83
+ return (await processor.process(css, { from, map: false })).css;
84
+ }
85
+ catch (err) {
86
+ throw new StyleError(`postcss (${from}): ${err.message}`);
87
+ }
88
+ };
89
+ }
@@ -0,0 +1,27 @@
1
+ import type { PageContext } from "./context.js";
2
+ export interface Presence<I> {
3
+ readonly name: string;
4
+ join(ctx: PageContext, room: string, info: I): void;
5
+ in(room: string): readonly I[];
6
+ }
7
+ export interface PresenceOptions<I = unknown> {
8
+ maxRooms?: number;
9
+ pointers?: {
10
+ label?: (info: I) => string | null | undefined;
11
+ };
12
+ }
13
+ export declare function watchRooms(fn: (presence: string, room: string) => void): void;
14
+ export declare function pointerPresence(name: string): {
15
+ name: string;
16
+ label?: (info: unknown) => string | null | undefined;
17
+ } | null;
18
+ export declare function presenceIn(ctx: PageContext, name: string, room: string): {
19
+ info: unknown;
20
+ } | null;
21
+ export declare function definePresence<I>(name: string, opts?: PresenceOptions<I>): Presence<I>;
22
+ export declare function presenceStartAway(ctx: PageContext): void;
23
+ export declare function presenceBegin(ctx: PageContext): void;
24
+ export declare function presenceEnd(ctx: PageContext): void;
25
+ export declare function presenceHeld(ctx: PageContext): boolean;
26
+ export declare function presenceAway(ctx: PageContext, away: boolean): void;
27
+ export declare function presenceRelease(ctx: PageContext): void;
@@ -0,0 +1,161 @@
1
+ import { defineRoom } from "@weft-framework/runtime";
2
+ const members = new WeakMap();
3
+ class PresenceImpl {
4
+ name;
5
+ rooms;
6
+ here = new Map();
7
+ max;
8
+ pointers;
9
+ constructor(name, opts) {
10
+ this.name = name;
11
+ this.max = opts.maxRooms ?? 10_000;
12
+ this.pointers = opts.pointers;
13
+ this.rooms = defineRoom(`presence:${name}`, () => Object.freeze([]), { maxRooms: this.max + 1 });
14
+ }
15
+ join(ctx, room, info) {
16
+ const m = members.get(ctx);
17
+ if (!m) {
18
+ throw new Error(`@weft-framework/server: presence ${this.name}: join from the load of a live page`);
19
+ }
20
+ if (typeof room !== "string" || room === "" || room.length > 256) {
21
+ throw new Error(`@weft-framework/server: presence ${this.name}: a room is a string of 1-256 characters`);
22
+ }
23
+ let mine = m.recs.get(this);
24
+ if (!mine) {
25
+ mine = new Map();
26
+ m.recs.set(this, mine);
27
+ }
28
+ const json = JSON.stringify(info) ?? "";
29
+ const before = mine.get(room);
30
+ mine.set(room, { info, json, gen: m.gen });
31
+ if (visible(m) && before?.json !== json) {
32
+ this.put(m, room, info);
33
+ }
34
+ }
35
+ in(room) {
36
+ return this.rooms.in(room).value;
37
+ }
38
+ put(m, room, info) {
39
+ let set = this.here.get(room);
40
+ if (!set) {
41
+ if (this.here.size >= this.max) {
42
+ return;
43
+ }
44
+ set = new Map();
45
+ this.here.set(room, set);
46
+ }
47
+ set.set(m, info);
48
+ this.publish(room, set);
49
+ for (const fn of roomWatchers)
50
+ fn(this.name, room);
51
+ }
52
+ remove(m, room) {
53
+ const set = this.here.get(room);
54
+ if (!set?.delete(m))
55
+ return;
56
+ this.publish(room, set);
57
+ for (const fn of roomWatchers)
58
+ fn(this.name, room);
59
+ if (set.size === 0) {
60
+ this.here.delete(room);
61
+ }
62
+ }
63
+ publish(room, set) {
64
+ this.rooms.in(room).value = Object.freeze([...set.values()]);
65
+ }
66
+ }
67
+ const visible = (m) => !m.away;
68
+ const named = new Map();
69
+ const roomWatchers = new Set();
70
+ export function watchRooms(fn) {
71
+ roomWatchers.add(fn);
72
+ }
73
+ export function pointerPresence(name) {
74
+ const p = named.get(name);
75
+ return p?.pointers ? { name, ...(p.pointers.label ? { label: p.pointers.label } : {}) } : null;
76
+ }
77
+ export function presenceIn(ctx, name, room) {
78
+ const p = named.get(name);
79
+ const m = members.get(ctx);
80
+ if (!p || !m || !visible(m))
81
+ return null;
82
+ const rec = m.recs.get(p)?.get(room);
83
+ return rec ? { info: rec.info } : null;
84
+ }
85
+ export function definePresence(name, opts = {}) {
86
+ if (typeof name !== "string" || !/^[A-Za-z0-9_.-]{1,64}$/.test(name)) {
87
+ throw new Error("@weft-framework/server: a presence name is 1-64 letters, digits, `_`, `-` or `.`");
88
+ }
89
+ if (opts.pointers !== undefined && (typeof opts.pointers !== "object" || opts.pointers === null || (opts.pointers.label !== undefined && typeof opts.pointers.label !== "function"))) {
90
+ throw new Error("@weft-framework/server: presence `pointers` is `{ label?: (info) => string }`");
91
+ }
92
+ const p = new PresenceImpl(name, opts);
93
+ named.set(name, p);
94
+ return p;
95
+ }
96
+ export function presenceStartAway(ctx) {
97
+ if (!members.has(ctx)) {
98
+ members.set(ctx, { gen: 0, away: true, recs: new Map() });
99
+ }
100
+ }
101
+ export function presenceBegin(ctx) {
102
+ let m = members.get(ctx);
103
+ if (!m) {
104
+ m = { gen: 0, away: false, recs: new Map() };
105
+ members.set(ctx, m);
106
+ }
107
+ m.gen += 1;
108
+ }
109
+ export function presenceEnd(ctx) {
110
+ const m = members.get(ctx);
111
+ if (!m)
112
+ return;
113
+ for (const [p, mine] of m.recs) {
114
+ for (const [room, rec] of mine) {
115
+ if (rec.gen !== m.gen) {
116
+ mine.delete(room);
117
+ p.remove(m, room);
118
+ }
119
+ }
120
+ }
121
+ }
122
+ export function presenceHeld(ctx) {
123
+ const m = members.get(ctx);
124
+ if (!m)
125
+ return false;
126
+ for (const mine of m.recs.values()) {
127
+ if (mine.size > 0)
128
+ return true;
129
+ }
130
+ return false;
131
+ }
132
+ export function presenceAway(ctx, away) {
133
+ const m = members.get(ctx);
134
+ if (!m || m.away === away)
135
+ return;
136
+ m.away = away;
137
+ if (away)
138
+ hide(m);
139
+ else
140
+ show(m);
141
+ }
142
+ export function presenceRelease(ctx) {
143
+ const m = members.get(ctx);
144
+ if (!m)
145
+ return;
146
+ hide(m);
147
+ m.recs.clear();
148
+ members.delete(ctx);
149
+ }
150
+ function show(m) {
151
+ for (const [p, mine] of m.recs) {
152
+ for (const [room, rec] of mine)
153
+ p.put(m, room, rec.info);
154
+ }
155
+ }
156
+ function hide(m) {
157
+ for (const [p, mine] of m.recs) {
158
+ for (const room of mine.keys())
159
+ p.remove(m, room);
160
+ }
161
+ }
@@ -0,0 +1,25 @@
1
+ export declare class PreviewError extends Error {
2
+ }
3
+ export interface PreviewState {
4
+ name: string;
5
+ branch: string;
6
+ commit: string;
7
+ port: number;
8
+ url: string;
9
+ pid: number;
10
+ started: number;
11
+ }
12
+ export declare function previewName(branch: string): string;
13
+ export interface UpOptions {
14
+ branch: string;
15
+ url?: string;
16
+ port?: number;
17
+ reset?: boolean;
18
+ wait?: number;
19
+ log?: (line: string) => void;
20
+ }
21
+ export declare function previewUp(root: string, o: UpOptions): Promise<PreviewState>;
22
+ export declare function previewList(root: string): (PreviewState & {
23
+ running: boolean;
24
+ })[];
25
+ export declare function previewDown(root: string, branch: string): Promise<boolean>;
@@ -0,0 +1,353 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, symlinkSync, writeFileSync, copyFileSync, openSync } from "node:fs";
3
+ import { createHash, randomBytes } from "node:crypto";
4
+ import { createServer } from "node:net";
5
+ import { join, resolve } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { parseArgs } from "node:util";
8
+ export class PreviewError extends Error {
9
+ }
10
+ export function previewName(branch) {
11
+ const chars = [];
12
+ let dash = true;
13
+ for (let k = 0; k < branch.length; k++) {
14
+ const c = branch.charCodeAt(k);
15
+ const lower = c >= 65 && c <= 90 ? c + 32 : c;
16
+ const alnum = (lower >= 97 && lower <= 122) || (lower >= 48 && lower <= 57);
17
+ if (alnum) {
18
+ chars.push(String.fromCharCode(lower));
19
+ dash = false;
20
+ }
21
+ else if (!dash) {
22
+ chars.push("-");
23
+ dash = true;
24
+ }
25
+ }
26
+ if (chars.length && chars[chars.length - 1] === "-")
27
+ chars.pop();
28
+ let plain = chars.join("");
29
+ if (plain.length > 32) {
30
+ plain = plain.slice(0, 32);
31
+ while (plain.endsWith("-"))
32
+ plain = plain.slice(0, -1);
33
+ }
34
+ if (plain === branch && plain.length > 0)
35
+ return plain;
36
+ const tag = createHash("sha256").update(branch).digest("hex").slice(0, 6);
37
+ return plain ? `${plain}-${tag}` : `branch-${tag}`;
38
+ }
39
+ function git(cwd, args) {
40
+ const r = spawnSync("git", args, { cwd, encoding: "utf8", windowsHide: true });
41
+ if (r.error)
42
+ throw new PreviewError(`git: ${r.error.message}`);
43
+ if (r.status !== 0)
44
+ throw new PreviewError(`git ${args[0]}: ${(r.stderr || r.stdout).trim()}`);
45
+ return r.stdout.trim();
46
+ }
47
+ const dirOf = (root, name) => join(root, ".weft", "previews", name);
48
+ const stateFile = (dir) => join(dir, ".weft", "preview.json");
49
+ function readState(dir) {
50
+ try {
51
+ return JSON.parse(readFileSync(stateFile(dir), "utf8"));
52
+ }
53
+ catch {
54
+ return null;
55
+ }
56
+ }
57
+ function alive(pid) {
58
+ if (!Number.isInteger(pid) || pid <= 0)
59
+ return false;
60
+ try {
61
+ process.kill(pid, 0);
62
+ return true;
63
+ }
64
+ catch (err) {
65
+ return err.code === "EPERM";
66
+ }
67
+ }
68
+ async function stop(state) {
69
+ if (!state || !alive(state.pid))
70
+ return;
71
+ try {
72
+ process.kill(state.pid, "SIGTERM");
73
+ }
74
+ catch {
75
+ return;
76
+ }
77
+ for (let i = 0; i < 100 && alive(state.pid); i++)
78
+ await new Promise((r) => setTimeout(r, 100));
79
+ if (alive(state.pid))
80
+ process.kill(state.pid, "SIGKILL");
81
+ }
82
+ function portFree(port) {
83
+ return new Promise((done) => {
84
+ const s = createServer();
85
+ s.once("error", () => done(false));
86
+ s.listen(port, "127.0.0.1", () => s.close(() => done(true)));
87
+ });
88
+ }
89
+ async function pickPort(name, asked, had) {
90
+ if (asked !== undefined) {
91
+ if (!Number.isInteger(asked) || asked < 1024 || asked > 65535)
92
+ throw new PreviewError("--port is 1024 to 65535");
93
+ if (!(await portFree(asked)))
94
+ throw new PreviewError(`port ${asked} is in use`);
95
+ return asked;
96
+ }
97
+ if (had !== undefined && (await portFree(had)))
98
+ return had;
99
+ const start = 4100 + (parseInt(createHash("sha256").update(name).digest("hex").slice(0, 4), 16) % 800);
100
+ for (let i = 0; i < 900; i++) {
101
+ const p = 4100 + ((start - 4100 + i) % 900);
102
+ if (await portFree(p))
103
+ return p;
104
+ }
105
+ throw new PreviewError("no free port from 4100 to 4999");
106
+ }
107
+ function readDotenv(file) {
108
+ const out = {};
109
+ if (!existsSync(file))
110
+ return out;
111
+ for (const line of readFileSync(file, "utf8").split(/\r?\n/)) {
112
+ const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(line);
113
+ if (!m)
114
+ continue;
115
+ let v = m[2];
116
+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'")))
117
+ v = v.slice(1, -1);
118
+ out[m[1]] = v;
119
+ }
120
+ return out;
121
+ }
122
+ export async function previewUp(root, o) {
123
+ root = resolve(root);
124
+ const log = o.log ?? ((s) => console.log(`[weft] ${s}`));
125
+ if (typeof o.branch !== "string" || o.branch === "" || o.branch.startsWith("-"))
126
+ throw new PreviewError("--branch names a branch");
127
+ const top = git(root, ["rev-parse", "--show-toplevel"]);
128
+ if (realpathSync(top) !== realpathSync(root))
129
+ throw new PreviewError("run it from the project's top directory (the git repository root)");
130
+ const commit = git(root, ["rev-parse", "--verify", "--end-of-options", `${o.branch}^{commit}`]);
131
+ const name = previewName(o.branch);
132
+ const dir = dirOf(root, name);
133
+ const before = readState(dir);
134
+ await stop(before);
135
+ if (!existsSync(dir)) {
136
+ mkdirSync(join(root, ".weft", "previews"), { recursive: true });
137
+ log(`checking out ${o.branch} (${commit.slice(0, 8)}) into .weft/previews/${name}`);
138
+ git(root, ["worktree", "add", "--detach", "--", dir, commit]);
139
+ }
140
+ else {
141
+ log(`updating ${name} to ${commit.slice(0, 8)}`);
142
+ git(dir, ["checkout", "--detach", "--force", commit]);
143
+ }
144
+ const lock = (d) => (existsSync(join(d, "package-lock.json")) ? readFileSync(join(d, "package-lock.json"), "utf8") : null);
145
+ const nm = join(dir, "node_modules");
146
+ if (lock(dir) === lock(root)) {
147
+ if (!existsSync(nm) && existsSync(join(root, "node_modules")))
148
+ symlinkSync(join(root, "node_modules"), nm, "junction");
149
+ }
150
+ else if (existsSync(join(dir, "package.json"))) {
151
+ rmSync(nm, { recursive: true, force: true });
152
+ log("installing dependencies (npm ci)");
153
+ const r = spawnSync(process.platform === "win32" ? "npm.cmd" : "npm", [lock(dir) ? "ci" : "install", "--no-audit", "--no-fund"], {
154
+ cwd: dir,
155
+ stdio: "inherit",
156
+ shell: process.platform === "win32",
157
+ windowsHide: true,
158
+ });
159
+ if (r.status !== 0)
160
+ throw new PreviewError("installing dependencies failed");
161
+ }
162
+ mkdirSync(join(dir, ".weft"), { recursive: true });
163
+ const secretFile = join(dir, ".weft", "preview-secret");
164
+ if (!existsSync(secretFile)) {
165
+ writeFileSync(secretFile, randomBytes(36).toString("base64url"), { mode: 0o600 });
166
+ try {
167
+ chmodSync(secretFile, 0o600);
168
+ }
169
+ catch {
170
+ }
171
+ }
172
+ const secret = readFileSync(secretFile, "utf8").trim();
173
+ const port = await pickPort(name, o.port, before?.port);
174
+ const url = o.url ? o.url.replaceAll("{name}", name) : `http://127.0.0.1:${port}`;
175
+ try {
176
+ new URL(url);
177
+ }
178
+ catch {
179
+ throw new PreviewError("--url is a URL, with {name} for the preview's name");
180
+ }
181
+ if (existsSync(join(root, ".env.preview")))
182
+ copyFileSync(join(root, ".env.preview"), join(dir, ".env"));
183
+ const fromFile = readDotenv(join(dir, ".env"));
184
+ const { loadConfig } = await import("./load-config.js");
185
+ const config = await loadConfig(dir);
186
+ const env = {
187
+ ...process.env,
188
+ ...fromFile,
189
+ NODE_ENV: "production",
190
+ WEFT_PREVIEW: name,
191
+ APP_URL: url,
192
+ PORT: String(port),
193
+ HOST: "127.0.0.1",
194
+ WEFT_SECRET: secret,
195
+ };
196
+ if (config.secret)
197
+ env[config.secret.env] = secret;
198
+ const self = fileURLToPath(import.meta.url);
199
+ const step = (args) => {
200
+ const r = spawnSync(process.execPath, ["--experimental-strip-types", "--disable-warning=ExperimentalWarning", self, "--command=step", dir, ...args], {
201
+ stdio: "inherit",
202
+ env,
203
+ windowsHide: true,
204
+ });
205
+ if (r.status !== 0)
206
+ throw new PreviewError(`${args[0]} failed`);
207
+ };
208
+ log("building");
209
+ step(["build"]);
210
+ const fresh = !before;
211
+ if (existsSync(join(dir, "src", "seed.ts")) && (o.reset || fresh)) {
212
+ log(o.reset ? "resetting and seeding the preview database" : "seeding the preview database");
213
+ step(["seed"]);
214
+ }
215
+ else {
216
+ log("migrating the preview database");
217
+ step(["migrate"]);
218
+ }
219
+ const out = openSync(join(dir, ".weft", "preview.log"), "a");
220
+ const child = spawn(process.execPath, ["--experimental-strip-types", "--disable-warning=ExperimentalWarning", join(dir, "dist", "server.mjs")], {
221
+ cwd: dir,
222
+ env,
223
+ detached: true,
224
+ stdio: ["ignore", out, out],
225
+ windowsHide: true,
226
+ });
227
+ child.unref();
228
+ const state = { name, branch: o.branch, commit, port, url, pid: child.pid ?? 0, started: Date.now() };
229
+ writeFileSync(stateFile(dir), JSON.stringify(state, null, 2));
230
+ const until = Date.now() + (o.wait ?? 60) * 1000;
231
+ for (;;) {
232
+ try {
233
+ const res = await fetch(`http://127.0.0.1:${port}/_weft/health`, { signal: AbortSignal.timeout(2000) });
234
+ if (res.ok)
235
+ break;
236
+ }
237
+ catch {
238
+ }
239
+ if (!alive(state.pid))
240
+ throw new PreviewError(`the preview stopped while starting; see .weft/previews/${name}/.weft/preview.log`);
241
+ if (Date.now() > until)
242
+ throw new PreviewError(`the preview did not answer /_weft/health; see .weft/previews/${name}/.weft/preview.log`);
243
+ await new Promise((r) => setTimeout(r, 300));
244
+ }
245
+ log(`${name} is up at ${url} (port ${port})`);
246
+ return state;
247
+ }
248
+ export function previewList(root) {
249
+ const base = join(resolve(root), ".weft", "previews");
250
+ if (!existsSync(base))
251
+ return [];
252
+ return readdirSync(base)
253
+ .map((n) => readState(join(base, n)))
254
+ .filter((s) => s !== null)
255
+ .map((s) => ({ ...s, running: alive(s.pid) }));
256
+ }
257
+ export async function previewDown(root, branch) {
258
+ root = resolve(root);
259
+ const name = previewName(branch);
260
+ const dir = dirOf(root, name);
261
+ if (!existsSync(dir))
262
+ return false;
263
+ await stop(readState(dir));
264
+ const nm = join(dir, "node_modules");
265
+ try {
266
+ if (realpathSync(nm) === realpathSync(join(root, "node_modules")))
267
+ rmSync(nm, { force: true, recursive: false });
268
+ }
269
+ catch {
270
+ }
271
+ git(root, ["worktree", "remove", "--force", "--", dir]);
272
+ rmSync(dir, { recursive: true, force: true });
273
+ return true;
274
+ }
275
+ async function runStep(dir, what) {
276
+ const { findCompiler } = await import("./compiler.js");
277
+ const compiler = findCompiler(dir);
278
+ if (what === "build") {
279
+ const { build } = await import("./build.js");
280
+ await build(dir, { compiler });
281
+ }
282
+ else if (what === "migrate") {
283
+ const { migrateProject } = await import("./migrate.js");
284
+ await migrateProject(dir, { compiler });
285
+ }
286
+ else if (what === "seed") {
287
+ const { seedProject } = await import("./seed.js");
288
+ await seedProject(dir, { compiler, reset: true });
289
+ }
290
+ else
291
+ throw new PreviewError(`unknown step ${what}`);
292
+ }
293
+ async function main() {
294
+ const { values, positionals } = parseArgs({
295
+ allowPositionals: true,
296
+ options: {
297
+ command: { type: "string" },
298
+ branch: { type: "string" },
299
+ url: { type: "string" },
300
+ port: { type: "string" },
301
+ reset: { type: "boolean" },
302
+ },
303
+ });
304
+ const root = resolve(positionals[0] ?? ".");
305
+ try {
306
+ switch (values.command) {
307
+ case "step":
308
+ await runStep(root, positionals[1] ?? "");
309
+ break;
310
+ case "up":
311
+ await previewUp(root, {
312
+ branch: values.branch ?? "",
313
+ ...(values.url !== undefined ? { url: values.url } : {}),
314
+ ...(values.port !== undefined ? { port: Number(values.port) } : {}),
315
+ reset: values.reset === true,
316
+ });
317
+ break;
318
+ case "list": {
319
+ const all = previewList(root);
320
+ if (all.length === 0)
321
+ console.log("[weft] no previews");
322
+ for (const p of all)
323
+ console.log(`${p.running ? "up " : "down"} ${p.name} ${p.branch}@${p.commit.slice(0, 8)} ${p.url}`);
324
+ break;
325
+ }
326
+ case "down":
327
+ if (!values.branch)
328
+ throw new PreviewError("--branch names the preview's branch");
329
+ console.log((await previewDown(root, values.branch)) ? `[weft] removed ${previewName(values.branch)}` : "[weft] no such preview");
330
+ break;
331
+ default:
332
+ throw new PreviewError("expected up, list or down");
333
+ }
334
+ }
335
+ catch (err) {
336
+ if (err instanceof PreviewError)
337
+ console.error(`[weft] preview: ${err.message}`);
338
+ else
339
+ console.error("[weft] preview:", err instanceof Error ? (err.stack ?? err.message) : err);
340
+ process.exit(1);
341
+ }
342
+ }
343
+ function isEntry() {
344
+ try {
345
+ return !!process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
346
+ }
347
+ catch {
348
+ return false;
349
+ }
350
+ }
351
+ if (isEntry()) {
352
+ await main();
353
+ }
@@ -0,0 +1,16 @@
1
+ import { type App } from "./app.js";
2
+ import { type BuildManifest } from "./build.js";
3
+ export interface ProductionOptions {
4
+ env?: Record<string, string | undefined>;
5
+ listen?: boolean;
6
+ }
7
+ export interface ProductionServer {
8
+ app: App;
9
+ manifest: BuildManifest;
10
+ url?: string;
11
+ close(): Promise<void>;
12
+ }
13
+ export declare class ProductionError extends Error {
14
+ }
15
+ export declare function startProduction(distUrl: URL | string, opts?: ProductionOptions): Promise<ProductionServer>;
16
+ export declare function runProduction(distUrl: URL | string): Promise<void>;