@pwfabric/cli 1.0.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/dist/commands/dev.js +4 -3
- package/dist/commands/dev.js.map +1 -1
- package/dist/commands/lib/report.d.ts +26 -1
- package/dist/commands/lib/report.js +136 -3
- package/dist/commands/lib/report.js.map +1 -1
- package/dist/dev/csp.js +1 -1
- package/dist/dev/csp.js.map +1 -1
- package/dist/dev/envelope.d.ts +4 -1
- package/dist/dev/envelope.js +6 -1
- package/dist/dev/envelope.js.map +1 -1
- package/dist/dev/server.d.ts +1 -1
- package/dist/dev/server.js +24 -10
- package/dist/dev/server.js.map +1 -1
- package/dist/dev/types.d.ts +1 -1
- package/dist/dev/types.js.map +1 -1
- package/dist/host/definitions.d.ts +10 -10
- package/dist/host/definitions.js +26 -11
- package/dist/host/definitions.js.map +1 -1
- package/dist/host/index.d.ts +33 -0
- package/dist/host/index.js +30 -0
- package/dist/host/index.js.map +1 -0
- package/dist/host/local-host.d.ts +5 -2
- package/dist/host/local-host.js +23 -9
- package/dist/host/local-host.js.map +1 -1
- package/dist/host/records.d.ts +53 -22
- package/dist/host/records.js +118 -65
- package/dist/host/records.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +13 -8
package/dist/dev/server.js
CHANGED
|
@@ -91,25 +91,35 @@ export async function createDevServer(options, internals = {}) {
|
|
|
91
91
|
const hostname = options.hostname ?? DEFAULT_HOSTNAME;
|
|
92
92
|
const cache = createCompileCache(internals.assemble?.cacheDir === undefined ? join(root, PWF_DIR, 'build-cache') : internals.assemble.cacheDir);
|
|
93
93
|
// ── the local host ───────────────────────────────────────────────
|
|
94
|
-
let
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
94
|
+
let origin = '';
|
|
95
|
+
let host = isLocalHost(options.localHost) ? options.localHost : null;
|
|
96
|
+
let hostNoted = false;
|
|
97
|
+
/**
|
|
98
|
+
* Mounts the host the first time the app needs one. Asked again on every
|
|
99
|
+
* build, not only at start: an app that starts as a bare page and gains its
|
|
100
|
+
* first entity or sign-in while the server runs needs the host from that
|
|
101
|
+
* build on, or its pages bind no data and its forms send nothing.
|
|
102
|
+
*/
|
|
103
|
+
const ensureHost = async () => {
|
|
104
|
+
if (host || options.localHost === false)
|
|
105
|
+
return;
|
|
99
106
|
const needs = await hostNeeds(root);
|
|
100
107
|
const wanted = options.localHost === true || needs.length > 0;
|
|
101
108
|
if (wanted && internals.createHost) {
|
|
102
109
|
host = internals.createHost({ root, prefix: HOST_PREFIX });
|
|
110
|
+
if (origin)
|
|
111
|
+
log(`local host mounted at ${origin}${HOST_PREFIX} — development only: records in memory, no password checked`);
|
|
103
112
|
}
|
|
104
|
-
else if (wanted) {
|
|
113
|
+
else if (wanted && !hostNoted) {
|
|
114
|
+
hostNoted = true;
|
|
105
115
|
log(`note: this app declares ${needs.join(' and ') || 'a host'}, but no local host is mounted — pages render, ${needs.includes('sign-in') ? 'sign-in cannot complete and ' : ''}data stays empty`);
|
|
106
116
|
}
|
|
107
|
-
}
|
|
117
|
+
};
|
|
118
|
+
await ensureHost();
|
|
108
119
|
// ── state ────────────────────────────────────────────────────────
|
|
109
120
|
let state = null;
|
|
110
121
|
const packMemo = new Map();
|
|
111
122
|
const clients = new Set();
|
|
112
|
-
let origin = '';
|
|
113
123
|
const broadcast = (event, data) => {
|
|
114
124
|
const frame = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
|
|
115
125
|
for (const c of clients)
|
|
@@ -117,13 +127,17 @@ export async function createDevServer(options, internals = {}) {
|
|
|
117
127
|
};
|
|
118
128
|
const build = async () => {
|
|
119
129
|
let result;
|
|
130
|
+
await ensureHost();
|
|
120
131
|
try {
|
|
121
132
|
result = await assemblePwapp(root, {
|
|
122
133
|
...internals.assemble,
|
|
123
134
|
cache,
|
|
124
135
|
packMemo,
|
|
125
136
|
shellExtra: RELOAD_CLIENT,
|
|
126
|
-
|
|
137
|
+
// Host addresses go out relative ('/_host/…'), so a page reaches its host at whatever
|
|
138
|
+
// address it was opened on — localhost, 127.0.0.1, a LAN name, a preview proxy. An
|
|
139
|
+
// origin fixed at start-up made every other address a cross-origin write the browser blocks.
|
|
140
|
+
...(host ? { envelopeEntries: host.envelopeEntries('') } : {}),
|
|
127
141
|
});
|
|
128
142
|
}
|
|
129
143
|
catch (e) {
|
|
@@ -230,7 +244,7 @@ export async function createDevServer(options, internals = {}) {
|
|
|
230
244
|
const url = urlFor(hostname, port);
|
|
231
245
|
origin = url.replace(/\/$/, '');
|
|
232
246
|
if (host) {
|
|
233
|
-
log(`local host mounted at ${origin}${HOST_PREFIX} — development only: records in memory,
|
|
247
|
+
log(`local host mounted at ${origin}${HOST_PREFIX} — development only: records in memory, no password checked`);
|
|
234
248
|
}
|
|
235
249
|
await rebuild();
|
|
236
250
|
let watcher = null;
|
package/dist/dev/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/dev/server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,YAAY,EAA6C,MAAM,WAAW,CAAA;AAEnF,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AAElD,OAAO,EAAE,aAAa,EAA6C,MAAM,eAAe,CAAA;AACxF,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAA;AACjD,OAAO,EAAE,gBAAgB,EAA2B,MAAM,kBAAkB,CAAA;AAC5E,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAA;AAC3C,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,aAAa,EAAE,SAAS,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;AAC3G,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;A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AAA;QACf,CAAC;KACF,CAAA;AACH,CAAC;AAED,0DAA0D;AAC1D,MAAM,CAAC,MAAM,cAAc,GAAmB,CAAC,OAAO,EAAE,EAAE,CAAC,eAAe,CAAC,OAAO,CAAC,CAAA","sourcesContent":["/**\n * `pwf dev`: serves an app folder as a pwapp and keeps it current.\n *\n * One `node:http` server on 127.0.0.1 (port 4600 by default). It assembles\n * the app into memory (see ./assemble.ts), serves the files from there,\n * watches the folder, reassembles on change and tells the open page to reload\n * through Server-Sent Events. While the last build has errors the page is an\n * overlay listing them; the terminal gets the same list.\n *\n * When the app declares sign-in or records it needs a local host. A host\n * passed in `localHost` is mounted on the same server: requests it claims go\n * to `host.handle()`, and the envelope carries `host.envelopeEntries()`.\n * This module never constructs a host itself (it depends on the host's\n * interface only); a caller that can make one passes `createHost`.\n */\nimport { createServer, type IncomingMessage, type ServerResponse } from 'node:http'\nimport type { AddressInfo } from 'node:net'\nimport { extname, join, resolve } from 'node:path'\nimport type { CreateLocalHost, LocalHost } from '../host/types.js'\nimport { assemblePwapp, type AssembleOptions, type AssembleResult } from './assemble.js'\nimport { createCompileCache } from './compile.js'\nimport { formatDiagnostic, type AssembleDiagnostic } from './diagnostics.js'\nimport { hostNeeds } from './needs-host.js'\nimport { EVENTS_PATH, overlayHtml, RELOAD_CLIENT, RELOAD_JS, RELOAD_PATH, STATUS_PATH } from './overlay.js'\nimport { withBaseHref } from './shell.js'\nimport { PWF_DIR, type PackMemo } from './sources.js'\nimport type { DevBuildResult, DevServer, DevServerOptions, StartDevServer } from './types.js'\nimport { watchFolder, type WatchOptions, type Watcher } from './watcher.js'\n\nexport const DEFAULT_PORT = 4600\nexport const DEFAULT_HOSTNAME = '127.0.0.1'\n/** Where a host this server creates is mounted. */\nexport const HOST_PREFIX = '/_host'\n\n/** Seams for the `dev` command and for tests; not part of the public contract. */\nexport interface DevServerInternals {\n /** Watching; `false` turns it off. */\n readonly watch?: WatchOptions | false\n /** Makes a host when the app needs one and none was passed. */\n readonly createHost?: CreateLocalHost\n /** Assembly options (runtime bundles, cache folder). */\n readonly assemble?: Pick<AssembleOptions, 'runtime' | 'cacheDir' | 'publishedAt'>\n}\n\nconst CONTENT_TYPES: Readonly<Record<string, string>> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.map': 'application/json; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n '.avif': 'image/avif',\n '.ico': 'image/x-icon',\n '.woff2': 'font/woff2',\n '.txt': 'text/plain; charset=utf-8',\n}\n\nexport function contentTypeOf(path: string): string {\n return CONTENT_TYPES[extname(path).toLowerCase()] ?? 'application/octet-stream'\n}\n\nfunction isLocalHost(value: unknown): value is LocalHost {\n return (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as LocalHost).handle === 'function' &&\n typeof (value as LocalHost).envelopeEntries === 'function'\n )\n}\n\n/** The address a browser should open for a bound interface. */\nexport function urlFor(hostname: string, port: number): string {\n const h = hostname === '0.0.0.0' || hostname === '::' || hostname === '' ? 'localhost' : hostname\n return `http://${h.includes(':') ? `[${h}]` : h}:${port}/`\n}\n\nfunction send(res: ServerResponse, status: number, type: string, body: string | Uint8Array, head = false): void {\n res.writeHead(status, {\n 'content-type': type,\n 'cache-control': 'no-store',\n 'content-length': typeof body === 'string' ? Buffer.byteLength(body) : body.byteLength,\n })\n res.end(head ? undefined : body)\n}\n\n/** Lines for the terminal: everything that is the app's own, and a count of what pinned packs say. */\nexport function logLines(diagnostics: readonly AssembleDiagnostic[]): string[] {\n const own: string[] = []\n let packWarnings = 0\n for (const d of diagnostics) {\n if (d.severity !== 'error' && d.path?.startsWith(`${PWF_DIR}/`)) {\n packWarnings++\n continue\n }\n if (d.severity === 'info') continue\n own.push(formatDiagnostic(d))\n }\n if (packWarnings > 0) own.push(`${packWarnings} finding${packWarnings === 1 ? '' : 's'} in pinned packs (\\`pwf build\\` lists them)`)\n return own\n}\n\n/** Starts the dev server with the internal seams. {@link startDevServer} is the public entry. */\nexport async function createDevServer(options: DevServerOptions, internals: DevServerInternals = {}): Promise<DevServer> {\n const root = resolve(options.root)\n const log = options.log ?? ((): void => undefined)\n const hostname = options.hostname ?? DEFAULT_HOSTNAME\n const cache = createCompileCache(\n internals.assemble?.cacheDir === undefined ? join(root, PWF_DIR, 'build-cache') : internals.assemble.cacheDir\n )\n\n // ── the local host ───────────────────────────────────────────────\n let host: LocalHost | null = null\n if (isLocalHost(options.localHost)) {\n host = options.localHost\n } else if (options.localHost !== false) {\n const needs = await hostNeeds(root)\n const wanted = options.localHost === true || needs.length > 0\n if (wanted && internals.createHost) {\n host = internals.createHost({ root, prefix: HOST_PREFIX })\n } else if (wanted) {\n log(\n `note: this app declares ${needs.join(' and ') || 'a host'}, but no local host is mounted — pages render, ${\n needs.includes('sign-in') ? 'sign-in cannot complete and ' : ''\n }data stays empty`\n )\n }\n }\n\n // ── state ────────────────────────────────────────────────────────\n let state: AssembleResult | null = null\n const packMemo: PackMemo = new Map()\n const clients = new Set<ServerResponse>()\n let origin = ''\n\n const broadcast = (event: string, data: unknown): void => {\n const frame = `event: ${event}\\ndata: ${JSON.stringify(data)}\\n\\n`\n for (const c of clients) c.write(frame)\n }\n\n const build = async (): Promise<DevBuildResult> => {\n let result: AssembleResult\n try {\n result = await assemblePwapp(root, {\n ...internals.assemble,\n cache,\n packMemo,\n shellExtra: RELOAD_CLIENT,\n ...(host ? { envelopeEntries: host.envelopeEntries(origin) } : {}),\n })\n } catch (e) {\n const diagnostics: AssembleDiagnostic[] = [\n { severity: 'error', code: 'INTERNAL', message: e instanceof Error ? (e.stack ?? e.message) : String(e) },\n ]\n result = {\n ok: false,\n files: state?.files ?? new Map(),\n diagnostics,\n stats: { pages: 0, blocks: 0, engines: 0, atoms: 0, compiled: 0, fromCache: 0, failed: 0 },\n ms: 0,\n }\n }\n state = result\n const { stats } = result\n log(\n `${result.ok ? 'built' : 'build failed'} in ${result.ms} ms — ${stats.pages} page${stats.pages === 1 ? '' : 's'}, ${\n stats.blocks\n } block type${stats.blocks === 1 ? '' : 's'}, ${stats.compiled}/${stats.atoms} atoms compiled (${stats.fromCache} from cache${\n stats.failed ? `, ${stats.failed} failed` : ''\n })`\n )\n for (const line of logLines(result.diagnostics)) log(` ${line}`)\n broadcast('reload', { ok: result.ok })\n return { ok: result.ok, compiled: stats.compiled, diagnostics: result.diagnostics.map(formatDiagnostic), ms: result.ms }\n }\n\n let chain: Promise<unknown> = Promise.resolve()\n const rebuild = (): Promise<DevBuildResult> => {\n const next = chain.then(build, build)\n chain = next.catch(() => undefined)\n return next\n }\n\n // ── HTTP ─────────────────────────────────────────────────────────\n const handle = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const url = new URL(req.url ?? '/', 'http://localhost')\n if (url.pathname === EVENTS_PATH) {\n res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' })\n res.write(': connected\\n\\n')\n clients.add(res)\n req.on('close', () => clients.delete(res))\n return\n }\n if (url.pathname === RELOAD_PATH) {\n send(res, 200, CONTENT_TYPES['.js'] as string, RELOAD_JS, req.method === 'HEAD')\n return\n }\n if (url.pathname === STATUS_PATH) {\n send(res, 200, CONTENT_TYPES['.json'] as string, JSON.stringify({ ok: state?.ok ?? false, diagnostics: state?.diagnostics ?? [] }))\n return\n }\n if (host && (await host.handle(req, res))) return\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n send(res, 405, CONTENT_TYPES['.txt'] as string, 'method not allowed')\n return\n }\n const head = req.method === 'HEAD'\n let path: string\n try {\n path = decodeURIComponent(url.pathname)\n } catch {\n send(res, 400, CONTENT_TYPES['.txt'] as string, 'bad path', head)\n return\n }\n let rel = path.replace(/^\\/+/, '')\n if (rel === '' || rel.endsWith('/')) rel += 'index.html'\n if (rel.split('/').some((s) => s === '..' || s === '.') || rel.includes('\\\\') || rel.includes('\\0')) {\n send(res, 400, CONTENT_TYPES['.txt'] as string, 'bad path', head)\n return\n }\n const current = state\n const isPage = rel === 'index.html' || extname(rel) === ''\n if (isPage && current && !current.ok) {\n send(res, 200, CONTENT_TYPES['.html'] as string, overlayHtml(current.diagnostics), head)\n return\n }\n // `_headers` configures a static host; it is not part of the site.\n const file =\n rel === '_headers'\n ? undefined\n : (current?.files.get(rel) ?? (extname(rel) === '' ? current?.files.get('index.html') : undefined))\n if (!file) {\n send(res, 404, CONTENT_TYPES['.txt'] as string, `not found: /${rel}`, head)\n return\n }\n // A nested page path answered with the shell needs the app's base, or the\n // shell's relative script addresses resolve under the page's folder.\n const body = isPage && rel !== 'index.html' ? withBaseHref(file) : file\n send(res, 200, contentTypeOf(isPage ? 'index.html' : rel), body, head)\n }\n\n const server = createServer((req, res) => {\n handle(req, res).catch((e: unknown) => {\n if (!res.headersSent) send(res, 500, CONTENT_TYPES['.txt'] as string, e instanceof Error ? e.message : String(e))\n else res.end()\n })\n })\n await new Promise<void>((ok, fail) => {\n server.once('error', fail)\n server.listen(options.port ?? DEFAULT_PORT, hostname, () => {\n server.off('error', fail)\n ok()\n })\n })\n const port = (server.address() as AddressInfo).port\n const url = urlFor(hostname, port)\n origin = url.replace(/\\/$/, '')\n if (host) {\n log(`local host mounted at ${origin}${HOST_PREFIX} — development only: records in memory, one user, any password`)\n }\n\n await rebuild()\n\n let watcher: Watcher | null = null\n if (internals.watch !== false) {\n watcher = watchFolder(\n root,\n (paths) => {\n // A pack build changed (or the platform could not say what did): read it again.\n if (paths === null || paths.some((p) => p.startsWith(`${PWF_DIR}/packs`))) packMemo.clear()\n void rebuild()\n },\n internals.watch ?? {}\n )\n log(`watching ${root} (${watcher.mode === 'native' ? 'file events' : 'polling'})`)\n }\n\n let closed: Promise<void> | null = null\n return {\n url,\n rebuild,\n close() {\n closed ??= (async () => {\n watcher?.close()\n for (const c of clients) c.end()\n clients.clear()\n await new Promise<void>((ok) => {\n server.close(() => ok())\n server.closeAllConnections()\n })\n await chain\n })()\n return closed\n },\n }\n}\n\n/** Implements the `pwf dev` contract (see ./types.ts). */\nexport const startDevServer: StartDevServer = (options) => createDevServer(options)\n"]}
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/dev/server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,YAAY,EAA6C,MAAM,WAAW,CAAA;AAEnF,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AAElD,OAAO,EAAE,aAAa,EAA6C,MAAM,eAAe,CAAA;AACxF,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAA;AACjD,OAAO,EAAE,gBAAgB,EAA2B,MAAM,kBAAkB,CAAA;AAC5E,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAA;AAC3C,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,aAAa,EAAE,SAAS,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;AAC3G,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AACzC,OAAO,EAAE,OAAO,EAAiB,MAAM,cAAc,CAAA;AAErD,OAAO,EAAE,WAAW,EAAmC,MAAM,cAAc,CAAA;AAE3E,MAAM,CAAC,MAAM,YAAY,GAAG,IAAI,CAAA;AAChC,MAAM,CAAC,MAAM,gBAAgB,GAAG,WAAW,CAAA;AAC3C,mDAAmD;AACnD,MAAM,CAAC,MAAM,WAAW,GAAG,QAAQ,CAAA;AAYnC,MAAM,aAAa,GAAqC;IACtD,OAAO,EAAE,0BAA0B;IACnC,KAAK,EAAE,gCAAgC;IACvC,MAAM,EAAE,gCAAgC;IACxC,OAAO,EAAE,iCAAiC;IAC1C,MAAM,EAAE,iCAAiC;IACzC,MAAM,EAAE,yBAAyB;IACjC,MAAM,E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C,OAAO,CAAC,CAAA","sourcesContent":["/**\n * `pwf dev`: serves an app folder as a pwapp and keeps it current.\n *\n * One `node:http` server on 127.0.0.1 (port 4600 by default). It assembles\n * the app into memory (see ./assemble.ts), serves the files from there,\n * watches the folder, reassembles on change and tells the open page to reload\n * through Server-Sent Events. While the last build has errors the page is an\n * overlay listing them; the terminal gets the same list.\n *\n * When the app declares sign-in or records it needs a local host. A host\n * passed in `localHost` is mounted on the same server: requests it claims go\n * to `host.handle()`, and the envelope carries `host.envelopeEntries()`.\n * This module never constructs a host itself (it depends on the host's\n * interface only); a caller that can make one passes `createHost`.\n */\nimport { createServer, type IncomingMessage, type ServerResponse } from 'node:http'\nimport type { AddressInfo } from 'node:net'\nimport { extname, join, resolve } from 'node:path'\nimport type { CreateLocalHost, LocalHost } from '../host/index.js'\nimport { assemblePwapp, type AssembleOptions, type AssembleResult } from './assemble.js'\nimport { createCompileCache } from './compile.js'\nimport { formatDiagnostic, type AssembleDiagnostic } from './diagnostics.js'\nimport { hostNeeds } from './needs-host.js'\nimport { EVENTS_PATH, overlayHtml, RELOAD_CLIENT, RELOAD_JS, RELOAD_PATH, STATUS_PATH } from './overlay.js'\nimport { withBaseHref } from './shell.js'\nimport { PWF_DIR, type PackMemo } from './sources.js'\nimport type { DevBuildResult, DevServer, DevServerOptions, StartDevServer } from './types.js'\nimport { watchFolder, type WatchOptions, type Watcher } from './watcher.js'\n\nexport const DEFAULT_PORT = 4600\nexport const DEFAULT_HOSTNAME = '127.0.0.1'\n/** Where a host this server creates is mounted. */\nexport const HOST_PREFIX = '/_host'\n\n/** Seams for the `dev` command and for tests; not part of the public contract. */\nexport interface DevServerInternals {\n /** Watching; `false` turns it off. */\n readonly watch?: WatchOptions | false\n /** Makes a host when the app needs one and none was passed. */\n readonly createHost?: CreateLocalHost\n /** Assembly options (runtime bundles, cache folder). */\n readonly assemble?: Pick<AssembleOptions, 'runtime' | 'cacheDir' | 'publishedAt'>\n}\n\nconst CONTENT_TYPES: Readonly<Record<string, string>> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.map': 'application/json; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n '.avif': 'image/avif',\n '.ico': 'image/x-icon',\n '.woff2': 'font/woff2',\n '.txt': 'text/plain; charset=utf-8',\n}\n\nexport function contentTypeOf(path: string): string {\n return CONTENT_TYPES[extname(path).toLowerCase()] ?? 'application/octet-stream'\n}\n\nfunction isLocalHost(value: unknown): value is LocalHost {\n return (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as LocalHost).handle === 'function' &&\n typeof (value as LocalHost).envelopeEntries === 'function'\n )\n}\n\n/** The address a browser should open for a bound interface. */\nexport function urlFor(hostname: string, port: number): string {\n const h = hostname === '0.0.0.0' || hostname === '::' || hostname === '' ? 'localhost' : hostname\n return `http://${h.includes(':') ? `[${h}]` : h}:${port}/`\n}\n\nfunction send(res: ServerResponse, status: number, type: string, body: string | Uint8Array, head = false): void {\n res.writeHead(status, {\n 'content-type': type,\n 'cache-control': 'no-store',\n 'content-length': typeof body === 'string' ? Buffer.byteLength(body) : body.byteLength,\n })\n res.end(head ? undefined : body)\n}\n\n/** Lines for the terminal: everything that is the app's own, and a count of what pinned packs say. */\nexport function logLines(diagnostics: readonly AssembleDiagnostic[]): string[] {\n const own: string[] = []\n let packWarnings = 0\n for (const d of diagnostics) {\n if (d.severity !== 'error' && d.path?.startsWith(`${PWF_DIR}/`)) {\n packWarnings++\n continue\n }\n if (d.severity === 'info') continue\n own.push(formatDiagnostic(d))\n }\n if (packWarnings > 0) own.push(`${packWarnings} finding${packWarnings === 1 ? '' : 's'} in pinned packs (\\`pwf build\\` lists them)`)\n return own\n}\n\n/** Starts the dev server with the internal seams. {@link startDevServer} is the public entry. */\nexport async function createDevServer(options: DevServerOptions, internals: DevServerInternals = {}): Promise<DevServer> {\n const root = resolve(options.root)\n const log = options.log ?? ((): void => undefined)\n const hostname = options.hostname ?? DEFAULT_HOSTNAME\n const cache = createCompileCache(\n internals.assemble?.cacheDir === undefined ? join(root, PWF_DIR, 'build-cache') : internals.assemble.cacheDir\n )\n\n // ── the local host ───────────────────────────────────────────────\n let origin = ''\n let host: LocalHost | null = isLocalHost(options.localHost) ? options.localHost : null\n let hostNoted = false\n /**\n * Mounts the host the first time the app needs one. Asked again on every\n * build, not only at start: an app that starts as a bare page and gains its\n * first entity or sign-in while the server runs needs the host from that\n * build on, or its pages bind no data and its forms send nothing.\n */\n const ensureHost = async (): Promise<void> => {\n if (host || options.localHost === false) return\n const needs = await hostNeeds(root)\n const wanted = options.localHost === true || needs.length > 0\n if (wanted && internals.createHost) {\n host = internals.createHost({ root, prefix: HOST_PREFIX })\n if (origin) log(`local host mounted at ${origin}${HOST_PREFIX} — development only: records in memory, no password checked`)\n } else if (wanted && !hostNoted) {\n hostNoted = true\n log(\n `note: this app declares ${needs.join(' and ') || 'a host'}, but no local host is mounted — pages render, ${\n needs.includes('sign-in') ? 'sign-in cannot complete and ' : ''\n }data stays empty`\n )\n }\n }\n await ensureHost()\n\n // ── state ────────────────────────────────────────────────────────\n let state: AssembleResult | null = null\n const packMemo: PackMemo = new Map()\n const clients = new Set<ServerResponse>()\n\n const broadcast = (event: string, data: unknown): void => {\n const frame = `event: ${event}\\ndata: ${JSON.stringify(data)}\\n\\n`\n for (const c of clients) c.write(frame)\n }\n\n const build = async (): Promise<DevBuildResult> => {\n let result: AssembleResult\n await ensureHost()\n try {\n result = await assemblePwapp(root, {\n ...internals.assemble,\n cache,\n packMemo,\n shellExtra: RELOAD_CLIENT,\n // Host addresses go out relative ('/_host/…'), so a page reaches its host at whatever\n // address it was opened on — localhost, 127.0.0.1, a LAN name, a preview proxy. An\n // origin fixed at start-up made every other address a cross-origin write the browser blocks.\n ...(host ? { envelopeEntries: host.envelopeEntries('') } : {}),\n })\n } catch (e) {\n const diagnostics: AssembleDiagnostic[] = [\n { severity: 'error', code: 'INTERNAL', message: e instanceof Error ? (e.stack ?? e.message) : String(e) },\n ]\n result = {\n ok: false,\n files: state?.files ?? new Map(),\n diagnostics,\n stats: { pages: 0, blocks: 0, engines: 0, atoms: 0, compiled: 0, fromCache: 0, failed: 0 },\n ms: 0,\n }\n }\n state = result\n const { stats } = result\n log(\n `${result.ok ? 'built' : 'build failed'} in ${result.ms} ms — ${stats.pages} page${stats.pages === 1 ? '' : 's'}, ${\n stats.blocks\n } block type${stats.blocks === 1 ? '' : 's'}, ${stats.compiled}/${stats.atoms} atoms compiled (${stats.fromCache} from cache${\n stats.failed ? `, ${stats.failed} failed` : ''\n })`\n )\n for (const line of logLines(result.diagnostics)) log(` ${line}`)\n broadcast('reload', { ok: result.ok })\n return { ok: result.ok, compiled: stats.compiled, diagnostics: result.diagnostics.map(formatDiagnostic), ms: result.ms }\n }\n\n let chain: Promise<unknown> = Promise.resolve()\n const rebuild = (): Promise<DevBuildResult> => {\n const next = chain.then(build, build)\n chain = next.catch(() => undefined)\n return next\n }\n\n // ── HTTP ─────────────────────────────────────────────────────────\n const handle = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const url = new URL(req.url ?? '/', 'http://localhost')\n if (url.pathname === EVENTS_PATH) {\n res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' })\n res.write(': connected\\n\\n')\n clients.add(res)\n req.on('close', () => clients.delete(res))\n return\n }\n if (url.pathname === RELOAD_PATH) {\n send(res, 200, CONTENT_TYPES['.js'] as string, RELOAD_JS, req.method === 'HEAD')\n return\n }\n if (url.pathname === STATUS_PATH) {\n send(res, 200, CONTENT_TYPES['.json'] as string, JSON.stringify({ ok: state?.ok ?? false, diagnostics: state?.diagnostics ?? [] }))\n return\n }\n if (host && (await host.handle(req, res))) return\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n send(res, 405, CONTENT_TYPES['.txt'] as string, 'method not allowed')\n return\n }\n const head = req.method === 'HEAD'\n let path: string\n try {\n path = decodeURIComponent(url.pathname)\n } catch {\n send(res, 400, CONTENT_TYPES['.txt'] as string, 'bad path', head)\n return\n }\n let rel = path.replace(/^\\/+/, '')\n if (rel === '' || rel.endsWith('/')) rel += 'index.html'\n if (rel.split('/').some((s) => s === '..' || s === '.') || rel.includes('\\\\') || rel.includes('\\0')) {\n send(res, 400, CONTENT_TYPES['.txt'] as string, 'bad path', head)\n return\n }\n const current = state\n const isPage = rel === 'index.html' || extname(rel) === ''\n if (isPage && current && !current.ok) {\n send(res, 200, CONTENT_TYPES['.html'] as string, overlayHtml(current.diagnostics), head)\n return\n }\n // `_headers` configures a static host; it is not part of the site.\n const file =\n rel === '_headers'\n ? undefined\n : (current?.files.get(rel) ?? (extname(rel) === '' ? current?.files.get('index.html') : undefined))\n if (!file) {\n send(res, 404, CONTENT_TYPES['.txt'] as string, `not found: /${rel}`, head)\n return\n }\n // A nested page path answered with the shell needs the app's base, or the\n // shell's relative script addresses resolve under the page's folder.\n const body = isPage && rel !== 'index.html' ? withBaseHref(file) : file\n send(res, 200, contentTypeOf(isPage ? 'index.html' : rel), body, head)\n }\n\n const server = createServer((req, res) => {\n handle(req, res).catch((e: unknown) => {\n if (!res.headersSent) send(res, 500, CONTENT_TYPES['.txt'] as string, e instanceof Error ? e.message : String(e))\n else res.end()\n })\n })\n await new Promise<void>((ok, fail) => {\n server.once('error', fail)\n server.listen(options.port ?? DEFAULT_PORT, hostname, () => {\n server.off('error', fail)\n ok()\n })\n })\n const port = (server.address() as AddressInfo).port\n const url = urlFor(hostname, port)\n origin = url.replace(/\\/$/, '')\n if (host) {\n log(`local host mounted at ${origin}${HOST_PREFIX} — development only: records in memory, no password checked`)\n }\n\n await rebuild()\n\n let watcher: Watcher | null = null\n if (internals.watch !== false) {\n watcher = watchFolder(\n root,\n (paths) => {\n // A pack build changed (or the platform could not say what did): read it again.\n if (paths === null || paths.some((p) => p.startsWith(`${PWF_DIR}/packs`))) packMemo.clear()\n void rebuild()\n },\n internals.watch ?? {}\n )\n log(`watching ${root} (${watcher.mode === 'native' ? 'file events' : 'polling'})`)\n }\n\n let closed: Promise<void> | null = null\n return {\n url,\n rebuild,\n close() {\n closed ??= (async () => {\n watcher?.close()\n for (const c of clients) c.end()\n clients.clear()\n await new Promise<void>((ok) => {\n server.close(() => ok())\n server.closeAllConnections()\n })\n await chain\n })()\n return closed\n },\n }\n}\n\n/** Implements the `pwf dev` contract (see ./types.ts). */\nexport const startDevServer: StartDevServer = (options) => createDevServer(options)\n"]}
|
package/dist/dev/types.d.ts
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* the runner against it. When the app declares data or sign-in, it mounts a
|
|
8
8
|
* local host (../host) that implements the session and data protocols.
|
|
9
9
|
*/
|
|
10
|
-
import type { LocalHost } from '../host/
|
|
10
|
+
import type { LocalHost } from '../host/index.js';
|
|
11
11
|
export interface DevServerOptions {
|
|
12
12
|
/** Absolute path of the pwpack folder to serve. */
|
|
13
13
|
readonly root: string;
|
package/dist/dev/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/dev/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG","sourcesContent":["/**\n * The contract between `pwf dev` (./server.ts, written by the dev lane) and\n * the rest of the CLI.\n *\n * `pwf dev` watches a pwpack folder, compiles its atoms with the engine's\n * compiler, builds an envelope from the folder, and serves a page that boots\n * the runner against it. When the app declares data or sign-in, it mounts a\n * local host (../host) that implements the session and data protocols.\n */\n\nimport type { LocalHost } from '../host/
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/dev/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG","sourcesContent":["/**\n * The contract between `pwf dev` (./server.ts, written by the dev lane) and\n * the rest of the CLI.\n *\n * `pwf dev` watches a pwpack folder, compiles its atoms with the engine's\n * compiler, builds an envelope from the folder, and serves a page that boots\n * the runner against it. When the app declares data or sign-in, it mounts a\n * local host (../host) that implements the session and data protocols.\n */\n\nimport type { LocalHost } from '../host/index.js'\n\nexport interface DevServerOptions {\n /** Absolute path of the pwpack folder to serve. */\n readonly root: string\n /** Port to listen on; 0 picks a free port. Default 4600. */\n readonly port?: number\n /** Host interface to bind. Default 127.0.0.1. */\n readonly hostname?: string\n /** Mount a local host for data and sign-in. Default: only when the app declares them. */\n readonly localHost?: boolean | LocalHost\n /** Called with human-readable progress lines. */\n readonly log?: (line: string) => void\n}\n\nexport interface DevServer {\n /** The URL the app is served at, e.g. http://127.0.0.1:4600/. */\n readonly url: string\n /** Rebuilds now (the watcher also rebuilds on change). */\n rebuild(): Promise<DevBuildResult>\n /** Stops the watcher and the HTTP server. */\n close(): Promise<void>\n}\n\nexport interface DevBuildResult {\n readonly ok: boolean\n /** Atoms compiled in this build. */\n readonly compiled: number\n /** Compiler and validation diagnostics, already formatted for a terminal. */\n readonly diagnostics: readonly string[]\n readonly ms: number\n}\n\n/** Implemented in ./server.ts. */\nexport type StartDevServer = (options: DevServerOptions) => Promise<DevServer>\n"]}
|
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
* app/definitions/auth.json who may enter (definitions.md, `auth.json`)
|
|
5
5
|
* app/definitions/entities.json the collections the host keeps
|
|
6
6
|
* app/surfaces/<key>.receipt.json the pages it serves
|
|
7
|
-
* app/
|
|
7
|
+
* app/content/<typeId>.json the app's shipped records (data-protocol §6)
|
|
8
|
+
* app/data/<typeId>.jsonl | .json development records, never published
|
|
8
9
|
*
|
|
9
10
|
* Read on every call, never cached: `pwf dev` edits these files while the
|
|
10
11
|
* host runs, and a definition change must apply without a restart. An absent
|
|
@@ -22,6 +23,7 @@ export interface AuthDeclaration {
|
|
|
22
23
|
readonly audience?: string;
|
|
23
24
|
};
|
|
24
25
|
readonly access: {
|
|
26
|
+
readonly roles: readonly string[];
|
|
25
27
|
readonly rules: readonly {
|
|
26
28
|
readonly subject: string;
|
|
27
29
|
readonly model: string;
|
|
@@ -38,8 +40,6 @@ export interface EntityDeclaration {
|
|
|
38
40
|
readonly typeId: string;
|
|
39
41
|
readonly displayName?: string;
|
|
40
42
|
readonly fields: readonly EntityField[];
|
|
41
|
-
/** Carried member (not in the spec yet): `"owner"` makes the collection per-visitor. */
|
|
42
|
-
readonly scope?: string;
|
|
43
43
|
}
|
|
44
44
|
/** `undefined` when the app declares no `auth.json` (or an empty one). */
|
|
45
45
|
export declare function readAuth(root: string): AuthDeclaration | undefined;
|
|
@@ -49,13 +49,13 @@ export declare const PAGE_KEY: RegExp;
|
|
|
49
49
|
export declare function surfaceKeys(root: string): string[];
|
|
50
50
|
export declare function readReceipt(root: string, key: string): Record<string, unknown> | undefined;
|
|
51
51
|
/**
|
|
52
|
-
* Seed rows for one collection.
|
|
52
|
+
* Seed rows for one collection: the app's content, then its development data.
|
|
53
53
|
*
|
|
54
|
-
*
|
|
55
|
-
* `
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
*
|
|
54
|
+
* Two folders, one shape (data-protocol §6):
|
|
55
|
+
* - `app/content/<typeId>.json` — records the app ships for every visitor; a
|
|
56
|
+
* publisher inserts each one the record store does not hold yet.
|
|
57
|
+
* - `app/data/<typeId>.json` — development and test records; never published.
|
|
58
|
+
* A data row with the id of a content row replaces it here, so a developer can
|
|
59
|
+
* try a variant without editing the content.
|
|
60
60
|
*/
|
|
61
61
|
export declare function readSeed(root: string, typeId: string): Record<string, unknown>[];
|
package/dist/host/definitions.js
CHANGED
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
* app/definitions/auth.json who may enter (definitions.md, `auth.json`)
|
|
5
5
|
* app/definitions/entities.json the collections the host keeps
|
|
6
6
|
* app/surfaces/<key>.receipt.json the pages it serves
|
|
7
|
-
* app/
|
|
7
|
+
* app/content/<typeId>.json the app's shipped records (data-protocol §6)
|
|
8
|
+
* app/data/<typeId>.jsonl | .json development records, never published
|
|
8
9
|
*
|
|
9
10
|
* Read on every call, never cached: `pwf dev` edits these files while the
|
|
10
11
|
* host runs, and a definition change must apply without a restart. An absent
|
|
@@ -51,7 +52,7 @@ export function readAuth(root) {
|
|
|
51
52
|
},
|
|
52
53
|
}
|
|
53
54
|
: {}),
|
|
54
|
-
access: { rules },
|
|
55
|
+
access: { roles: strings(access.roles), rules },
|
|
55
56
|
};
|
|
56
57
|
}
|
|
57
58
|
export function readEntities(root) {
|
|
@@ -68,7 +69,6 @@ export function readEntities(root) {
|
|
|
68
69
|
typeId: e.typeId,
|
|
69
70
|
...(typeof e.displayName === 'string' ? { displayName: e.displayName } : {}),
|
|
70
71
|
fields,
|
|
71
|
-
...(typeof e.scope === 'string' ? { scope: e.scope } : {}),
|
|
72
72
|
},
|
|
73
73
|
];
|
|
74
74
|
});
|
|
@@ -92,19 +92,34 @@ export function readReceipt(root, key) {
|
|
|
92
92
|
return isObject(raw) ? raw : undefined;
|
|
93
93
|
}
|
|
94
94
|
/**
|
|
95
|
-
* Seed rows for one collection.
|
|
95
|
+
* Seed rows for one collection: the app's content, then its development data.
|
|
96
96
|
*
|
|
97
|
-
*
|
|
98
|
-
* `
|
|
99
|
-
*
|
|
100
|
-
*
|
|
101
|
-
*
|
|
102
|
-
*
|
|
97
|
+
* Two folders, one shape (data-protocol §6):
|
|
98
|
+
* - `app/content/<typeId>.json` — records the app ships for every visitor; a
|
|
99
|
+
* publisher inserts each one the record store does not hold yet.
|
|
100
|
+
* - `app/data/<typeId>.json` — development and test records; never published.
|
|
101
|
+
* A data row with the id of a content row replaces it here, so a developer can
|
|
102
|
+
* try a variant without editing the content.
|
|
103
103
|
*/
|
|
104
104
|
export function readSeed(root, typeId) {
|
|
105
105
|
if (!PAGE_KEY.test(typeId))
|
|
106
106
|
return [];
|
|
107
|
-
const
|
|
107
|
+
const rows = new Map();
|
|
108
|
+
let anonymous = 0;
|
|
109
|
+
for (const row of [...readRecordsFile(join(root, 'app', 'content'), typeId), ...readRecordsFile(join(root, 'app', 'data'), typeId)]) {
|
|
110
|
+
const id = typeof row.id === 'string' || typeof row.id === 'number' ? String(row.id) : `\0${anonymous++}`;
|
|
111
|
+
rows.set(id, row);
|
|
112
|
+
}
|
|
113
|
+
return [...rows.values()];
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* `<dir>/<typeId>.json` holding `{ "data": [ …records ] }` — the same `data`
|
|
117
|
+
* envelope a record list answer uses. A record may carry its own `id`;
|
|
118
|
+
* `createdAt`/`updatedAt` are filled when absent. Also accepted, for
|
|
119
|
+
* hand-written files only: `<dir>/<typeId>.jsonl`, one JSON object per line
|
|
120
|
+
* (blank lines skipped), read when no `.json` file exists.
|
|
121
|
+
*/
|
|
122
|
+
function readRecordsFile(dir, typeId) {
|
|
108
123
|
const jsonPath = join(dir, `${typeId}.json`);
|
|
109
124
|
const json = readJson(jsonPath);
|
|
110
125
|
if (json !== undefined) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/host/definitions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AAC/D,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AA+BhC,SAAS,QAAQ,CAAC,IAAY;IAC5B,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;QAAE,OAAO,SAAS,CAAA;IACvC,MAAM,IAAI,GAAG,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,CAAA;IACvC,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAY,CAAA;IACpC,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,uBAAwB,GAAa,CAAC,OAAO,EAAE,CAAC,CAAA;IACzE,CAAC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AAC,oBAAoB,CAAC,CAAA;QACpD,CAAC;QACD,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,IAAI,CAAC,uBAAuB,CAAC,CAAA;QACzE,OAAO,GAAG,CAAA;IACZ,CAAC,CAAC,CAAA;AACN,CAAC","sourcesContent":["/**\n * What the local host reads from the pwpack folder.\n *\n * app/definitions/auth.json who may enter (definitions.md, `auth.json`)\n * app/definitions/entities.json the collections the host keeps\n * app/surfaces/<key>.receipt.json the pages it serves\n * app/data/<typeId>.jsonl | .json seed rows (a convention of this host)\n *\n * Read on every call, never cached: `pwf dev` edits these files while the\n * host runs, and a definition change must apply without a restart. An absent\n * file is \"not declared\"; an unreadable one is reported as an error rather\n * than guessed around.\n */\n\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nexport interface AuthDeclaration {\n readonly required: boolean\n readonly topology: 'app' | 'external'\n readonly methods: readonly string[]\n readonly issuer?: {\n readonly issuer: string\n readonly clientId: string\n readonly scopes: readonly string[]\n readonly audience?: string\n }\n readonly access: {\n readonly rules: readonly { readonly subject: string; readonly model: string; readonly rule: string }[]\n }\n}\n\nexport interface EntityField {\n readonly name: string\n readonly type: string\n readonly required: boolean\n}\n\nexport interface EntityDeclaration {\n readonly typeId: string\n readonly displayName?: string\n readonly fields: readonly EntityField[]\n /** Carried member (not in the spec yet): `\"owner\"` makes the collection per-visitor. */\n readonly scope?: string\n}\n\nfunction readJson(path: string): unknown {\n if (!existsSync(path)) return undefined\n const text = readFileSync(path, 'utf8')\n try {\n return JSON.parse(text) as unknown\n } catch (err) {\n throw new Error(`${path} is not valid JSON: ${(err as Error).message}`)\n }\n}\n\nconst isObject = (v: unknown): v is Record<string, unknown> => Boolean(v) && typeof v === 'object' && !Array.isArray(v)\nconst strings = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [])\n\n/** `undefined` when the app declares no `auth.json` (or an empty one). */\nexport function readAuth(root: string): AuthDeclaration | undefined {\n const raw = readJson(join(root, 'app', 'definitions', 'auth.json'))\n if (!isObject(raw) || Object.keys(raw).length === 0) return undefined\n const topology = raw.topology === 'external' ? 'external' : 'app'\n const iss = isObject(raw.issuer) ? raw.issuer : undefined\n const access = isObject(raw.access) ? raw.access : {}\n const rules = (Array.isArray(access.rules) ? access.rules : [])\n .filter(isObject)\n .map((r) => ({ subject: String(r.subject ?? ''), model: String(r.model ?? ''), rule: String(r.rule ?? '') }))\n return {\n required: raw.required === true,\n topology,\n methods: strings(raw.methods),\n ...(iss && typeof iss.issuer === 'string' && typeof iss.clientId === 'string'\n ? {\n issuer: {\n issuer: iss.issuer,\n clientId: iss.clientId,\n scopes: Array.isArray(iss.scopes) ? strings(iss.scopes) : ['openid', 'profile', 'email'],\n ...(typeof iss.audience === 'string' && iss.audience ? { audience: iss.audience } : {}),\n },\n }\n : {}),\n access: { rules },\n }\n}\n\nexport function readEntities(root: string): EntityDeclaration[] {\n const raw = readJson(join(root, 'app', 'definitions', 'entities.json'))\n const list = isObject(raw) && Array.isArray(raw.entities) ? raw.entities : []\n return list.filter(isObject).flatMap((e) => {\n if (typeof e.typeId !== 'string' || !e.typeId) return []\n const fields = (Array.isArray(e.fields) ? e.fields : []).filter(isObject).flatMap((f) =>\n typeof f.name === 'string' && f.name\n ? [{ name: f.name, type: typeof f.type === 'string' ? f.type : 'text', required: f.required === true }]\n : []\n )\n return [\n {\n typeId: e.typeId,\n ...(typeof e.displayName === 'string' ? { displayName: e.displayName } : {}),\n fields,\n ...(typeof e.scope === 'string' ? { scope: e.scope } : {}),\n },\n ]\n })\n}\n\n/** A page key is a file name, never a path. */\nexport const PAGE_KEY = /^[A-Za-z0-9][A-Za-z0-9_-]*$/\n\nexport function surfaceKeys(root: string): string[] {\n const dir = join(root, 'app', 'surfaces')\n if (!existsSync(dir)) return []\n return readdirSync(dir)\n .filter((f) => f.endsWith('.receipt.json'))\n .map((f) => f.slice(0, -'.receipt.json'.length))\n .filter((k) => PAGE_KEY.test(k))\n .sort()\n}\n\nexport function readReceipt(root: string, key: string): Record<string, unknown> | undefined {\n if (!PAGE_KEY.test(key)) return undefined\n const raw = readJson(join(root, 'app', 'surfaces', `${key}.receipt.json`))\n return isObject(raw) ? raw : undefined\n}\n\n/**\n * Seed rows for one collection.\n *\n * THE CONVENTION (proposed for the spec): `app/data/<typeId>.json` holding\n * `{ \"data\": [ …records ] }` — the same `data` envelope a record list answer\n * uses. A record may carry its own `id`; `createdAt`/`updatedAt` are filled\n * when absent. Also accepted, for hand-written seed files only:\n * `app/data/<typeId>.jsonl`, one JSON object per line (blank lines skipped),\n * read when no `.json` file exists.\n */\nexport function readSeed(root: string, typeId: string): Record<string, unknown>[] {\n if (!PAGE_KEY.test(typeId)) return []\n const dir = join(root, 'app', 'data')\n const jsonPath = join(dir, `${typeId}.json`)\n const json = readJson(jsonPath)\n if (json !== undefined) {\n if (!isObject(json) || !Array.isArray(json.data)) {\n throw new Error(`${jsonPath} must be { \"data\": [ ...records ] }`)\n }\n return json.data.filter(isObject)\n }\n const jsonl = join(dir, `${typeId}.jsonl`)\n if (!existsSync(jsonl)) return []\n return readFileSync(jsonl, 'utf8')\n .split(/\\r?\\n/)\n .map((line, i) => [line.trim(), i + 1] as const)\n .filter(([line]) => line !== '')\n .map(([line, n]) => {\n let row: unknown\n try {\n row = JSON.parse(line)\n } catch {\n throw new Error(`${jsonl}:${n} is not valid JSON`)\n }\n if (!isObject(row)) throw new Error(`${jsonl}:${n} is not a JSON object`)\n return row\n })\n}\n"]}
|
|
1
|
+
{"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/host/definitions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AAC/D,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AA8BhC,SAAS,QAAQ,CAAC,I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C,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;YACjD,MAAM,IAAI,KAAK,CAAC,GAAG,QAAQ,qCAAqC,CAAC,CAAA;QACnE,CAAC;QACD,OAAO,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAA;IACnC,CAAC;IACD,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,MAAM,QAAQ,CAAC,CAAA;IAC1C,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC;QAAE,OAAO,EAAE,CAAA;IACjC,OAAO,YAAY,CAAC,KAAK,EAAE,MAAM,CAAC;SAC/B,KAAK,CAAC,OAAO,CAAC;SACd,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,EAAE,CAAC,GAAG,CAAC,CAAU,CAAC;SAC/C,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC,IAAI,KAAK,EAAE,CAAC;SAC/B,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,EAAE,EAAE;QACjB,IAAI,GAAY,CAAA;QAChB,IAAI,CAAC;YACH,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;QACxB,CAAC;QAAC,MAAM,CAAC;YACP,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,IAAI,CAAC,oBAAoB,CAAC,CAAA;QACpD,CAAC;QACD,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,IAAI,CAAC,uBAAuB,CAAC,CAAA;QACzE,OAAO,GAAG,CAAA;IACZ,CAAC,CAAC,CAAA;AACN,CAAC","sourcesContent":["/**\n * What the local host reads from the pwpack folder.\n *\n * app/definitions/auth.json who may enter (definitions.md, `auth.json`)\n * app/definitions/entities.json the collections the host keeps\n * app/surfaces/<key>.receipt.json the pages it serves\n * app/content/<typeId>.json the app's shipped records (data-protocol §6)\n * app/data/<typeId>.jsonl | .json development records, never published\n *\n * Read on every call, never cached: `pwf dev` edits these files while the\n * host runs, and a definition change must apply without a restart. An absent\n * file is \"not declared\"; an unreadable one is reported as an error rather\n * than guessed around.\n */\n\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nexport interface AuthDeclaration {\n readonly required: boolean\n readonly topology: 'app' | 'external'\n readonly methods: readonly string[]\n readonly issuer?: {\n readonly issuer: string\n readonly clientId: string\n readonly scopes: readonly string[]\n readonly audience?: string\n }\n readonly access: {\n readonly roles: readonly string[]\n readonly rules: readonly { readonly subject: string; readonly model: string; readonly rule: string }[]\n }\n}\n\nexport interface EntityField {\n readonly name: string\n readonly type: string\n readonly required: boolean\n}\n\nexport interface EntityDeclaration {\n readonly typeId: string\n readonly displayName?: string\n readonly fields: readonly EntityField[]\n}\n\nfunction readJson(path: string): unknown {\n if (!existsSync(path)) return undefined\n const text = readFileSync(path, 'utf8')\n try {\n return JSON.parse(text) as unknown\n } catch (err) {\n throw new Error(`${path} is not valid JSON: ${(err as Error).message}`)\n }\n}\n\nconst isObject = (v: unknown): v is Record<string, unknown> => Boolean(v) && typeof v === 'object' && !Array.isArray(v)\nconst strings = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [])\n\n/** `undefined` when the app declares no `auth.json` (or an empty one). */\nexport function readAuth(root: string): AuthDeclaration | undefined {\n const raw = readJson(join(root, 'app', 'definitions', 'auth.json'))\n if (!isObject(raw) || Object.keys(raw).length === 0) return undefined\n const topology = raw.topology === 'external' ? 'external' : 'app'\n const iss = isObject(raw.issuer) ? raw.issuer : undefined\n const access = isObject(raw.access) ? raw.access : {}\n const rules = (Array.isArray(access.rules) ? access.rules : [])\n .filter(isObject)\n .map((r) => ({ subject: String(r.subject ?? ''), model: String(r.model ?? ''), rule: String(r.rule ?? '') }))\n return {\n required: raw.required === true,\n topology,\n methods: strings(raw.methods),\n ...(iss && typeof iss.issuer === 'string' && typeof iss.clientId === 'string'\n ? {\n issuer: {\n issuer: iss.issuer,\n clientId: iss.clientId,\n scopes: Array.isArray(iss.scopes) ? strings(iss.scopes) : ['openid', 'profile', 'email'],\n ...(typeof iss.audience === 'string' && iss.audience ? { audience: iss.audience } : {}),\n },\n }\n : {}),\n access: { roles: strings(access.roles), rules },\n }\n}\n\nexport function readEntities(root: string): EntityDeclaration[] {\n const raw = readJson(join(root, 'app', 'definitions', 'entities.json'))\n const list = isObject(raw) && Array.isArray(raw.entities) ? raw.entities : []\n return list.filter(isObject).flatMap((e) => {\n if (typeof e.typeId !== 'string' || !e.typeId) return []\n const fields = (Array.isArray(e.fields) ? e.fields : []).filter(isObject).flatMap((f) =>\n typeof f.name === 'string' && f.name\n ? [{ name: f.name, type: typeof f.type === 'string' ? f.type : 'text', required: f.required === true }]\n : []\n )\n return [\n {\n typeId: e.typeId,\n ...(typeof e.displayName === 'string' ? { displayName: e.displayName } : {}),\n fields,\n },\n ]\n })\n}\n\n/** A page key is a file name, never a path. */\nexport const PAGE_KEY = /^[A-Za-z0-9][A-Za-z0-9_-]*$/\n\nexport function surfaceKeys(root: string): string[] {\n const dir = join(root, 'app', 'surfaces')\n if (!existsSync(dir)) return []\n return readdirSync(dir)\n .filter((f) => f.endsWith('.receipt.json'))\n .map((f) => f.slice(0, -'.receipt.json'.length))\n .filter((k) => PAGE_KEY.test(k))\n .sort()\n}\n\nexport function readReceipt(root: string, key: string): Record<string, unknown> | undefined {\n if (!PAGE_KEY.test(key)) return undefined\n const raw = readJson(join(root, 'app', 'surfaces', `${key}.receipt.json`))\n return isObject(raw) ? raw : undefined\n}\n\n/**\n * Seed rows for one collection: the app's content, then its development data.\n *\n * Two folders, one shape (data-protocol §6):\n * - `app/content/<typeId>.json` — records the app ships for every visitor; a\n * publisher inserts each one the record store does not hold yet.\n * - `app/data/<typeId>.json` — development and test records; never published.\n * A data row with the id of a content row replaces it here, so a developer can\n * try a variant without editing the content.\n */\nexport function readSeed(root: string, typeId: string): Record<string, unknown>[] {\n if (!PAGE_KEY.test(typeId)) return []\n const rows = new Map<string, Record<string, unknown>>()\n let anonymous = 0\n for (const row of [...readRecordsFile(join(root, 'app', 'content'), typeId), ...readRecordsFile(join(root, 'app', 'data'), typeId)]) {\n const id = typeof row.id === 'string' || typeof row.id === 'number' ? String(row.id) : `\\0${anonymous++}`\n rows.set(id, row)\n }\n return [...rows.values()]\n}\n\n/**\n * `<dir>/<typeId>.json` holding `{ \"data\": [ …records ] }` — the same `data`\n * envelope a record list answer uses. A record may carry its own `id`;\n * `createdAt`/`updatedAt` are filled when absent. Also accepted, for\n * hand-written files only: `<dir>/<typeId>.jsonl`, one JSON object per line\n * (blank lines skipped), read when no `.json` file exists.\n */\nfunction readRecordsFile(dir: string, typeId: string): Record<string, unknown>[] {\n const jsonPath = join(dir, `${typeId}.json`)\n const json = readJson(jsonPath)\n if (json !== undefined) {\n if (!isObject(json) || !Array.isArray(json.data)) {\n throw new Error(`${jsonPath} must be { \"data\": [ ...records ] }`)\n }\n return json.data.filter(isObject)\n }\n const jsonl = join(dir, `${typeId}.jsonl`)\n if (!existsSync(jsonl)) return []\n return readFileSync(jsonl, 'utf8')\n .split(/\\r?\\n/)\n .map((line, i) => [line.trim(), i + 1] as const)\n .filter(([line]) => line !== '')\n .map(([line, n]) => {\n let row: unknown\n try {\n row = JSON.parse(line)\n } catch {\n throw new Error(`${jsonl}:${n} is not valid JSON`)\n }\n if (!isObject(row)) throw new Error(`${jsonl}:${n} is not a JSON object`)\n return row\n })\n}\n"]}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@pwfabric/cli/host` — the building blocks of the local host, for any host.
|
|
3
|
+
*
|
|
4
|
+
* `pwf dev` serves an app's sign-in, records and pages through
|
|
5
|
+
* `createLocalHost`. A host of its own (a server, a worker, a test harness)
|
|
6
|
+
* needs the same decisions, made the same way, so the pieces are exported
|
|
7
|
+
* here as they are; `pwf dev` imports them from this entry too.
|
|
8
|
+
*
|
|
9
|
+
* Access `accessOf`, `parseRule` — what a caller may do with a model
|
|
10
|
+
* under the app's `auth.json` `access` rules.
|
|
11
|
+
* Records `RecordStore` — an in-memory record store that enforces those
|
|
12
|
+
* rules (seeded from the app folder; throws `HostError`).
|
|
13
|
+
* Receipts `rewriteEntitySources` — a receipt's `entity` sources rewritten
|
|
14
|
+
* to `rest` sources against `<base>/records/…`, with
|
|
15
|
+
* `authProviderRef: <base>` so the runner sends the visitor's
|
|
16
|
+
* session there.
|
|
17
|
+
* Addresses `authAddresses` — the envelope `auth.json` for a declaration,
|
|
18
|
+
* pointed at `<base>`.
|
|
19
|
+
* Definitions `readAuth`, `readEntities`, `readSeed` — the app folder's
|
|
20
|
+
* declarations as the pieces above take them.
|
|
21
|
+
*
|
|
22
|
+
* These are Node modules (`node:fs`, `node:crypto`). Nothing here is a
|
|
23
|
+
* production server: see `createLocalHost` for what the local host is not.
|
|
24
|
+
*/
|
|
25
|
+
export { accessOf, parseRule, RecordStore } from './records.js';
|
|
26
|
+
export type { Access, AccessReach, AccessVerb, AggregateAnswer, Caller, ListAnswer, Scope, Target } from './records.js';
|
|
27
|
+
export { rewriteEntitySources } from './receipts.js';
|
|
28
|
+
export { authAddresses, createLocalHost, DEFAULT_DEV_USER, SESSION_COOKIE } from './local-host.js';
|
|
29
|
+
export { readAuth, readEntities, readSeed } from './definitions.js';
|
|
30
|
+
export type { AuthDeclaration, EntityDeclaration, EntityField } from './definitions.js';
|
|
31
|
+
export { HostError } from './http.js';
|
|
32
|
+
export type { Principal } from './tokens.js';
|
|
33
|
+
export type { CreateLocalHost, LocalHost, LocalHostOptions } from './types.js';
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@pwfabric/cli/host` — the building blocks of the local host, for any host.
|
|
3
|
+
*
|
|
4
|
+
* `pwf dev` serves an app's sign-in, records and pages through
|
|
5
|
+
* `createLocalHost`. A host of its own (a server, a worker, a test harness)
|
|
6
|
+
* needs the same decisions, made the same way, so the pieces are exported
|
|
7
|
+
* here as they are; `pwf dev` imports them from this entry too.
|
|
8
|
+
*
|
|
9
|
+
* Access `accessOf`, `parseRule` — what a caller may do with a model
|
|
10
|
+
* under the app's `auth.json` `access` rules.
|
|
11
|
+
* Records `RecordStore` — an in-memory record store that enforces those
|
|
12
|
+
* rules (seeded from the app folder; throws `HostError`).
|
|
13
|
+
* Receipts `rewriteEntitySources` — a receipt's `entity` sources rewritten
|
|
14
|
+
* to `rest` sources against `<base>/records/…`, with
|
|
15
|
+
* `authProviderRef: <base>` so the runner sends the visitor's
|
|
16
|
+
* session there.
|
|
17
|
+
* Addresses `authAddresses` — the envelope `auth.json` for a declaration,
|
|
18
|
+
* pointed at `<base>`.
|
|
19
|
+
* Definitions `readAuth`, `readEntities`, `readSeed` — the app folder's
|
|
20
|
+
* declarations as the pieces above take them.
|
|
21
|
+
*
|
|
22
|
+
* These are Node modules (`node:fs`, `node:crypto`). Nothing here is a
|
|
23
|
+
* production server: see `createLocalHost` for what the local host is not.
|
|
24
|
+
*/
|
|
25
|
+
export { accessOf, parseRule, RecordStore } from './records.js';
|
|
26
|
+
export { rewriteEntitySources } from './receipts.js';
|
|
27
|
+
export { authAddresses, createLocalHost, DEFAULT_DEV_USER, SESSION_COOKIE } from './local-host.js';
|
|
28
|
+
export { readAuth, readEntities, readSeed } from './definitions.js';
|
|
29
|
+
export { HostError } from './http.js';
|
|
30
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/host/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;AAE/D,OAAO,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAA;AACpD,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAClG,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AAEnE,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAA","sourcesContent":["/**\n * `@pwfabric/cli/host` — the building blocks of the local host, for any host.\n *\n * `pwf dev` serves an app's sign-in, records and pages through\n * `createLocalHost`. A host of its own (a server, a worker, a test harness)\n * needs the same decisions, made the same way, so the pieces are exported\n * here as they are; `pwf dev` imports them from this entry too.\n *\n * Access `accessOf`, `parseRule` — what a caller may do with a model\n * under the app's `auth.json` `access` rules.\n * Records `RecordStore` — an in-memory record store that enforces those\n * rules (seeded from the app folder; throws `HostError`).\n * Receipts `rewriteEntitySources` — a receipt's `entity` sources rewritten\n * to `rest` sources against `<base>/records/…`, with\n * `authProviderRef: <base>` so the runner sends the visitor's\n * session there.\n * Addresses `authAddresses` — the envelope `auth.json` for a declaration,\n * pointed at `<base>`.\n * Definitions `readAuth`, `readEntities`, `readSeed` — the app folder's\n * declarations as the pieces above take them.\n *\n * These are Node modules (`node:fs`, `node:crypto`). Nothing here is a\n * production server: see `createLocalHost` for what the local host is not.\n */\n\nexport { accessOf, parseRule, RecordStore } from './records.js'\nexport type { Access, AccessReach, AccessVerb, AggregateAnswer, Caller, ListAnswer, Scope, Target } from './records.js'\nexport { rewriteEntitySources } from './receipts.js'\nexport { authAddresses, createLocalHost, DEFAULT_DEV_USER, SESSION_COOKIE } from './local-host.js'\nexport { readAuth, readEntities, readSeed } from './definitions.js'\nexport type { AuthDeclaration, EntityDeclaration, EntityField } from './definitions.js'\nexport { HostError } from './http.js'\nexport type { Principal } from './tokens.js'\nexport type { CreateLocalHost, LocalHost, LocalHostOptions } from './types.js'\n"]}
|
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
* The local host — the session protocol and the data protocol, in process,
|
|
3
3
|
* for development.
|
|
4
4
|
*
|
|
5
|
-
* NOT A PRODUCTION SERVER. Records live in memory and vanish on restart;
|
|
6
|
-
*
|
|
5
|
+
* NOT A PRODUCTION SERVER. Records live in memory and vanish on restart; no
|
|
6
|
+
* password is checked (the development e-mail is the development user, any
|
|
7
|
+
* other e-mail a plain member); the issuer stand-in mints
|
|
7
8
|
* unsigned ID tokens; there is no rate limit, no CORS, no TLS. It exists so an
|
|
8
9
|
* app that declares data and sign-in runs on a laptop with no hosted service,
|
|
9
10
|
* and so the runner's sign-in wall, account control, gate and data paths are
|
|
@@ -54,6 +55,8 @@ export declare const SESSION_COOKIE = "pwf_dev_session";
|
|
|
54
55
|
* - `app`: the password door when `password` is declared; the provider
|
|
55
56
|
* buttons and the start address for every declared provider method; the
|
|
56
57
|
* gateway's session and logout addresses for either; `methods` as declared.
|
|
58
|
+
* - Either: `apiBase`, the base itself — where the app's records live, and
|
|
59
|
+
* the only address the runner sends the visitor's session to.
|
|
57
60
|
*/
|
|
58
61
|
export declare function authAddresses(auth: AuthDeclaration | undefined, base: string): Record<string, unknown> | undefined;
|
|
59
62
|
export declare const createLocalHost: CreateLocalHost;
|
package/dist/host/local-host.js
CHANGED
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
* The local host — the session protocol and the data protocol, in process,
|
|
3
3
|
* for development.
|
|
4
4
|
*
|
|
5
|
-
* NOT A PRODUCTION SERVER. Records live in memory and vanish on restart;
|
|
6
|
-
*
|
|
5
|
+
* NOT A PRODUCTION SERVER. Records live in memory and vanish on restart; no
|
|
6
|
+
* password is checked (the development e-mail is the development user, any
|
|
7
|
+
* other e-mail a plain member); the issuer stand-in mints
|
|
7
8
|
* unsigned ID tokens; there is no rate limit, no CORS, no TLS. It exists so an
|
|
8
9
|
* app that declares data and sign-in runs on a laptop with no hosted service,
|
|
9
10
|
* and so the runner's sign-in wall, account control, gate and data paths are
|
|
@@ -67,6 +68,8 @@ function providersOf(auth) {
|
|
|
67
68
|
* - `app`: the password door when `password` is declared; the provider
|
|
68
69
|
* buttons and the start address for every declared provider method; the
|
|
69
70
|
* gateway's session and logout addresses for either; `methods` as declared.
|
|
71
|
+
* - Either: `apiBase`, the base itself — where the app's records live, and
|
|
72
|
+
* the only address the runner sends the visitor's session to.
|
|
70
73
|
*/
|
|
71
74
|
export function authAddresses(auth, base) {
|
|
72
75
|
if (!auth)
|
|
@@ -79,6 +82,7 @@ export function authAddresses(auth, base) {
|
|
|
79
82
|
: [...auth.issuer.scopes, 'offline_access'];
|
|
80
83
|
return {
|
|
81
84
|
provider: 'oauth2-pkce',
|
|
85
|
+
apiBase: base,
|
|
82
86
|
issuer: `${base}/oidc`,
|
|
83
87
|
clientId: auth.issuer.clientId,
|
|
84
88
|
scopes,
|
|
@@ -110,6 +114,9 @@ export function authAddresses(auth, base) {
|
|
|
110
114
|
door.gatewaySessionUrl ??= `${base}/_auth/session`;
|
|
111
115
|
door.gatewayLogoutUrl ??= `${base}/_auth/logout`;
|
|
112
116
|
door.methods = [...auth.methods];
|
|
117
|
+
// Stated, not left for the runner to infer: every door reaches the same
|
|
118
|
+
// records, and the runner sends the visitor's session to this base only.
|
|
119
|
+
door.apiBase = base;
|
|
113
120
|
return door;
|
|
114
121
|
}
|
|
115
122
|
function segments(rest) {
|
|
@@ -140,10 +147,17 @@ export const createLocalHost = (options) => {
|
|
|
140
147
|
const issuer = new DevIssuer(bearer, user);
|
|
141
148
|
const originOf = (req) => `http://${req.headers.host ?? 'localhost'}`;
|
|
142
149
|
const principalOf = (req) => bearer.get(credentialOf(req))?.principal;
|
|
143
|
-
function startSession() {
|
|
150
|
+
function startSession(principal = user) {
|
|
144
151
|
const expiresAt = Date.now() + SESSION_TTL_MS;
|
|
145
|
-
const token = bearer.issue({ principal
|
|
146
|
-
return { token, expiresAt: new Date(expiresAt).toISOString(), principal
|
|
152
|
+
const token = bearer.issue({ principal, kind: 'session', expiresAt });
|
|
153
|
+
return { token, expiresAt: new Date(expiresAt).toISOString(), principal };
|
|
154
|
+
}
|
|
155
|
+
/** The password door signs in whoever it is told: the development user, or a plain member for any other e-mail. */
|
|
156
|
+
function principalNamed(email) {
|
|
157
|
+
if (typeof email !== 'string' || !email.trim() || email.trim().toLowerCase() === user.email.toLowerCase())
|
|
158
|
+
return user;
|
|
159
|
+
const address = email.trim().toLowerCase();
|
|
160
|
+
return { id: `dev-${address}`, email: address, displayName: address };
|
|
147
161
|
}
|
|
148
162
|
const sessionCookie = (token, maxAgeS) => `${SESSION_COOKIE}=${encodeURIComponent(token)}; Path=${prefix}/_auth; HttpOnly; SameSite=Lax; Max-Age=${maxAgeS}`;
|
|
149
163
|
function requireRunnerRequest(req) {
|
|
@@ -176,13 +190,13 @@ export const createLocalHost = (options) => {
|
|
|
176
190
|
sendJson(res, 200, { data: { signedOut: true } });
|
|
177
191
|
return;
|
|
178
192
|
}
|
|
179
|
-
// login / register: the
|
|
180
|
-
//
|
|
181
|
-
await readJsonObject(req);
|
|
193
|
+
// login / register: the password is not checked. The e-mail picks who
|
|
194
|
+
// signs in (see principalNamed), so access rules can be tried as a member.
|
|
195
|
+
const credentials = await readJsonObject(req);
|
|
182
196
|
if (!auth || auth.topology !== 'app' || !auth.methods.includes('password')) {
|
|
183
197
|
throw new HostError(404, 'NO_PASSWORD_DOOR', 'This app declares no password sign-in.');
|
|
184
198
|
}
|
|
185
|
-
sendJson(res, action === 'register' ? 201 : 200, { data: startSession() });
|
|
199
|
+
sendJson(res, action === 'register' ? 201 : 200, { data: startSession(principalNamed(credentials.email)) });
|
|
186
200
|
}
|
|
187
201
|
function gateway(req, res, url, parts) {
|
|
188
202
|
const [action, method] = parts;
|