@pwfabric/cli 1.0.0-rc.2 → 1.1.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 +3 -2
- package/dist/commands/dev.js.map +1 -1
- package/dist/commands/lib/report.d.ts +15 -1
- package/dist/commands/lib/report.js +95 -3
- package/dist/commands/lib/report.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.js +24 -10
- package/dist/dev/server.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/local-host.d.ts +3 -2
- package/dist/host/local-host.js +17 -9
- package/dist/host/local-host.js.map +1 -1
- package/dist/host/records.d.ts +37 -22
- package/dist/host/records.js +99 -64
- package/dist/host/records.js.map +1 -1
- package/package.json +8 -8
package/README.md
CHANGED
|
@@ -94,8 +94,10 @@ endpoints of the data protocol, with records in memory seeded from
|
|
|
94
94
|
its receipts — entity sources rewritten to `rest` sources against
|
|
95
95
|
`/_host/records/<Entity>` — replace the folder's copies. `--local-host` mounts
|
|
96
96
|
it for an app that declares neither; `--no-host` serves the pages alone. The
|
|
97
|
-
local host is for development only:
|
|
98
|
-
a restart.
|
|
97
|
+
local host is for development only: no password is checked, nothing survives
|
|
98
|
+
a restart. It enforces the app's access rules (`auth.json` `access`): the
|
|
99
|
+
development e-mail `dev@localhost` signs in with every declared role, any
|
|
100
|
+
other e-mail as a plain member, so each visitor can be tried.
|
|
99
101
|
|
|
100
102
|
### `pwf build [dir] [--out <dir>]`
|
|
101
103
|
|
package/dist/commands/dev.js
CHANGED
|
@@ -100,8 +100,9 @@ export const devCommand = {
|
|
|
100
100
|
--no-host do not mount the local host, even when the app declares sign-in or records
|
|
101
101
|
|
|
102
102
|
The local host (under ${HOST_PREFIX}) is for development only: records live in
|
|
103
|
-
memory and are seeded from app/data/,
|
|
104
|
-
|
|
103
|
+
memory and are seeded from app/content/ then app/data/, no password is checked, and nothing
|
|
104
|
+
survives a restart. The access rules of auth.json apply: dev@localhost signs in with every
|
|
105
|
+
declared role, any other e-mail as a plain member.`,
|
|
105
106
|
run: (args, io) => runDev(args, io),
|
|
106
107
|
};
|
|
107
108
|
//# sourceMappingURL=dev.js.map
|
package/dist/commands/dev.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dev.js","sourceRoot":"","sources":["../../src/commands/dev.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AACnC,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,YAAY,EAAE,WAAW,EAA2B,MAAM,kBAAkB,CAAA;AACxH,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAA;AAGvD,mFAAmF;AACnF,MAAM,UAAU,gBAAgB;IAC9B,OAAO,IAAI,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;QAC1B,MAAM,IAAI,GAAG,GAAS,EAAE;YACtB,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAA;YAC3B,OAAO,CAAC,GAAG,CAAC,SAAS,EAAE,IAAI,CAAC,CAAA;YAC5B,IAAI,EAAE,CAAA;QACR,CAAC,CAAA;QACD,OAAO,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAA;QAC5B,OAAO,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAA;IAC/B,CAAC,CAAC,CAAA;AACJ,CAAC;AASD,MAAM,CAAC,KAAK,UAAU,MAAM,CAAC,IAAgB,EAAE,EAAa,EAAE,UAA6B,EAAE;IAC3F,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAA;IACnC,IAAI,IAAI,GAAG,YAAY,CAAA;IACvB,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C,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC;CACpC,CAAA","sourcesContent":["/**\n * `pwf dev [dir] [--port <n>] [--host <name>] [--local-host | --no-host]` —\n * serves the app locally, rebuilds on every change and reloads the page. Runs\n * until interrupted.\n *\n * This is where the dev server and the local host meet (ARCHITECTURE.md:\n * `dev/` knows the host's interface only). The host is mounted under\n * `/_host` when the app declares sign-in or records, or when `--local-host`\n * asks for it; `--no-host` serves the pages alone.\n */\nimport { resolve } from 'node:path'\nimport { createDevServer, DEFAULT_HOSTNAME, DEFAULT_PORT, HOST_PREFIX, type DevServerInternals } from '../dev/server.js'\nimport { createLocalHost } from '../host/local-host.js'\nimport type { Command, CommandIO, ParsedArgs } from './types.js'\n\n/** Resolves when the process is asked to stop (Ctrl+C or a termination signal). */\nexport function untilInterrupted(): Promise<void> {\n return new Promise((done) => {\n const stop = (): void => {\n process.off('SIGINT', stop)\n process.off('SIGTERM', stop)\n done()\n }\n process.once('SIGINT', stop)\n process.once('SIGTERM', stop)\n })\n}\n\nexport interface DevCommandOptions {\n /** What keeps the server running; default {@link untilInterrupted}. */\n readonly until?: () => Promise<void>\n /** Passed through to the server (tests turn watching off). */\n readonly internals?: DevServerInternals\n}\n\nexport async function runDev(args: ParsedArgs, io: CommandIO, options: DevCommandOptions = {}): Promise<number> {\n const portFlag = args.flags['port']\n let port = DEFAULT_PORT\n if (portFlag !== undefined) {\n const n = typeof portFlag === 'string' ? Number(portFlag) : NaN\n if (!Number.isInteger(n) || n < 0 || n > 65535) {\n io.err('pwf dev: --port needs a number from 0 to 65535')\n return 2\n }\n port = n\n }\n const hostFlag = args.flags['host']\n if (hostFlag === true || hostFlag === '') {\n io.err('pwf dev: --host needs an interface name or address')\n return 2\n }\n const hostname = typeof hostFlag === 'string' ? hostFlag : DEFAULT_HOSTNAME\n\n // A switch followed by the folder (`pwf dev --no-host ./app`) is read by the\n // argument parser as the switch's value; take it back as the folder.\n let dirArg = args.positionals[0]\n const extra: string[] = []\n const switchOn = (name: string): boolean => {\n const v = args.flags[name]\n if (v === undefined || v === false || v === 'false') return false\n if (typeof v === 'string' && v !== 'true') {\n if (dirArg === undefined) dirArg = v\n else extra.push(v)\n }\n return true\n }\n const forceHost = switchOn('local-host')\n const noHost = switchOn('no-host')\n if (extra.length > 0) {\n io.err(`pwf dev: unexpected argument ${extra.map((e) => `\"${e}\"`).join(', ')}; pwf dev serves one folder`)\n return 2\n }\n if (forceHost && noHost) {\n io.err('pwf dev: --local-host and --no-host contradict each other; pass one')\n return 2\n }\n const root = resolve(io.cwd, dirArg ?? '.')\n\n // Undefined lets the server decide from the app's declarations.\n const localHost = noHost ? false : forceHost ? true : undefined\n const internals: DevServerInternals = { createHost: createLocalHost, ...options.internals }\n\n let server\n try {\n server = await createDevServer(\n { root, port, hostname, log: io.out, ...(localHost !== undefined ? { localHost } : {}) },\n internals\n )\n } catch (e) {\n const err = e as NodeJS.ErrnoException\n io.err(\n err.code === 'EADDRINUSE'\n ? `pwf dev: port ${port} is in use; pass --port <n> (or --port 0 for any free port)`\n : `pwf dev: ${err.message}`\n )\n return 1\n }\n io.out(`pwf dev: serving ${root} at ${server.url}`)\n io.out('press Ctrl+C to stop')\n await (options.until ?? untilInterrupted)()\n await server.close()\n io.out('pwf dev: stopped')\n return 0\n}\n\nexport const devCommand: Command = {\n name: 'dev',\n summary: 'Serve the app locally and reload it on every change',\n usage: `pwf dev [dir] [--port <n>] [--host <name>] [--local-host | --no-host]\n\n dir the app folder (default: the current folder)\n --port <n> port to listen on (default ${DEFAULT_PORT}; 0 picks a free one)\n --host <name> interface to bind (default ${DEFAULT_HOSTNAME})\n --local-host mount the local host for sign-in and data even when the app declares neither\n --no-host do not mount the local host, even when the app declares sign-in or records\n\nThe local host (under ${HOST_PREFIX}) is for development only: records live in\nmemory and are seeded from app/content/ then app/data/, no password is checked, and nothing\nsurvives a restart. The access rules of auth.json apply: dev@localhost signs in with every\ndeclared role, any other e-mail as a plain member.`,\n run: (args, io) => runDev(args, io),\n}\n"]}
|
|
@@ -7,7 +7,21 @@ import type { CommandIO } from '../types.js';
|
|
|
7
7
|
* (`PIN_HASH_MISMATCH`).
|
|
8
8
|
*/
|
|
9
9
|
export declare function checkPins(root: string, identity: PackValidation['identity']): Promise<PackIssue[]>;
|
|
10
|
-
/**
|
|
10
|
+
/**
|
|
11
|
+
* Reads every `app/data/<typeId>.json(l)` seed file with the same reader
|
|
12
|
+
* `pwf dev` uses, so a file the dev host would reject is an error here
|
|
13
|
+
* (`SEED_INVALID`) instead of a 500 on the first record request.
|
|
14
|
+
*/
|
|
15
|
+
export declare function checkSeeds(root: string): PackIssue[];
|
|
16
|
+
/**
|
|
17
|
+
* `app/definitions/entities.json` as `pwf dev` reads it: an entry without a
|
|
18
|
+
* `typeId`, or a field without a `name`, is dropped there without a word, and the
|
|
19
|
+
* page that writes to it fails in the browser with "Entity type … is not
|
|
20
|
+
* registered". Here each is an error (`ENTITY_INVALID`), and so is a page that
|
|
21
|
+
* binds an entity type the file does not declare (`ENTITY_UNDECLARED`).
|
|
22
|
+
*/
|
|
23
|
+
export declare function checkEntities(root: string): PackIssue[];
|
|
24
|
+
/** `validatePack` plus {@link checkPins}, {@link checkSeeds} and {@link checkEntities}, as one result. */
|
|
11
25
|
export declare function validateProject(root: string, pack: PackFolder): Promise<PackValidation>;
|
|
12
26
|
/** Prints issues grouped by severity, errors first. Prints nothing for an empty list. */
|
|
13
27
|
export declare function printIssues(io: CommandIO, issues: readonly PackIssue[]): void;
|
|
@@ -2,10 +2,12 @@
|
|
|
2
2
|
* Validation as the commands report it: the pack library's findings plus
|
|
3
3
|
* the project's pins checked against its local cache.
|
|
4
4
|
*/
|
|
5
|
-
import { existsSync } from 'node:fs';
|
|
5
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
6
|
+
import { join } from 'node:path';
|
|
6
7
|
import { hashPack, validatePack } from '@pwfabric/pack';
|
|
7
8
|
import { cacheDir, cacheRelDir, readCachedPack } from './project.js';
|
|
8
9
|
import { pinsOf } from './identity.js';
|
|
10
|
+
import { readEntities, readReceipt, readSeed, surfaceKeys } from '../../host/definitions.js';
|
|
9
11
|
/**
|
|
10
12
|
* Checks every `packs[]` pin against `.pwf/packs/<id>@<version>/`.
|
|
11
13
|
* A build that is not cached is a warning (`PIN_NOT_CACHED`: `pwf add` it);
|
|
@@ -45,11 +47,101 @@ export async function checkPins(root, identity) {
|
|
|
45
47
|
}
|
|
46
48
|
return issues;
|
|
47
49
|
}
|
|
48
|
-
/**
|
|
50
|
+
/**
|
|
51
|
+
* Reads every `app/data/<typeId>.json(l)` seed file with the same reader
|
|
52
|
+
* `pwf dev` uses, so a file the dev host would reject is an error here
|
|
53
|
+
* (`SEED_INVALID`) instead of a 500 on the first record request.
|
|
54
|
+
*/
|
|
55
|
+
export function checkSeeds(root) {
|
|
56
|
+
const dir = join(root, 'app', 'data');
|
|
57
|
+
if (!existsSync(dir))
|
|
58
|
+
return [];
|
|
59
|
+
const issues = [];
|
|
60
|
+
const typeIds = new Set(readdirSync(dir)
|
|
61
|
+
.filter((f) => f.endsWith('.json') || f.endsWith('.jsonl'))
|
|
62
|
+
.map((f) => f.replace(/\.jsonl?$/, '')));
|
|
63
|
+
for (const typeId of typeIds) {
|
|
64
|
+
try {
|
|
65
|
+
readSeed(root, typeId);
|
|
66
|
+
}
|
|
67
|
+
catch (e) {
|
|
68
|
+
issues.push({ severity: 'error', code: 'SEED_INVALID', path: `app/data/${typeId}`, message: e.message });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return issues;
|
|
72
|
+
}
|
|
73
|
+
const ENTITIES_SHAPE = '{ "entities": [ { "typeId": "…", "fields": [ { "name": "…", "type": "text", "required": true } ] } ] }';
|
|
74
|
+
/**
|
|
75
|
+
* `app/definitions/entities.json` as `pwf dev` reads it: an entry without a
|
|
76
|
+
* `typeId`, or a field without a `name`, is dropped there without a word, and the
|
|
77
|
+
* page that writes to it fails in the browser with "Entity type … is not
|
|
78
|
+
* registered". Here each is an error (`ENTITY_INVALID`), and so is a page that
|
|
79
|
+
* binds an entity type the file does not declare (`ENTITY_UNDECLARED`).
|
|
80
|
+
*/
|
|
81
|
+
export function checkEntities(root) {
|
|
82
|
+
const issues = [];
|
|
83
|
+
const path = 'app/definitions/entities.json';
|
|
84
|
+
const file = join(root, path);
|
|
85
|
+
if (existsSync(file)) {
|
|
86
|
+
let raw;
|
|
87
|
+
try {
|
|
88
|
+
raw = JSON.parse(readFileSync(file, 'utf8'));
|
|
89
|
+
}
|
|
90
|
+
catch (e) {
|
|
91
|
+
return [{ severity: 'error', code: 'ENTITY_INVALID', path, message: `not valid JSON: ${e.message}` }];
|
|
92
|
+
}
|
|
93
|
+
const list = raw && typeof raw === 'object' && Array.isArray(raw.entities)
|
|
94
|
+
? (raw.entities)
|
|
95
|
+
: null;
|
|
96
|
+
if (!list)
|
|
97
|
+
issues.push({ severity: 'error', code: 'ENTITY_INVALID', path, message: `must be ${ENTITIES_SHAPE}` });
|
|
98
|
+
for (const [i, e] of (list ?? []).entries()) {
|
|
99
|
+
const entry = (e && typeof e === 'object' ? e : {});
|
|
100
|
+
if (typeof entry.typeId !== 'string' || !entry.typeId) {
|
|
101
|
+
issues.push({ severity: 'error', code: 'ENTITY_INVALID', path, message: `entities[${i}] has no "typeId" (it has: ${Object.keys(entry).join(', ') || 'nothing'}); expected ${ENTITIES_SHAPE}` });
|
|
102
|
+
}
|
|
103
|
+
for (const [j, f] of (Array.isArray(entry.fields) ? entry.fields : []).entries()) {
|
|
104
|
+
const field = (f && typeof f === 'object' ? f : {});
|
|
105
|
+
if (typeof field.name !== 'string' || !field.name) {
|
|
106
|
+
issues.push({ severity: 'error', code: 'ENTITY_INVALID', path, message: `entities[${i}].fields[${j}] has no "name" (it has: ${Object.keys(field).join(', ') || 'nothing'})` });
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
const declared = new Set(readEntities(root).map((e) => e.typeId));
|
|
112
|
+
for (const key of surfaceKeys(root)) {
|
|
113
|
+
const used = new Set();
|
|
114
|
+
const walk = (v) => {
|
|
115
|
+
if (Array.isArray(v))
|
|
116
|
+
return v.forEach(walk);
|
|
117
|
+
if (!v || typeof v !== 'object')
|
|
118
|
+
return;
|
|
119
|
+
for (const [k, x] of Object.entries(v)) {
|
|
120
|
+
if (k === 'entityType' && typeof x === 'string' && x)
|
|
121
|
+
used.add(x);
|
|
122
|
+
else
|
|
123
|
+
walk(x);
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
try {
|
|
127
|
+
walk(readReceipt(root, key));
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
for (const type of used) {
|
|
133
|
+
if (!declared.has(type)) {
|
|
134
|
+
issues.push({ severity: 'error', code: 'ENTITY_UNDECLARED', path: `app/surfaces/${key}.receipt.json`, message: `uses entity type "${type}", which ${path} does not declare` });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return issues;
|
|
139
|
+
}
|
|
140
|
+
/** `validatePack` plus {@link checkPins}, {@link checkSeeds} and {@link checkEntities}, as one result. */
|
|
49
141
|
export async function validateProject(root, pack) {
|
|
50
142
|
const result = validatePack(pack);
|
|
51
143
|
const pinIssues = await checkPins(root, result.identity);
|
|
52
|
-
const issues = [...result.issues, ...pinIssues];
|
|
144
|
+
const issues = [...result.issues, ...pinIssues, ...checkSeeds(root), ...checkEntities(root)];
|
|
53
145
|
return { ...result, issues, ok: !issues.some((i) => i.severity === 'error') };
|
|
54
146
|
}
|
|
55
147
|
const SEVERITIES = ['error', 'warning', 'info'];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"report.js","sourceRoot":"","sources":["../../../src/commands/lib/report.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AACpC,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAwD,MA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AAM,KAAK,GAAG,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;QACtE,KAAK,CAAC,GAAG,QAAQ,CAAC,QAAQ,CAAC,KAAK,KAAK,CAAC,MAAM,IAAI,CAAC,CAAA;QACjD,KAAK,MAAM,KAAK,IAAI,KAAK;YAAE,KAAK,CAAC,KAAK,KAAK,CAAC,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC,CAAA;IAC5G,CAAC;AACH,CAAC;AAED,iDAAiD;AACjD,MAAM,UAAU,SAAS,CAAC,MAA4B;IACpD,MAAM,CAAC,GAAG,CAAC,CAAwB,EAAU,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,KAAK,CAAC,CAAC,CAAC,MAAM,CAAA;IAC7F,MAAM,MAAM,GAAG,CAAC,KAAa,EAAE,IAAY,EAAU,EAAE,CAAC,GAAG,KAAK,IAAI,IAAI,GAAG,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,EAAE,CAAA;IACnG,OAAO,GAAG,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC,KAAK,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,EAAE,SAAS,CAAC,EAAE,CAAA;AAC7E,CAAC","sourcesContent":["/**\n * Validation as the commands report it: the pack library's findings plus\n * the project's pins checked against its local cache.\n */\nimport { existsSync } from 'node:fs'\nimport { hashPack, validatePack, type PackFolder, type PackIssue, type PackValidation } from '@pwfabric/pack'\nimport type { CommandIO } from '../types.js'\nimport { cacheDir, cacheRelDir, readCachedPack } from './project.js'\nimport { pinsOf } from './identity.js'\n\n/**\n * Checks every `packs[]` pin against `.pwf/packs/<id>@<version>/`.\n * A build that is not cached is a warning (`PIN_NOT_CACHED`: `pwf add` it);\n * a cached build whose content hash differs from the pin is an error\n * (`PIN_HASH_MISMATCH`).\n */\nexport async function checkPins(root: string, identity: PackValidation['identity']): Promise<PackIssue[]> {\n const issues: PackIssue[] = []\n for (const pin of pinsOf(identity)) {\n let dir: string\n try {\n dir = cacheDir(root, pin.id, pin.version)\n } catch (e) {\n issues.push({ severity: 'error', code: 'PIN_INVALID', path: 'pwpack.json', message: (e as Error).message })\n continue\n }\n const rel = cacheRelDir(pin.id, pin.version)\n if (!existsSync(dir)) {\n issues.push({\n severity: 'warning',\n code: 'PIN_NOT_CACHED',\n path: rel,\n message: `${pin.id}@${pin.version} is pinned but not in ${rel}; run \\`pwf add <its .pwpack or folder>\\``,\n })\n continue\n }\n const actual = hashPack(await readCachedPack(dir))\n if (actual !== pin.hash) {\n issues.push({\n severity: 'error',\n code: 'PIN_HASH_MISMATCH',\n path: rel,\n message: `${pin.id}@${pin.version} is pinned at ${pin.hash} but the cached build hashes ${actual}`,\n })\n }\n }\n return issues\n}\n\n/** `validatePack` plus {@link checkPins}, as one result. */\nexport async function validateProject(root: string, pack: PackFolder): Promise<PackValidation> {\n const result = validatePack(pack)\n const pinIssues = await checkPins(root, result.identity)\n const issues = [...result.issues, ...pinIssues]\n return { ...result, issues, ok: !issues.some((i) => i.severity === 'error') }\n}\n\nconst SEVERITIES = ['error', 'warning', 'info'] as const\nconst HEADINGS = { error: 'Errors', warning: 'Warnings', info: 'Notes' } as const\n\n/** Prints issues grouped by severity, errors first. Prints nothing for an empty list. */\nexport function printIssues(io: CommandIO, issues: readonly PackIssue[]): void {\n for (const severity of SEVERITIES) {\n const group = issues.filter((i) => i.severity === severity)\n if (group.length === 0) continue\n const write = severity === 'error' ? io.err.bind(io) : io.out.bind(io)\n write(`${HEADINGS[severity]} (${group.length}):`)\n for (const issue of group) write(` ${issue.code}${issue.path ? ` ${issue.path}` : ''}: ${issue.message}`)\n }\n}\n\n/** `n errors, n warnings` for a summary line. */\nexport function countLine(issues: readonly PackIssue[]): string {\n const n = (s: PackIssue['severity']): number => issues.filter((i) => i.severity === s).length\n const plural = (count: number, word: string): string => `${count} ${word}${count === 1 ? '' : 's'}`\n return `${plural(n('error'), 'error')}, ${plural(n('warning'), 'warning')}`\n}\n"]}
|
|
1
|
+
{"version":3,"file":"report.js","sourceRoot":"","sources":["../../../src/commands/lib/report.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AAC/D,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAwD,MAAM,gBAAgB,CAAA;AAE7G,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,cAAc,CAAA;AACpE,OAAO,EAAE,MAAM,EAAE,MAAM,eAAe,CAAA;AACtC,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAA;AAE5F;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAAC,IAAY,EAAE,QAAoC;IAChF,MAAM,MAAM,GAAgB,EAAE,CAAA;IAC9B,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC;QACnC,IAAI,GAAW,CAAA;QACf,IAAI,CAAC;YACH,GAAG,GAAG,QAAQ,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,EAAE,GAAG,CAAC,OAAO,CAAC,CAAA;QAC3C,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,MAAM,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,aAAa,EAAE,IAAI,E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G,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC,KAAK,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,EAAE,SAAS,CAAC,EAAE,CAAA;AAC7E,CAAC","sourcesContent":["/**\n * Validation as the commands report it: the pack library's findings plus\n * the project's pins checked against its local cache.\n */\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { hashPack, validatePack, type PackFolder, type PackIssue, type PackValidation } from '@pwfabric/pack'\nimport type { CommandIO } from '../types.js'\nimport { cacheDir, cacheRelDir, readCachedPack } from './project.js'\nimport { pinsOf } from './identity.js'\nimport { readEntities, readReceipt, readSeed, surfaceKeys } from '../../host/definitions.js'\n\n/**\n * Checks every `packs[]` pin against `.pwf/packs/<id>@<version>/`.\n * A build that is not cached is a warning (`PIN_NOT_CACHED`: `pwf add` it);\n * a cached build whose content hash differs from the pin is an error\n * (`PIN_HASH_MISMATCH`).\n */\nexport async function checkPins(root: string, identity: PackValidation['identity']): Promise<PackIssue[]> {\n const issues: PackIssue[] = []\n for (const pin of pinsOf(identity)) {\n let dir: string\n try {\n dir = cacheDir(root, pin.id, pin.version)\n } catch (e) {\n issues.push({ severity: 'error', code: 'PIN_INVALID', path: 'pwpack.json', message: (e as Error).message })\n continue\n }\n const rel = cacheRelDir(pin.id, pin.version)\n if (!existsSync(dir)) {\n issues.push({\n severity: 'warning',\n code: 'PIN_NOT_CACHED',\n path: rel,\n message: `${pin.id}@${pin.version} is pinned but not in ${rel}; run \\`pwf add <its .pwpack or folder>\\``,\n })\n continue\n }\n const actual = hashPack(await readCachedPack(dir))\n if (actual !== pin.hash) {\n issues.push({\n severity: 'error',\n code: 'PIN_HASH_MISMATCH',\n path: rel,\n message: `${pin.id}@${pin.version} is pinned at ${pin.hash} but the cached build hashes ${actual}`,\n })\n }\n }\n return issues\n}\n\n/**\n * Reads every `app/data/<typeId>.json(l)` seed file with the same reader\n * `pwf dev` uses, so a file the dev host would reject is an error here\n * (`SEED_INVALID`) instead of a 500 on the first record request.\n */\nexport function checkSeeds(root: string): PackIssue[] {\n const dir = join(root, 'app', 'data')\n if (!existsSync(dir)) return []\n const issues: PackIssue[] = []\n const typeIds = new Set(\n readdirSync(dir)\n .filter((f) => f.endsWith('.json') || f.endsWith('.jsonl'))\n .map((f) => f.replace(/\\.jsonl?$/, '')),\n )\n for (const typeId of typeIds) {\n try {\n readSeed(root, typeId)\n } catch (e) {\n issues.push({ severity: 'error', code: 'SEED_INVALID', path: `app/data/${typeId}`, message: (e as Error).message })\n }\n }\n return issues\n}\n\nconst ENTITIES_SHAPE = '{ \"entities\": [ { \"typeId\": \"…\", \"fields\": [ { \"name\": \"…\", \"type\": \"text\", \"required\": true } ] } ] }'\n\n/**\n * `app/definitions/entities.json` as `pwf dev` reads it: an entry without a\n * `typeId`, or a field without a `name`, is dropped there without a word, and the\n * page that writes to it fails in the browser with \"Entity type … is not\n * registered\". Here each is an error (`ENTITY_INVALID`), and so is a page that\n * binds an entity type the file does not declare (`ENTITY_UNDECLARED`).\n */\nexport function checkEntities(root: string): PackIssue[] {\n const issues: PackIssue[] = []\n const path = 'app/definitions/entities.json'\n const file = join(root, path)\n if (existsSync(file)) {\n let raw: unknown\n try { raw = JSON.parse(readFileSync(file, 'utf8')) } catch (e) {\n return [{ severity: 'error', code: 'ENTITY_INVALID', path, message: `not valid JSON: ${(e as Error).message}` }]\n }\n const list = raw && typeof raw === 'object' && Array.isArray((raw as { entities?: unknown }).entities)\n ? ((raw as { entities: unknown[] }).entities)\n : null\n if (!list) issues.push({ severity: 'error', code: 'ENTITY_INVALID', path, message: `must be ${ENTITIES_SHAPE}` })\n for (const [i, e] of (list ?? []).entries()) {\n const entry = (e && typeof e === 'object' ? e : {}) as Record<string, unknown>\n if (typeof entry.typeId !== 'string' || !entry.typeId) {\n issues.push({ severity: 'error', code: 'ENTITY_INVALID', path, message: `entities[${i}] has no \"typeId\" (it has: ${Object.keys(entry).join(', ') || 'nothing'}); expected ${ENTITIES_SHAPE}` })\n }\n for (const [j, f] of (Array.isArray(entry.fields) ? entry.fields : []).entries()) {\n const field = (f && typeof f === 'object' ? f : {}) as Record<string, unknown>\n if (typeof field.name !== 'string' || !field.name) {\n issues.push({ severity: 'error', code: 'ENTITY_INVALID', path, message: `entities[${i}].fields[${j}] has no \"name\" (it has: ${Object.keys(field).join(', ') || 'nothing'})` })\n }\n }\n }\n }\n const declared = new Set(readEntities(root).map((e) => e.typeId))\n for (const key of surfaceKeys(root)) {\n const used = new Set<string>()\n const walk = (v: unknown): void => {\n if (Array.isArray(v)) return v.forEach(walk)\n if (!v || typeof v !== 'object') return\n for (const [k, x] of Object.entries(v)) {\n if (k === 'entityType' && typeof x === 'string' && x) used.add(x)\n else walk(x)\n }\n }\n try { walk(readReceipt(root, key)) } catch { continue }\n for (const type of used) {\n if (!declared.has(type)) {\n issues.push({ severity: 'error', code: 'ENTITY_UNDECLARED', path: `app/surfaces/${key}.receipt.json`, message: `uses entity type \"${type}\", which ${path} does not declare` })\n }\n }\n }\n return issues\n}\n\n/** `validatePack` plus {@link checkPins}, {@link checkSeeds} and {@link checkEntities}, as one result. */\nexport async function validateProject(root: string, pack: PackFolder): Promise<PackValidation> {\n const result = validatePack(pack)\n const pinIssues = await checkPins(root, result.identity)\n const issues = [...result.issues, ...pinIssues, ...checkSeeds(root), ...checkEntities(root)]\n return { ...result, issues, ok: !issues.some((i) => i.severity === 'error') }\n}\n\nconst SEVERITIES = ['error', 'warning', 'info'] as const\nconst HEADINGS = { error: 'Errors', warning: 'Warnings', info: 'Notes' } as const\n\n/** Prints issues grouped by severity, errors first. Prints nothing for an empty list. */\nexport function printIssues(io: CommandIO, issues: readonly PackIssue[]): void {\n for (const severity of SEVERITIES) {\n const group = issues.filter((i) => i.severity === severity)\n if (group.length === 0) continue\n const write = severity === 'error' ? io.err.bind(io) : io.out.bind(io)\n write(`${HEADINGS[severity]} (${group.length}):`)\n for (const issue of group) write(` ${issue.code}${issue.path ? ` ${issue.path}` : ''}: ${issue.message}`)\n }\n}\n\n/** `n errors, n warnings` for a summary line. */\nexport function countLine(issues: readonly PackIssue[]): string {\n const n = (s: PackIssue['severity']): number => issues.filter((i) => i.severity === s).length\n const plural = (count: number, word: string): string => `${count} ${word}${count === 1 ? '' : 's'}`\n return `${plural(n('error'), 'error')}, ${plural(n('warning'), 'warning')}`\n}\n"]}
|
package/dist/dev/envelope.d.ts
CHANGED
|
@@ -25,7 +25,10 @@ export declare function deriveNavigation(pages: readonly Page[], entry: string):
|
|
|
25
25
|
}[];
|
|
26
26
|
};
|
|
27
27
|
};
|
|
28
|
-
/**
|
|
28
|
+
/**
|
|
29
|
+
* What the app declares about who may enter (`app/definitions/auth.json`), as `project.json` carries it.
|
|
30
|
+
* A file that says nothing about entry (only `access`) is no identity: the app has no door and no wall.
|
|
31
|
+
*/
|
|
29
32
|
export declare function identityOf(auth: unknown): {
|
|
30
33
|
required: boolean;
|
|
31
34
|
topology: 'app' | 'external';
|
package/dist/dev/envelope.js
CHANGED
|
@@ -29,12 +29,17 @@ export function deriveNavigation(pages, entry) {
|
|
|
29
29
|
navbar: { links: pages.map((p) => ({ label: pageLabel(p), href: p.key === entry ? '/' : `/${p.key}` })) },
|
|
30
30
|
};
|
|
31
31
|
}
|
|
32
|
-
/**
|
|
32
|
+
/**
|
|
33
|
+
* What the app declares about who may enter (`app/definitions/auth.json`), as `project.json` carries it.
|
|
34
|
+
* A file that says nothing about entry (only `access`) is no identity: the app has no door and no wall.
|
|
35
|
+
*/
|
|
33
36
|
export function identityOf(auth) {
|
|
34
37
|
if (!isRecord(auth))
|
|
35
38
|
return undefined;
|
|
36
39
|
const topology = auth['topology'] === 'external' ? 'external' : 'app';
|
|
37
40
|
const methods = Array.isArray(auth['methods']) ? auth['methods'].filter((m) => typeof m === 'string') : [];
|
|
41
|
+
if (topology === 'app' && methods.length === 0 && auth['required'] !== true)
|
|
42
|
+
return undefined;
|
|
38
43
|
return {
|
|
39
44
|
required: auth['required'] === true,
|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MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QACpD,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,EAAE,CAAC;YAC9B,WAAW,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,IAAI,EAAE,oBAAoB,EAAE,OAAO,EAAE,2BAA2B,IAAI,uCAAuC,EAAE,CAAC,CAAA;YACtJ,SAAQ;QACV,CAAC;QACD,MAAM,IAAI,GAAG,UAAU,IAAI,EAAE,CAAA;QAC7B,IAAI,IAAI,KAAK,cAAc,IAAI,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;YAC/C,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAe,CAAC,CAA4B,CAAA;YAC9G,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,GAAG,OAAO,EAAE,GAAG,KAAK,EAAE,CAAC,CAAC,CAAC,CAAA;YACrE,SAAQ;QACV,CAAC;QACD,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;IACpD,CAAC;AACH,CAAC","sourcesContent":["/**\n * The envelope documents a runner reads (`pwpack/project.json`,\n * `navigation.json`, `connections.json`, the two module manifests), built\n * from the app folder's declaration.\n */\nimport type { AssembleDiagnostic } from './diagnostics.js'\nimport { isRecord } from './sources.js'\n\n/** One page of the app: its key, its receipt and what the receipt says. */\nexport interface Page {\n readonly key: string\n /** Path of the receipt in the app folder. */\n readonly path: string\n readonly bytes: Uint8Array\n readonly receipt: Record<string, unknown>\n}\n\n/** The block types a receipt places, walking `blocks` and every `children`. */\nexport function blockTypesOf(receipt: unknown): string[] {\n const types = new Set<string>()\n const walk = (node: unknown): void => {\n if (Array.isArray(node)) {\n node.forEach(walk)\n return\n }\n if (!isRecord(node)) return\n if (typeof node['type'] === 'string' && node['type']) types.add(node['type'])\n if (Array.isArray(node['children'])) node['children'].forEach(walk)\n }\n if (isRecord(receipt)) walk(receipt['blocks'])\n return [...types]\n}\n\n/** The page's display name: the receipt's title, else the key. */\nexport function pageLabel(page: Page): string {\n const title = page.receipt['title']\n return typeof title === 'string' && title.trim() ? title.trim() : page.key\n}\n\n/** Navigation derived from the route table when the app declares none. */\nexport function deriveNavigation(pages: readonly Page[], entry: string): { navbar: { links: { label: string; href: string }[] } } {\n return {\n navbar: { links: pages.map((p) => ({ label: pageLabel(p), href: p.key === entry ? '/' : `/${p.key}` })) },\n }\n}\n\n/** What the app declares about who may enter (`app/definitions/auth.json`), as `project.json` carries it. */\nexport function identityOf(auth: unknown): { required: boolean; topology: 'app' | 'external'; methods?: string[] } | undefined {\n if (!isRecord(auth)) return undefined\n const topology = auth['topology'] === 'external' ? 'external' : 'app'\n const methods = Array.isArray(auth['methods']) ? auth['methods'].filter((m): m is string => typeof m === 'string') : []\n return {\n required: auth['required'] === true,\n topology,\n ...(topology === 'app' ? { methods } : {}),\n }\n}\n\nexport interface ProjectJsonInput {\n readonly id: string\n readonly title: string\n readonly entry: string\n readonly pages: readonly Page[]\n readonly auth?: unknown\n}\n\n/** `pwpack/project.json`. */\nexport function buildProjectJson(input: ProjectJsonInput): Record<string, unknown> {\n const surfaceReceiptFiles: Record<string, string> = {}\n for (const p of input.pages) surfaceReceiptFiles[p.key] = `surfaces/${p.key}.receipt.json`\n const identity = identityOf(input.auth)\n return {\n schemaVersion: '1.0.0',\n id: input.id,\n title: input.title,\n entrySurfaceId: input.entry,\n surfaceOrder: input.pages.map((p) => p.key),\n surfaceReceiptFiles,\n ...(identity ? { identity } : {}),\n }\n}\n\n/** Config keys that smell of a credential. Such a key never reaches a published app. */\nexport const CREDENTIAL_KEY_RE =\n /(auth|header|credential|secret|token|password|passwd|apikey|api_key|clientsecret|client_secret|bearer|cookie|signature)/i\n\nfunction stripCredentials(value: unknown, path: string, dropped: string[]): unknown {\n if (Array.isArray(value)) return value.map((v, i) => stripCredentials(v, `${path}[${i}]`, dropped))\n if (!isRecord(value)) return value\n const out: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(value)) {\n if (CREDENTIAL_KEY_RE.test(k)) {\n dropped.push(`${path}.${k}`)\n continue\n }\n out[k] = stripCredentials(v, `${path}.${k}`, dropped)\n }\n return out\n}\n\n/**\n * `pwpack/connections.json`: the declaration with every credential-like\n * config key removed (each removal is reported). A bare string entry is read\n * as `{ name }`.\n */\nexport function buildConnections(\n doc: unknown,\n diagnostics: AssembleDiagnostic[],\n path = 'app/definitions/connections.json'\n): { connections: Record<string, unknown>[] } | undefined {\n if (!isRecord(doc)) return undefined\n const list = Array.isArray(doc['connections']) ? doc['connections'] : []\n const connections: Record<string, unknown>[] = []\n for (const raw of list) {\n const entry = typeof raw === 'string' ? { name: raw } : isRecord(raw) ? raw : null\n if (!entry || typeof entry['name'] !== 'string') {\n diagnostics.push({ severity: 'warning', code: 'CONNECTION_INVALID', message: 'a connection without a name is skipped', path })\n continue\n }\n const dropped: string[] = []\n const out: Record<string, unknown> = { ...entry }\n if (entry['config'] !== undefined) out['config'] = stripCredentials(entry['config'], 'config', dropped)\n for (const d of dropped) {\n diagnostics.push({\n severity: 'warning',\n code: 'CREDENTIAL_DROPPED',\n message: `connection \"${entry['name']}\": ${d} looks like a credential and is not published`,\n path,\n })\n }\n connections.push(out)\n }\n return { connections }\n}\n\n/** One entry of `blocks/manifest.json`. */\nexport interface BlockManifestEntry {\n readonly blockType: string\n readonly moduleUrl: string\n readonly integrity: string\n readonly publisher: string\n readonly publisherVerified: boolean\n readonly definition: { readonly name: string }\n}\n\n/** One entry of `engines/manifest.json`. */\nexport interface EngineManifestEntry {\n readonly connection: string\n readonly atomId: string\n readonly kind: 'connector' | 'provider'\n readonly moduleUrl?: string\n readonly integrity?: string\n readonly engine?: unknown\n}\n\n/** A file name for a module: `<name>.<first 8 hex of its hash>.mjs`, with anything unsafe replaced. */\nexport function moduleFileName(name: string, hexHash: string): string {\n const safe = name.replace(/[^A-Za-z0-9._-]+/g, '_').replace(/^\\.+/, '_') || 'module'\n return `${safe}.${hexHash.slice(0, 8)}.mjs`\n}\n\n/** The publisher an atom is attributed to: the pack id's publisher segment, or the id itself. */\nexport function publisherOf(packId: string): string {\n const m = /^@pwpack\\/([^/]+)\\//.exec(packId)\n return m?.[1] ?? packId\n}\n\n/**\n * Whether a local host may write `name` into the envelope: a relative path of\n * `/`-separated segments ending in `.json` (`auth.json`,\n * `surfaces/home.receipt.json`), each segment starting with a letter, digit,\n * `_` or `-` — so no `.`/`..` segment, no hidden file, no absolute path.\n */\nexport function isEnvelopeFileName(name: string): boolean {\n return /^(?:[A-Za-z0-9_-][A-Za-z0-9_.-]*\\/)*[A-Za-z0-9_-][A-Za-z0-9_.-]*\\.json$/.test(name)\n}\n\n/**\n * Merges what a local host adds to the envelope. Each key is a file name\n * relative to `pwpack/` (`auth.json`, `surfaces/<key>.receipt.json`) and each\n * value the document; a value for `project.json` is merged into it member by\n * member. Called after the static envelope is laid out, so what the host\n * offers WINS: its receipts (entity sources rewritten to its record\n * endpoints) replace the folder's copies.\n */\nexport function mergeEnvelopeEntries(\n files: Map<string, Uint8Array>,\n entries: Readonly<Record<string, unknown>> | undefined,\n diagnostics: AssembleDiagnostic[]\n): void {\n if (!entries) return\n const enc = new TextEncoder()\n for (const [name, value] of Object.entries(entries)) {\n if (!isEnvelopeFileName(name)) {\n diagnostics.push({ severity: 'warning', code: 'HOST_ENTRY_IGNORED', message: `the local host offered \"${name}\", which is not an envelope file name` })\n continue\n }\n const path = `pwpack/${name}`\n if (name === 'project.json' && isRecord(value)) {\n const current = JSON.parse(new TextDecoder().decode(files.get(path) as Uint8Array)) as Record<string, unknown>\n files.set(path, enc.encode(JSON.stringify({ ...current, ...value })))\n continue\n }\n files.set(path, enc.encode(JSON.stringify(value)))\n }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IAAI,WAAW,EAAE,CAAA;IAC7B,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QACpD,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,EAAE,CAAC;YAC9B,WAAW,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,IAAI,EAAE,oBAAoB,EAAE,OAAO,EAAE,2BAA2B,IAAI,uCAAuC,EAAE,CAAC,CAAA;YACtJ,SAAQ;QACV,CAAC;QACD,MAAM,IAAI,GAAG,UAAU,IAAI,EAAE,CAAA;QAC7B,IAAI,IAAI,KAAK,cAAc,IAAI,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;YAC/C,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAe,CAAC,CAA4B,CAAA;YAC9G,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,GAAG,OAAO,EAAE,GAAG,KAAK,EAAE,CAAC,CAAC,CAAC,CAAA;YACrE,SAAQ;QACV,CAAC;QACD,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;IACpD,CAAC;AACH,CAAC","sourcesContent":["/**\n * The envelope documents a runner reads (`pwpack/project.json`,\n * `navigation.json`, `connections.json`, the two module manifests), built\n * from the app folder's declaration.\n */\nimport type { AssembleDiagnostic } from './diagnostics.js'\nimport { isRecord } from './sources.js'\n\n/** One page of the app: its key, its receipt and what the receipt says. */\nexport interface Page {\n readonly key: string\n /** Path of the receipt in the app folder. */\n readonly path: string\n readonly bytes: Uint8Array\n readonly receipt: Record<string, unknown>\n}\n\n/** The block types a receipt places, walking `blocks` and every `children`. */\nexport function blockTypesOf(receipt: unknown): string[] {\n const types = new Set<string>()\n const walk = (node: unknown): void => {\n if (Array.isArray(node)) {\n node.forEach(walk)\n return\n }\n if (!isRecord(node)) return\n if (typeof node['type'] === 'string' && node['type']) types.add(node['type'])\n if (Array.isArray(node['children'])) node['children'].forEach(walk)\n }\n if (isRecord(receipt)) walk(receipt['blocks'])\n return [...types]\n}\n\n/** The page's display name: the receipt's title, else the key. */\nexport function pageLabel(page: Page): string {\n const title = page.receipt['title']\n return typeof title === 'string' && title.trim() ? title.trim() : page.key\n}\n\n/** Navigation derived from the route table when the app declares none. */\nexport function deriveNavigation(pages: readonly Page[], entry: string): { navbar: { links: { label: string; href: string }[] } } {\n return {\n navbar: { links: pages.map((p) => ({ label: pageLabel(p), href: p.key === entry ? '/' : `/${p.key}` })) },\n }\n}\n\n/**\n * What the app declares about who may enter (`app/definitions/auth.json`), as `project.json` carries it.\n * A file that says nothing about entry (only `access`) is no identity: the app has no door and no wall.\n */\nexport function identityOf(auth: unknown): { required: boolean; topology: 'app' | 'external'; methods?: string[] } | undefined {\n if (!isRecord(auth)) return undefined\n const topology = auth['topology'] === 'external' ? 'external' : 'app'\n const methods = Array.isArray(auth['methods']) ? auth['methods'].filter((m): m is string => typeof m === 'string') : []\n if (topology === 'app' && methods.length === 0 && auth['required'] !== true) return undefined\n return {\n required: auth['required'] === true,\n topology,\n ...(topology === 'app' ? { methods } : {}),\n }\n}\n\nexport interface ProjectJsonInput {\n readonly id: string\n readonly title: string\n readonly entry: string\n readonly pages: readonly Page[]\n readonly auth?: unknown\n}\n\n/** `pwpack/project.json`. */\nexport function buildProjectJson(input: ProjectJsonInput): Record<string, unknown> {\n const surfaceReceiptFiles: Record<string, string> = {}\n for (const p of input.pages) surfaceReceiptFiles[p.key] = `surfaces/${p.key}.receipt.json`\n const identity = identityOf(input.auth)\n return {\n schemaVersion: '1.0.0',\n id: input.id,\n title: input.title,\n entrySurfaceId: input.entry,\n surfaceOrder: input.pages.map((p) => p.key),\n surfaceReceiptFiles,\n ...(identity ? { identity } : {}),\n }\n}\n\n/** Config keys that smell of a credential. Such a key never reaches a published app. */\nexport const CREDENTIAL_KEY_RE =\n /(auth|header|credential|secret|token|password|passwd|apikey|api_key|clientsecret|client_secret|bearer|cookie|signature)/i\n\nfunction stripCredentials(value: unknown, path: string, dropped: string[]): unknown {\n if (Array.isArray(value)) return value.map((v, i) => stripCredentials(v, `${path}[${i}]`, dropped))\n if (!isRecord(value)) return value\n const out: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(value)) {\n if (CREDENTIAL_KEY_RE.test(k)) {\n dropped.push(`${path}.${k}`)\n continue\n }\n out[k] = stripCredentials(v, `${path}.${k}`, dropped)\n }\n return out\n}\n\n/**\n * `pwpack/connections.json`: the declaration with every credential-like\n * config key removed (each removal is reported). A bare string entry is read\n * as `{ name }`.\n */\nexport function buildConnections(\n doc: unknown,\n diagnostics: AssembleDiagnostic[],\n path = 'app/definitions/connections.json'\n): { connections: Record<string, unknown>[] } | undefined {\n if (!isRecord(doc)) return undefined\n const list = Array.isArray(doc['connections']) ? doc['connections'] : []\n const connections: Record<string, unknown>[] = []\n for (const raw of list) {\n const entry = typeof raw === 'string' ? { name: raw } : isRecord(raw) ? raw : null\n if (!entry || typeof entry['name'] !== 'string') {\n diagnostics.push({ severity: 'warning', code: 'CONNECTION_INVALID', message: 'a connection without a name is skipped', path })\n continue\n }\n const dropped: string[] = []\n const out: Record<string, unknown> = { ...entry }\n if (entry['config'] !== undefined) out['config'] = stripCredentials(entry['config'], 'config', dropped)\n for (const d of dropped) {\n diagnostics.push({\n severity: 'warning',\n code: 'CREDENTIAL_DROPPED',\n message: `connection \"${entry['name']}\": ${d} looks like a credential and is not published`,\n path,\n })\n }\n connections.push(out)\n }\n return { connections }\n}\n\n/** One entry of `blocks/manifest.json`. */\nexport interface BlockManifestEntry {\n readonly blockType: string\n readonly moduleUrl: string\n readonly integrity: string\n readonly publisher: string\n readonly publisherVerified: boolean\n readonly definition: { readonly name: string }\n}\n\n/** One entry of `engines/manifest.json`. */\nexport interface EngineManifestEntry {\n readonly connection: string\n readonly atomId: string\n readonly kind: 'connector' | 'provider'\n readonly moduleUrl?: string\n readonly integrity?: string\n readonly engine?: unknown\n}\n\n/** A file name for a module: `<name>.<first 8 hex of its hash>.mjs`, with anything unsafe replaced. */\nexport function moduleFileName(name: string, hexHash: string): string {\n const safe = name.replace(/[^A-Za-z0-9._-]+/g, '_').replace(/^\\.+/, '_') || 'module'\n return `${safe}.${hexHash.slice(0, 8)}.mjs`\n}\n\n/** The publisher an atom is attributed to: the pack id's publisher segment, or the id itself. */\nexport function publisherOf(packId: string): string {\n const m = /^@pwpack\\/([^/]+)\\//.exec(packId)\n return m?.[1] ?? packId\n}\n\n/**\n * Whether a local host may write `name` into the envelope: a relative path of\n * `/`-separated segments ending in `.json` (`auth.json`,\n * `surfaces/home.receipt.json`), each segment starting with a letter, digit,\n * `_` or `-` — so no `.`/`..` segment, no hidden file, no absolute path.\n */\nexport function isEnvelopeFileName(name: string): boolean {\n return /^(?:[A-Za-z0-9_-][A-Za-z0-9_.-]*\\/)*[A-Za-z0-9_-][A-Za-z0-9_.-]*\\.json$/.test(name)\n}\n\n/**\n * Merges what a local host adds to the envelope. Each key is a file name\n * relative to `pwpack/` (`auth.json`, `surfaces/<key>.receipt.json`) and each\n * value the document; a value for `project.json` is merged into it member by\n * member. Called after the static envelope is laid out, so what the host\n * offers WINS: its receipts (entity sources rewritten to its record\n * endpoints) replace the folder's copies.\n */\nexport function mergeEnvelopeEntries(\n files: Map<string, Uint8Array>,\n entries: Readonly<Record<string, unknown>> | undefined,\n diagnostics: AssembleDiagnostic[]\n): void {\n if (!entries) return\n const enc = new TextEncoder()\n for (const [name, value] of Object.entries(entries)) {\n if (!isEnvelopeFileName(name)) {\n diagnostics.push({ severity: 'warning', code: 'HOST_ENTRY_IGNORED', message: `the local host offered \"${name}\", which is not an envelope file name` })\n continue\n }\n const path = `pwpack/${name}`\n if (name === 'project.json' && isRecord(value)) {\n const current = JSON.parse(new TextDecoder().decode(files.get(path) as Uint8Array)) as Record<string, unknown>\n files.set(path, enc.encode(JSON.stringify({ ...current, ...value })))\n continue\n }\n files.set(path, enc.encode(JSON.stringify(value)))\n }\n}\n"]}
|
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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A;IACpF,CAAC;IAED,IAAI,MAAM,GAAyB,IAAI,CAAA;IACvC,OAAO;QACL,GAAG;QACH,OAAO;QACP,KAAK;YACH,MAAM,KAAK,CAAC,KAAK,IAAI,EAAE;gBACrB,OAAO,EAAE,KAAK,EAAE,CAAA;gBAChB,KAAK,MAAM,CAAC,IAAI,OAAO;oBAAE,CAAC,CAAC,GAAG,EAAE,CAAA;gBAChC,OAAO,CAAC,KAAK,EAAE,CAAA;gBACf,MAAM,IAAI,OAAO,CAAO,CAAC,EAAE,EAAE,EAAE;oBAC7B,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC,CAAA;oBACxB,MAAM,CAAC,mBAAmB,EAAE,CAAA;gBAC9B,CAAC,CAAC,CAAA;gBACF,MAAM,KAAK,CAAA;YACb,CAAC,CAAC,EAAE,CAAA;YACJ,OAAO,MAAM,CAAA;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,WA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,EAAE;gBACrB,OAAO,EAAE,KAAK,EAAE,CAAA;gBAChB,KAAK,MAAM,CAAC,IAAI,OAAO;oBAAE,CAAC,CAAC,GAAG,EAAE,CAAA;gBAChC,OAAO,CAAC,KAAK,EAAE,CAAA;gBACf,MAAM,IAAI,OAAO,CAAO,CAAC,EAAE,EAAE,EAAE;oBAC7B,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC,CAAA;oBACxB,MAAM,CAAC,mBAAmB,EAAE,CAAA;gBAC9B,CAAC,CAAC,CAAA;gBACF,MAAM,KAAK,CAAA;YACb,CAAC,CAAC,EAAE,CAAA;YACJ,OAAO,MAAM,CAAA;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 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"]}
|