@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
package/dist/meta.js ADDED
@@ -0,0 +1,146 @@
1
+ import { escapeAttr, escapeHtml } from "@weft-framework/runtime";
2
+ export function mergeMeta(...layers) {
3
+ const out = {};
4
+ for (const m of layers) {
5
+ if (!m) {
6
+ continue;
7
+ }
8
+ for (const key of Object.keys(m)) {
9
+ const v = m[key];
10
+ if (v === undefined) {
11
+ continue;
12
+ }
13
+ if (key === "openGraph" || key === "twitter") {
14
+ out[key] = { ...out[key], ...v };
15
+ }
16
+ else if (key === "tags" || key === "links") {
17
+ out[key] = [...(out[key] ?? []), ...v];
18
+ }
19
+ else {
20
+ out[key] = v;
21
+ }
22
+ }
23
+ }
24
+ return out;
25
+ }
26
+ export function applySite(meta, siteUrl) {
27
+ if (!siteUrl) {
28
+ return meta;
29
+ }
30
+ const abs = (value) => value !== undefined && value.startsWith("/") && !value.startsWith("//") && !value.startsWith("/\\")
31
+ ? siteUrl + value
32
+ : value;
33
+ return {
34
+ ...meta,
35
+ canonical: abs(meta.canonical),
36
+ openGraph: meta.openGraph
37
+ ? { ...meta.openGraph, url: abs(meta.openGraph.url), image: abs(meta.openGraph.image) }
38
+ : undefined,
39
+ twitter: meta.twitter ? { ...meta.twitter, image: abs(meta.twitter.image) } : undefined,
40
+ };
41
+ }
42
+ export function resolveTitle(meta) {
43
+ const title = meta.title ?? "";
44
+ const tpl = meta.titleTemplate;
45
+ if (!tpl || !tpl.includes("%s")) {
46
+ return title;
47
+ }
48
+ if (title === "") {
49
+ const i = tpl.indexOf("%s");
50
+ const marks = (ch) => ch === " " || ch === "|" || ch === "-" || ch === ":" || ch === "\u2013" || ch === "\u2014" || ch === "\u00b7";
51
+ let left = tpl.slice(0, i);
52
+ let right = tpl.slice(i + 2);
53
+ while (left.length && marks(left[left.length - 1]))
54
+ left = left.slice(0, -1);
55
+ while (right.length && marks(right[0]))
56
+ right = right.slice(1);
57
+ return `${left} ${right}`.trim();
58
+ }
59
+ return tpl.replace("%s", () => title);
60
+ }
61
+ export function resolveLang(meta) {
62
+ const lang = meta.lang ?? "en";
63
+ return /^[A-Za-z]{2,8}(-[A-Za-z0-9]{1,8})*$/.test(lang) ? lang : "en";
64
+ }
65
+ function metaTag(attr, key, content) {
66
+ return `<meta ${attr}="${escapeAttr(key)}" content="${escapeAttr(content)}">`;
67
+ }
68
+ export function scriptJson(value) {
69
+ return JSON.stringify(value).replace(/[<>&\u2028\u2029]/g, (c) => {
70
+ return `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`;
71
+ });
72
+ }
73
+ export function renderMeta(meta, opts = {}) {
74
+ const parts = [`<title>${escapeHtml(resolveTitle(meta))}</title>`];
75
+ if (meta.description !== undefined) {
76
+ parts.push(metaTag("name", "description", meta.description));
77
+ }
78
+ if (meta.robots !== undefined) {
79
+ parts.push(metaTag("name", "robots", meta.robots));
80
+ }
81
+ if (meta.themeColor !== undefined) {
82
+ parts.push(metaTag("name", "theme-color", meta.themeColor));
83
+ }
84
+ if (meta.canonical !== undefined) {
85
+ parts.push(`<link rel="canonical" href="${escapeAttr(meta.canonical)}">`);
86
+ }
87
+ const og = meta.openGraph;
88
+ if (og) {
89
+ const fields = [
90
+ ["og:title", og.title],
91
+ ["og:description", og.description],
92
+ ["og:type", og.type],
93
+ ["og:url", og.url],
94
+ ["og:image", og.image],
95
+ ["og:image:alt", og.imageAlt],
96
+ ["og:site_name", og.siteName],
97
+ ["og:locale", og.locale],
98
+ ];
99
+ for (const [key, value] of fields) {
100
+ if (value !== undefined) {
101
+ parts.push(metaTag("property", key, value));
102
+ }
103
+ }
104
+ }
105
+ const tw = meta.twitter;
106
+ if (tw) {
107
+ const fields = [
108
+ ["twitter:card", tw.card],
109
+ ["twitter:site", tw.site],
110
+ ["twitter:creator", tw.creator],
111
+ ["twitter:title", tw.title],
112
+ ["twitter:description", tw.description],
113
+ ["twitter:image", tw.image],
114
+ ];
115
+ for (const [key, value] of fields) {
116
+ if (value !== undefined) {
117
+ parts.push(metaTag("name", key, value));
118
+ }
119
+ }
120
+ }
121
+ for (const t of meta.tags ?? []) {
122
+ if (t.name !== undefined) {
123
+ parts.push(metaTag("name", t.name, t.content));
124
+ }
125
+ else if (t.property !== undefined) {
126
+ parts.push(metaTag("property", t.property, t.content));
127
+ }
128
+ else if (t.httpEquiv !== undefined) {
129
+ parts.push(metaTag("http-equiv", t.httpEquiv, t.content));
130
+ }
131
+ }
132
+ for (const l of meta.links ?? []) {
133
+ let tag = `<link rel="${escapeAttr(l.rel)}" href="${escapeAttr(l.href)}"`;
134
+ for (const k of ["type", "sizes", "hreflang", "media"]) {
135
+ if (l[k] !== undefined) {
136
+ tag += ` ${k}="${escapeAttr(l[k])}"`;
137
+ }
138
+ }
139
+ parts.push(tag + ">");
140
+ }
141
+ if (meta.jsonLd !== undefined) {
142
+ const nonce = opts.nonce ? ` nonce="${escapeAttr(opts.nonce)}"` : "";
143
+ parts.push(`<script type="application/ld+json"${nonce}>${scriptJson(meta.jsonLd)}</script>`);
144
+ }
145
+ return parts.join("");
146
+ }
@@ -0,0 +1,20 @@
1
+ export interface MiddlewareContext {
2
+ request: Request;
3
+ url: URL;
4
+ session: string | null;
5
+ user: unknown;
6
+ }
7
+ export type MiddlewareResult = void | null | Response | {
8
+ headers?: Record<string, string> | Headers;
9
+ rewrite?: string;
10
+ };
11
+ export declare function safeRewrite(path: unknown): string | null;
12
+ export type Middleware = (ctx: MiddlewareContext) => MiddlewareResult | Promise<MiddlewareResult>;
13
+ export declare function safeHeaders(input: Record<string, string> | Headers | undefined): [string, string][];
14
+ export declare function runMiddleware(mw: Middleware | readonly Middleware[] | undefined, ctx: MiddlewareContext): Promise<{
15
+ response?: Response;
16
+ headers: [string, string][];
17
+ rewrite?: string;
18
+ }>;
19
+ export declare function withExtraHeaders(res: Response, extra: readonly (readonly [string, string])[]): Response;
20
+ export declare function copyHeaders(src: Headers): Headers;
@@ -0,0 +1,101 @@
1
+ export function safeRewrite(path) {
2
+ if (typeof path !== "string" || path.length > 2048 || !/^\/[A-Za-z0-9\-._~!$&'()*+,;=:@%/]*$/.test(path)) {
3
+ return null;
4
+ }
5
+ if (path.includes("//") || /(^|\/)\.\.?(\/|$)/.test(path) || path === "/_weft" || path.startsWith("/_weft/")) {
6
+ return null;
7
+ }
8
+ return path;
9
+ }
10
+ const BLOCKED = new Set([
11
+ "content-security-policy",
12
+ "content-security-policy-report-only",
13
+ "strict-transport-security",
14
+ "x-frame-options",
15
+ "x-content-type-options",
16
+ "cross-origin-opener-policy",
17
+ "cross-origin-embedder-policy",
18
+ "cross-origin-resource-policy",
19
+ "set-cookie",
20
+ "set-cookie2",
21
+ "cookie",
22
+ "host",
23
+ "connection",
24
+ "keep-alive",
25
+ "transfer-encoding",
26
+ "content-length",
27
+ "location",
28
+ "trailer",
29
+ "upgrade",
30
+ "te",
31
+ ]);
32
+ const NAME = /^[!#$%&'*+\-.^_`|~0-9a-z]+$/;
33
+ export function safeHeaders(input) {
34
+ if (!input) {
35
+ return [];
36
+ }
37
+ const entries = input instanceof Headers ? [...input.entries()] : Object.entries(input);
38
+ const out = [];
39
+ for (const [rawName, rawValue] of entries) {
40
+ if (out.length >= 32) {
41
+ break;
42
+ }
43
+ if (typeof rawValue !== "string") {
44
+ continue;
45
+ }
46
+ const name = rawName.toLowerCase();
47
+ if (!NAME.test(name) || BLOCKED.has(name) || rawValue.length > 512 || /[\r\n\0]/.test(rawValue)) {
48
+ continue;
49
+ }
50
+ out.push([name, rawValue]);
51
+ }
52
+ return out;
53
+ }
54
+ export async function runMiddleware(mw, ctx) {
55
+ if (!mw) {
56
+ return { headers: [] };
57
+ }
58
+ const list = Array.isArray(mw) ? mw : [mw];
59
+ const headers = [];
60
+ let rewrite;
61
+ for (const fn of list) {
62
+ if (typeof fn !== "function") {
63
+ throw new Error("@weft-framework/server: middleware must be a function");
64
+ }
65
+ const result = await fn(ctx);
66
+ if (result instanceof Response) {
67
+ return { response: result, headers };
68
+ }
69
+ if (result && typeof result === "object") {
70
+ if ("headers" in result)
71
+ headers.push(...safeHeaders(result.headers));
72
+ if ("rewrite" in result)
73
+ rewrite = safeRewrite(result.rewrite) ?? rewrite;
74
+ }
75
+ }
76
+ return rewrite === undefined ? { headers: headers.slice(0, 32) } : { headers: headers.slice(0, 32), rewrite };
77
+ }
78
+ export function withExtraHeaders(res, extra) {
79
+ if (extra.length === 0) {
80
+ return res;
81
+ }
82
+ const headers = copyHeaders(res.headers);
83
+ for (const [name, value] of extra) {
84
+ if (!headers.has(name)) {
85
+ headers.append(name, value);
86
+ }
87
+ }
88
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
89
+ }
90
+ export function copyHeaders(src) {
91
+ const headers = new Headers();
92
+ src.forEach((value, name) => {
93
+ if (name.toLowerCase() !== "set-cookie") {
94
+ headers.set(name, value);
95
+ }
96
+ });
97
+ for (const cookie of src.getSetCookie?.() ?? []) {
98
+ headers.append("set-cookie", cookie);
99
+ }
100
+ return headers;
101
+ }
@@ -0,0 +1,12 @@
1
+ import { type MigrationPlan } from "@weft-framework/data";
2
+ import { type Compiler } from "./compiler.js";
3
+ export interface MigrateCommandOptions {
4
+ compiler: Compiler;
5
+ dryRun?: boolean;
6
+ destructive?: boolean;
7
+ }
8
+ export declare class MigrateError extends Error {
9
+ }
10
+ export declare function migrateProject(root: string, opts: MigrateCommandOptions): Promise<MigrationPlan & {
11
+ database: string;
12
+ }>;
@@ -0,0 +1,88 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdirSync, realpathSync, rmSync } from "node:fs";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { parseArgs } from "node:util";
6
+ import { migrate, planMigrations } from "@weft-framework/data";
7
+ import { CompileError, findCompiler } from "./compiler.js";
8
+ import { ConfigError } from "./config.js";
9
+ import { ProjectError, loadProject } from "./project.js";
10
+ export class MigrateError extends Error {
11
+ }
12
+ export async function migrateProject(root, opts) {
13
+ root = resolve(root);
14
+ const outDir = join(root, ".weft", "migrate", randomUUID());
15
+ try {
16
+ const project = await loadProject(root, { compiler: opts.compiler, outDir, browserAssets: false, cacheKey: outDir });
17
+ if (project.database === undefined) {
18
+ throw new MigrateError("no `database` in weft.config.ts; models are kept in memory");
19
+ }
20
+ const models = Object.values(project.models);
21
+ const { openSqlite } = await import("@weft-framework/data/sqlite");
22
+ if (project.database !== ":memory:") {
23
+ mkdirSync(dirname(project.database), { recursive: true });
24
+ }
25
+ const db = openSqlite(project.database);
26
+ try {
27
+ const plan = opts.dryRun
28
+ ? planMigrations(db, models, { destructive: opts.destructive })
29
+ : migrate(db, models, { destructive: opts.destructive });
30
+ return { ...plan, database: project.database };
31
+ }
32
+ finally {
33
+ db.close();
34
+ }
35
+ }
36
+ finally {
37
+ rmSync(outDir, { recursive: true, force: true });
38
+ }
39
+ }
40
+ async function main() {
41
+ const { values, positionals } = parseArgs({
42
+ allowPositionals: true,
43
+ options: { "dry-run": { type: "boolean" }, "allow-destructive": { type: "boolean" } },
44
+ });
45
+ const root = resolve(positionals[0] ?? ".");
46
+ const dryRun = values["dry-run"] === true;
47
+ try {
48
+ const plan = await migrateProject(root, {
49
+ compiler: findCompiler(root),
50
+ dryRun,
51
+ destructive: values["allow-destructive"] === true,
52
+ });
53
+ console.log(`[weft] ${plan.database}`);
54
+ if (plan.steps.length === 0) {
55
+ console.log(" up to date");
56
+ }
57
+ else {
58
+ console.log(dryRun ? " would run:" : " applied:");
59
+ for (const s of plan.steps)
60
+ console.log(` ${s.sql};`);
61
+ }
62
+ for (const w of plan.warnings)
63
+ console.warn(` warning: ${w}`);
64
+ }
65
+ catch (err) {
66
+ if (err instanceof CompileError) {
67
+ console.error(err.diagnostics);
68
+ }
69
+ else if (err instanceof MigrateError || err instanceof ProjectError || err instanceof ConfigError) {
70
+ console.error(`[weft] ${err.message}`);
71
+ }
72
+ else {
73
+ console.error("[weft] migrate:", err instanceof Error ? err.message : err);
74
+ }
75
+ process.exit(1);
76
+ }
77
+ }
78
+ function isEntry() {
79
+ try {
80
+ return !!process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
81
+ }
82
+ catch {
83
+ return false;
84
+ }
85
+ }
86
+ if (isEntry()) {
87
+ await main();
88
+ }
package/dist/node.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ import type { App } from "./app.js";
2
+ export interface NodeServeOptions {
3
+ port?: number;
4
+ host?: string;
5
+ trustProxy?: boolean;
6
+ onError?(err: unknown): void;
7
+ }
8
+ export interface NodeServer {
9
+ url: string;
10
+ close(): Promise<void>;
11
+ }
12
+ export declare function serveNode(app: App, opts?: NodeServeOptions): Promise<NodeServer>;
13
+ export { runtimeAssets, rewriteImports } from "./assets.js";
14
+ export { assetManifest, publicFiles } from "./files.js";
15
+ export type { FileHandler, PublicFilesOptions } from "./files.js";
16
+ export { parseConfig, resolveSecret, ConfigError, isSiteUrl } from "./config.js";
17
+ export { loadConfig } from "./load-config.js";
18
+ export { loadProject, ProjectError } from "./project.js";
19
+ export type { ProjectApp, ProjectOptions } from "./project.js";
20
+ export { projectStyles, StyleError } from "./tailwind.js";
21
+ export type { ProjectStyles, StyleOptions } from "./tailwind.js";
22
+ export { CompileError, compileFile, compileTree, findCompiler } from "./compiler.js";
23
+ export type { Compiler } from "./compiler.js";
24
+ export { ModelStorage } from "./storage.js";
25
+ export type { StorageOptions } from "./storage.js";
26
+ export { loadEnvFile } from "./env.js";
package/dist/node.js ADDED
@@ -0,0 +1,96 @@
1
+ import { createServer } from "node:http";
2
+ import { Readable } from "node:stream";
3
+ function toRequest(req, opts, signal) {
4
+ const fwd = (name) => {
5
+ const v = req.headers[name];
6
+ return opts.trustProxy && typeof v === "string" ? v.split(",")[0].trim() : undefined;
7
+ };
8
+ const proto = fwd("x-forwarded-proto") ?? "http";
9
+ const host = fwd("x-forwarded-host") ?? req.headers.host ?? "localhost";
10
+ const headers = new Headers();
11
+ for (let i = 0; i < req.rawHeaders.length; i += 2) {
12
+ headers.append(req.rawHeaders[i], req.rawHeaders[i + 1]);
13
+ }
14
+ const method = req.method ?? "GET";
15
+ const hasBody = method !== "GET" && method !== "HEAD";
16
+ return new Request(`${proto}://${host}${req.url ?? "/"}`, {
17
+ method,
18
+ headers,
19
+ signal,
20
+ body: hasBody ? Readable.toWeb(req) : undefined,
21
+ duplex: hasBody ? "half" : undefined,
22
+ });
23
+ }
24
+ async function send(res, response) {
25
+ const headers = {};
26
+ response.headers.forEach((value, name) => {
27
+ if (name !== "set-cookie") {
28
+ headers[name] = value;
29
+ }
30
+ });
31
+ const cookies = response.headers.getSetCookie();
32
+ if (cookies.length > 0) {
33
+ headers["set-cookie"] = cookies;
34
+ }
35
+ res.writeHead(response.status, headers);
36
+ if (!response.body) {
37
+ res.end();
38
+ return;
39
+ }
40
+ const reader = response.body.getReader();
41
+ res.on("close", () => {
42
+ reader.cancel().catch(() => undefined);
43
+ });
44
+ try {
45
+ for (;;) {
46
+ const { done, value } = await reader.read();
47
+ if (done) {
48
+ break;
49
+ }
50
+ res.write(value);
51
+ }
52
+ }
53
+ finally {
54
+ res.end();
55
+ }
56
+ }
57
+ export function serveNode(app, opts = {}) {
58
+ const onError = opts.onError ?? ((err) => console.error("[weft]", err));
59
+ const server = createServer((req, res) => {
60
+ const abort = new AbortController();
61
+ res.on("close", () => abort.abort());
62
+ (async () => {
63
+ const response = (await app.fetch(toRequest(req, opts, abort.signal))) ?? new Response(null, { status: 426 });
64
+ await send(res, response);
65
+ })().catch((err) => {
66
+ onError(err);
67
+ if (!res.headersSent) {
68
+ res.writeHead(500);
69
+ }
70
+ res.end();
71
+ });
72
+ });
73
+ return new Promise((resolve, reject) => {
74
+ server.once("error", reject);
75
+ server.listen(opts.port ?? 3000, opts.host ?? "127.0.0.1", () => {
76
+ const addr = server.address();
77
+ const port = typeof addr === "object" && addr ? addr.port : opts.port;
78
+ resolve({
79
+ url: `http://${opts.host ?? "127.0.0.1"}:${port}`,
80
+ close: () => new Promise((done) => {
81
+ server.closeAllConnections();
82
+ server.close(() => done());
83
+ }),
84
+ });
85
+ });
86
+ });
87
+ }
88
+ export { runtimeAssets, rewriteImports } from "./assets.js";
89
+ export { assetManifest, publicFiles } from "./files.js";
90
+ export { parseConfig, resolveSecret, ConfigError, isSiteUrl } from "./config.js";
91
+ export { loadConfig } from "./load-config.js";
92
+ export { loadProject, ProjectError } from "./project.js";
93
+ export { projectStyles, StyleError } from "./tailwind.js";
94
+ export { CompileError, compileFile, compileTree, findCompiler } from "./compiler.js";
95
+ export { ModelStorage } from "./storage.js";
96
+ export { loadEnvFile } from "./env.js";
@@ -0,0 +1,21 @@
1
+ import type { Model } from "@weft-framework/data";
2
+ export interface Notice {
3
+ text: string;
4
+ kind?: string;
5
+ data?: unknown;
6
+ }
7
+ export interface NotifyOptions {
8
+ self?: boolean;
9
+ }
10
+ export declare class NoticeError extends Error {
11
+ }
12
+ export interface SentNotice {
13
+ text: string;
14
+ kind: string;
15
+ data?: unknown;
16
+ }
17
+ type Hub = (model: Model<unknown>, row: unknown, notice: SentNotice, self: boolean) => number;
18
+ export declare function addNoticeHub(hub: Hub): () => void;
19
+ export declare function checkNotice(n: Notice): SentNotice;
20
+ export declare function notifyReaders<T>(model: Model<T>, row: T, notice: Notice, opts?: NotifyOptions): number;
21
+ export {};
package/dist/notice.js ADDED
@@ -0,0 +1,48 @@
1
+ import { NOTICE_KIND } from "@weft-framework/runtime";
2
+ export class NoticeError extends Error {
3
+ }
4
+ const hubs = new Set();
5
+ export function addNoticeHub(hub) {
6
+ hubs.add(hub);
7
+ return () => void hubs.delete(hub);
8
+ }
9
+ const MAX_DATA = 4096;
10
+ export function checkNotice(n) {
11
+ if (typeof n !== "object" || n === null)
12
+ throw new NoticeError("a notice is an object with `text`");
13
+ const { text, kind = "info", data } = n;
14
+ if (typeof text !== "string" || text.trim() === "")
15
+ throw new NoticeError("a notice needs non-empty `text`");
16
+ if (text.length > 500)
17
+ throw new NoticeError("a notice's text is at most 500 characters");
18
+ if (/[\u0000-\u001f\u007f\u2028\u2029]/.test(text))
19
+ throw new NoticeError("a notice's text is one line of plain text");
20
+ if (typeof kind !== "string" || !NOTICE_KIND.test(kind)) {
21
+ throw new NoticeError("a notice's kind is lowercase letters, digits and _.- (at most 32 characters)");
22
+ }
23
+ if (data === undefined)
24
+ return { text, kind };
25
+ let json;
26
+ try {
27
+ json = JSON.stringify(data);
28
+ }
29
+ catch {
30
+ throw new NoticeError("a notice's data must be JSON");
31
+ }
32
+ if (json === undefined)
33
+ throw new NoticeError("a notice's data must be JSON");
34
+ if (new TextEncoder().encode(json).length > MAX_DATA)
35
+ throw new NoticeError(`a notice's data is at most ${MAX_DATA} bytes of JSON`);
36
+ return { text, kind, data: JSON.parse(json) };
37
+ }
38
+ export function notifyReaders(model, row, notice, opts = {}) {
39
+ if (typeof model?.name !== "string")
40
+ throw new NoticeError("notifyReaders needs a model");
41
+ if (typeof row !== "object" || row === null)
42
+ throw new NoticeError("notifyReaders needs the row");
43
+ const sent = checkNotice(notice);
44
+ let n = 0;
45
+ for (const hub of hubs)
46
+ n += hub(model, row, sent, opts.self === true);
47
+ return n;
48
+ }
package/dist/npm.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ export declare const NPM_PREFIX = "/_weft/npm/";
2
+ export declare const LOCAL_PREFIX = "/_weft/local/";
3
+ export declare class NpmError extends Error {
4
+ }
5
+ export interface BrowserModulesOptions {
6
+ root: string;
7
+ mode?: "development" | "production";
8
+ onWarn?: (message: string) => void;
9
+ }
10
+ export declare function browserModules(modules: Record<string, {
11
+ js: string;
12
+ dir: string;
13
+ }>, opts: BrowserModulesOptions): {
14
+ modules: Record<string, string>;
15
+ assets: Record<string, string>;
16
+ };