@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 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: one user, any password, nothing survives
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
 
@@ -10,7 +10,7 @@
10
10
  */
11
11
  import { resolve } from 'node:path';
12
12
  import { createDevServer, DEFAULT_HOSTNAME, DEFAULT_PORT, HOST_PREFIX } from '../dev/server.js';
13
- import { createLocalHost } from '../host/local-host.js';
13
+ import { createLocalHost } from '../host/index.js';
14
14
  /** Resolves when the process is asked to stop (Ctrl+C or a termination signal). */
15
15
  export function untilInterrupted() {
16
16
  return new Promise((done) => {
@@ -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/, the one development user signs in
104
- with any password, and nothing survives a restart.`,
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
@@ -1 +1 @@
1
- {"version":3,"file":"dev.js","sourceRoot":"","sources":["../../src/commands/dev.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,OAAO,EAAE,MAA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B,CAAC,EAAE,CAAA;IAC3C,MAAM,MAAM,CAAC,KAAK,EAAE,CAAA;IACpB,EAAE,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAA;IAC1B,OAAO,CAAC,CAAA;AACV,CAAC;AAED,MAAM,CAAC,MAAM,UAAU,GAAY;IACjC,IAAI,EAAE,KAAK;IACX,OAAO,EAAE,qDAAqD;IAC9D,KAAK,EAAE;;;8CAGqC,YAAY;8CACZ,gBAAgB;;;;wBAItC,WAAW;;mDAEgB;IACjD,GAAG,EAAE,CAAC,IAAI,EAAE,EAAE,EAAE,EAAE,CAAC,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/data/, the one development user signs in\nwith any password, and nothing survives a restart.`,\n run: (args, io) => runDev(args, io),\n}\n"]}
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,kBAAkB,CAAA;AAGlD,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,Y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AC,OAAO,CAAC,EAAE,CAAC;QACX,MAAM,GAAG,GAAG,CAA0B,CAAA;QACtC,EAAE,CAAC,GAAG,CACJ,GAAG,CAAC,IAAI,KAAK,YAAY;YACvB,CAAC,CAAC,iBAAiB,IAAI,6DAA6D;YACpF,CAAC,CAAC,YAAY,GAAG,CAAC,OAAO,EAAE,CAC9B,CAAA;QACD,OAAO,CAAC,CAAA;IACV,CAAC;IACD,EAAE,CAAC,GAAG,CAAC,oBAAoB,IAAI,OAAO,MAAM,CAAC,GAAG,EAAE,CAAC,CAAA;IACnD,EAAE,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAA;IAC9B,MAAM,CAAC,OAAO,CAAC,KAAK,IAAI,gBAAgB,CAAC,EAAE,CAAA;IAC3C,MAAM,MAAM,CAAC,KAAK,EAAE,CAAA;IACpB,EAAE,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAA;IAC1B,OAAO,CAAC,CAAA;AACV,CAAC;AAED,MAAM,CAAC,MAAM,UAAU,GAAY;IACjC,IAAI,EAAE,KAAK;IACX,OAAO,EAAE,qDAAqD;IAC9D,KAAK,EAAE;;;8CAGqC,YAAY;8CACZ,gBAAgB;;;;wBAItC,WAAW;;;mDAGgB;IACjD,GAAG,EAAE,CAAC,IAAI,EAAE,EAAE,EAAE,EAAE,CAAC,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/index.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,32 @@ 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
- /** `validatePack` plus {@link checkPins}, as one result. */
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
+ /**
25
+ * Every model the app declares must be named by an `access` rule
26
+ * (`ACCESS_RULE_MISSING`, an error).
27
+ *
28
+ * A host that publishes an app serves only what the rules grant: a model no
29
+ * rule names is closed, and an app with no `access` block serves its pages and
30
+ * no records. `pwf dev` is more forgiving (an app with no rule at all stays
31
+ * open there), so without this check an author would find out only after
32
+ * publishing. Public data needs an explicit `public` rule.
33
+ */
34
+ export declare function checkAccess(root: string): PackIssue[];
35
+ /** `validatePack` plus {@link checkPins}, {@link checkSeeds}, {@link checkEntities} and {@link checkAccess}, as one result. */
11
36
  export declare function validateProject(root: string, pack: PackFolder): Promise<PackValidation>;
12
37
  /** Prints issues grouped by severity, errors first. Prints nothing for an empty list. */
13
38
  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 { readAuth, 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,142 @@ export async function checkPins(root, identity) {
45
47
  }
46
48
  return issues;
47
49
  }
48
- /** `validatePack` plus {@link checkPins}, as one result. */
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
+ const normName = (s) => s.toLowerCase().replace(/[\s_-]/g, '');
141
+ /**
142
+ * Every model the app declares must be named by an `access` rule
143
+ * (`ACCESS_RULE_MISSING`, an error).
144
+ *
145
+ * A host that publishes an app serves only what the rules grant: a model no
146
+ * rule names is closed, and an app with no `access` block serves its pages and
147
+ * no records. `pwf dev` is more forgiving (an app with no rule at all stays
148
+ * open there), so without this check an author would find out only after
149
+ * publishing. Public data needs an explicit `public` rule.
150
+ */
151
+ export function checkAccess(root) {
152
+ const entities = readEntities(root);
153
+ if (entities.length === 0)
154
+ return [];
155
+ const path = 'app/definitions/auth.json';
156
+ let auth;
157
+ try {
158
+ auth = readAuth(root);
159
+ }
160
+ catch {
161
+ return []; // not valid JSON: reported by the pack validation
162
+ }
163
+ const rules = auth?.access.rules ?? [];
164
+ const named = new Set(rules.map((r) => normName(r.model)));
165
+ const issues = [];
166
+ for (const e of entities) {
167
+ if (named.has(normName(e.typeId)) || (e.displayName && named.has(normName(e.displayName))))
168
+ continue;
169
+ const where = rules.length === 0 ? `${path} has no access rules` : `no rule in ${path} access.rules names it`;
170
+ issues.push({
171
+ severity: 'error',
172
+ code: 'ACCESS_RULE_MISSING',
173
+ path,
174
+ message: `model "${e.typeId}" has no access rule (${where}), so a published app serves its records to nobody. ` +
175
+ `Add one to access.rules, e.g. { "subject": "public", "model": "${e.typeId}", "rule": "read" } for public data, ` +
176
+ `or { "subject": "member", "model": "${e.typeId}", "rule": "create, read own" } for each visitor's own records`,
177
+ });
178
+ }
179
+ return issues;
180
+ }
181
+ /** `validatePack` plus {@link checkPins}, {@link checkSeeds}, {@link checkEntities} and {@link checkAccess}, as one result. */
49
182
  export async function validateProject(root, pack) {
50
183
  const result = validatePack(pack);
51
184
  const pinIssues = await checkPins(root, result.identity);
52
- const issues = [...result.issues, ...pinIssues];
185
+ const issues = [...result.issues, ...pinIssues, ...checkSeeds(root), ...checkEntities(root), ...checkAccess(root)];
53
186
  return { ...result, issues, ok: !issues.some((i) => i.severity === 'error') };
54
187
  }
55
188
  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,MAAM,gBAAgB,CAAA;AAE7G,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,cAAc,CAAA;AACpE,OAAO,EAAE,MAAM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AAC,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,QAAQ,EAAE,YAAY,EAAE,WAAW,EAAE,QAAQ,EAAE,WAAW,EAAwB,MAAM,2BAA2B,CAAA;AAE5H;;;;;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,EAAE,aAAa,EAAE,OAAO,EAAG,CAAW,CAAC,OAAO,EAAE,CAAC,CAAA;YAC3G,SAAQ;QACV,CAAC;QACD,MAAM,GAAG,G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G,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, 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 { readAuth, readEntities, readReceipt, readSeed, surfaceKeys, type AuthDeclaration } 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\nconst normName = (s: string): string => s.toLowerCase().replace(/[\\s_-]/g, '')\n\n/**\n * Every model the app declares must be named by an `access` rule\n * (`ACCESS_RULE_MISSING`, an error).\n *\n * A host that publishes an app serves only what the rules grant: a model no\n * rule names is closed, and an app with no `access` block serves its pages and\n * no records. `pwf dev` is more forgiving (an app with no rule at all stays\n * open there), so without this check an author would find out only after\n * publishing. Public data needs an explicit `public` rule.\n */\nexport function checkAccess(root: string): PackIssue[] {\n const entities = readEntities(root)\n if (entities.length === 0) return []\n const path = 'app/definitions/auth.json'\n let auth: AuthDeclaration | undefined\n try {\n auth = readAuth(root)\n } catch {\n return [] // not valid JSON: reported by the pack validation\n }\n const rules = auth?.access.rules ?? []\n const named = new Set(rules.map((r) => normName(r.model)))\n const issues: PackIssue[] = []\n for (const e of entities) {\n if (named.has(normName(e.typeId)) || (e.displayName && named.has(normName(e.displayName)))) continue\n const where = rules.length === 0 ? `${path} has no access rules` : `no rule in ${path} access.rules names it`\n issues.push({\n severity: 'error',\n code: 'ACCESS_RULE_MISSING',\n path,\n message:\n `model \"${e.typeId}\" has no access rule (${where}), so a published app serves its records to nobody. ` +\n `Add one to access.rules, e.g. { \"subject\": \"public\", \"model\": \"${e.typeId}\", \"rule\": \"read\" } for public data, ` +\n `or { \"subject\": \"member\", \"model\": \"${e.typeId}\", \"rule\": \"create, read own\" } for each visitor's own records`,\n })\n }\n return issues\n}\n\n/** `validatePack` plus {@link checkPins}, {@link checkSeeds}, {@link checkEntities} and {@link checkAccess}, 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), ...checkAccess(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/csp.js CHANGED
@@ -135,7 +135,7 @@ function restEndpointsOf(receipt) {
135
135
  }
136
136
  return out;
137
137
  }
138
- const AUTH_ADDRESS_KEYS = ['loginUrl', 'registerUrl', 'logoutUrl', 'sessionUrl', 'tokenUrl', 'issuer', 'startUrl', 'gatewaySessionUrl', 'gatewayLogoutUrl'];
138
+ const AUTH_ADDRESS_KEYS = ['loginUrl', 'registerUrl', 'logoutUrl', 'sessionUrl', 'tokenUrl', 'issuer', 'startUrl', 'gatewaySessionUrl', 'gatewayLogoutUrl', 'apiBase'];
139
139
  /** Writes the directives as a policy string. */
140
140
  export function serializeCsp(directives, options = {}) {
141
141
  return Object.entries(directives)
@@ -1 +1 @@
1
- {"version":3,"file":"csp.js","sourceRoot":"","sources":["../../src/dev/csp.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAA;AA0CvC,2FAA2F;AAC3F,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,CAAC,iBAAiB,EAAE,YAAY,EAAE,WAAW,EAAE,SAAS,CAAC,CAAC,CAAA;AAEtF,kFAAkF;AAClF,MAAM,UAAU,UAAU,CAAC,IAAY;IACrC,OAAO,WAAW,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAA;AACjF,CAAC;AAED,MAAM,QAAQ,GAAG,kEAAkE,CAAA;AAEnF;;;GAGG;AACH,MAAM,UAAU,QAAQ,CAAC,KAAa;IACpC,MAAM,CAAC,GAAG,0BAA0B,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAA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AQ,CAAC;QACzB,YAAY,EAAE,CAAC,QAAQ,EAAE,OAAO,EAAE,UAAU,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;QAClE,WAAW,EAAE,CAAC,QAAQ,EAAE,iBAAiB,EAAE,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;QAC5D,SAAS,EAAE,CAAC,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;QACzD,WAAW,EAAE,CAAC,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;QAC3D,GAAG,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACzD,UAAU,EAAE,CAAC,QAAQ,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;QACvC,aAAa,EAAE,CAAC,QAAQ,EAAE,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;QAC7C,UAAU,EAAE,CAAC,QAAQ,CAAC;QACtB,YAAY,EAAE,CAAC,QAAQ,CAAC;QACxB,iBAAiB,EAAE,CAAC,QAAQ,CAAC;KAC9B,CAAA;IACD,OAAO;QACL,UAAU;QACV,MAAM,EAAE,YAAY,CAAC,UAAU,CAAC;QAChC,IAAI,EAAE,YAAY,CAAC,UAAU,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;QAC9C,UAAU;KACX,CAAA;AACH,CAAC;AAED,6DAA6D;AAC7D,MAAM,UAAU,WAAW,CAAC,MAAc;IACxC,OAAO,kCAAkC,MAAM,IAAI,CAAA;AACrD,CAAC","sourcesContent":["/**\n * The app's Content Security Policy, derived from what the app declares.\n *\n * A pwapp is static files; what it may load and reach is known at build time\n * from its own declarations, so `pwf build` writes a policy that allows that\n * and nothing else (pwapp-format §2.1):\n *\n * default-src 'none'\n * script-src 'self' blob: 'sha256-<import map>'\n * Blocks and compiled engines are verified and then imported\n * from `blob:` URLs. The import map is the shell's only inline\n * script (an import map cannot be an external file), so its\n * hash is listed; the renderer seeding and the boot call are\n * files (`assets/seed.js`, `assets/boot.js`).\n * style-src 'self' 'unsafe-inline' [+ the webfont stylesheet origin]\n * The renderer draws `<style>` elements at run time (the\n * surface base, visibility, state, responsive and dark-theme\n * rules, computed per page), and blocks set `style`\n * attributes. Neither can be hashed ahead of time.\n * img-src 'self' data: blob: [+ media origins]\n * media-src 'self' data: blob: [+ media origins]\n * frame-src [media origins] — only when there are any\n * font-src 'self' [+ the webfont file origin]\n * connect-src 'self' [+ every origin the app's data and sign-in reach]\n * base-uri 'self' — a host that serves the app under a sub-path\n * injects `<base href>` (pwapp-format §2); 'none' would make\n * the browser ignore it and break path routing.\n * object-src 'none'\n * frame-ancestors 'none' — header only: browsers ignore it in a `<meta>`.\n *\n * Origins come from: absolute `rest` endpoints in the receipts; declared\n * engines' `host` templates filled from `connections.json` config;\n * the envelope `auth.json` addresses and an external issuer; `publish.json`\n * media and absolute media URLs in receipt props. A template that cannot be\n * resolved at build time, and a compiled engine (whose code may reach any\n * origin), is listed in `unresolved` instead of being guessed.\n *\n * @module @pwfabric/cli/dev/csp\n */\nimport { createHash } from 'node:crypto'\nimport { isRecord } from './sources.js'\n\n/** Directive name → its sources, in the order they are written. */\nexport type CspDirectives = Record<string, string[]>\n\n/** Something the policy could not resolve at build time. */\nexport interface CspUnresolved {\n /** What declared it: `connection:<name>`, `engine:<atomId>`, `page:<key>`, `auth`. */\n readonly source: string\n /** The template or address as written. */\n readonly value: string\n readonly reason: string\n}\n\nexport interface AppCsp {\n readonly directives: CspDirectives\n /** The policy as a header value (every directive). */\n readonly header: string\n /** The policy for a `<meta http-equiv>` (without the directives a meta cannot carry). */\n readonly meta: string\n readonly unresolved: readonly CspUnresolved[]\n}\n\nexport interface CspInputs {\n /** The exact text of the shell's inline import map. */\n readonly importMapText: string\n /** Served receipts by page key (after media slots are filled). */\n readonly receipts: ReadonlyMap<string, unknown>\n /** `pwpack/connections.json`. */\n readonly connections?: { readonly connections: readonly Record<string, unknown>[] } | undefined\n /** `engines/manifest.json` entries. */\n readonly engines: readonly { readonly connection: string; readonly atomId: string; readonly moduleUrl?: string; readonly engine?: unknown }[]\n /** The envelope `auth.json`, when the build has one. */\n readonly envelopeAuth?: unknown\n /** `app/definitions/auth.json` (the declaration). */\n readonly authDefinition?: unknown\n /** `publish.json` `media[]`. */\n readonly media: readonly { readonly url: string }[]\n /** The webfont stylesheet the shell links, when any. */\n readonly webfontHref?: string | null\n}\n\n/** Directives a `<meta http-equiv=\"Content-Security-Policy\">` cannot carry (CSP3 §3.3). */\nconst HEADER_ONLY = new Set(['frame-ancestors', 'report-uri', 'report-to', 'sandbox'])\n\n/** The CSP source for an inline script: `'sha256-<base64>'` of its exact text. */\nexport function scriptHash(text: string): string {\n return `'sha256-${createHash('sha256').update(text, 'utf8').digest('base64')}'`\n}\n\nconst LOOPBACK = /^(?:localhost|127\\.0\\.0\\.1|\\[::1\\]|[^/:]+\\.localhost)(?::\\d+)?$/i\n\n/**\n * The origin of an absolute http(s) URL, or null. Expressions (`{{…}}`) or\n * templates (`{…}`) in the scheme or host make it unresolvable (`undefined`).\n */\nexport function originOf(value: string): string | null | undefined {\n const m = /^(https?):\\/\\/([^/?#]*)/i.exec(value.trim())\n if (!m) return null\n const host = m[2] as string\n if (!host || /[{}]/.test(host)) return undefined\n try {\n return new URL(`${(m[1] as string).toLowerCase()}://${host}`).origin\n } catch {\n return undefined\n }\n}\n\n/**\n * The origin a declared engine's `host` reaches (connector-manifest §3.1):\n * `{name}` filled from the connection's string config, the scheme dropped and\n * `https://` prepended, except an explicit `http://` on a loopback host.\n * `undefined` when a placeholder stays unfilled.\n */\nexport function engineHostOrigin(host: string, config: Record<string, unknown> | undefined): string | undefined {\n const filled = host.replace(/\\{([A-Za-z0-9_.-]+)\\}/g, (whole, name: string) => {\n const v = config?.[name]\n return typeof v === 'string' ? v : whole\n })\n if (/[{}]/.test(filled)) return undefined\n const explicitHttp = /^http:\\/\\//i.test(filled.trim())\n const bare = filled.trim().replace(/^[a-z][a-z0-9+.-]*:\\/\\//i, '')\n const hostPart = bare.split(/[/?#]/)[0] ?? ''\n if (!hostPart) return undefined\n const scheme = explicitHttp && LOOPBACK.test(hostPart) ? 'http' : 'https'\n try {\n return new URL(`${scheme}://${hostPart}`).origin\n } catch {\n return undefined\n }\n}\n\n/** A prop that names where a link goes (navigation is not governed by CSP). */\nconst LINK_PROP = /^(?:href|to|link|url|.*Href|.*Link)$/\n\n/** Every absolute URL a receipt's block props carry, except links. */\nfunction mediaUrlsOf(blocks: unknown, out: string[]): void {\n if (!Array.isArray(blocks)) return\n for (const block of blocks) {\n if (!isRecord(block)) continue\n const props = block['props']\n if (isRecord(props)) collectUrls(props, out)\n mediaUrlsOf(block['children'], out)\n }\n}\n\nfunction collectUrls(value: Record<string, unknown> | unknown[], out: string[]): void {\n const entries: [string, unknown][] = Array.isArray(value) ? value.map((v, i) => [String(i), v]) : Object.entries(value)\n for (const [key, v] of entries) {\n if (typeof v === 'string') {\n if (!LINK_PROP.test(key) && /^https?:\\/\\//i.test(v.trim())) out.push(v.trim())\n } else if (Array.isArray(v) || isRecord(v)) {\n collectUrls(v, out)\n }\n }\n}\n\n/** `rest` data sources of a receipt's persistence capability. */\nfunction restEndpointsOf(receipt: unknown): string[] {\n if (!isRecord(receipt) || !Array.isArray(receipt['capabilities'])) return []\n const out: string[] = []\n for (const cap of receipt['capabilities']) {\n if (!isRecord(cap) || !isRecord(cap['config'])) continue\n const sources = cap['config']['dataSources']\n if (!Array.isArray(sources)) continue\n for (const s of sources) {\n if (isRecord(s) && s['kind'] === 'rest' && typeof s['endpoint'] === 'string') out.push(s['endpoint'])\n }\n }\n return out\n}\n\nconst AUTH_ADDRESS_KEYS = ['loginUrl', 'registerUrl', 'logoutUrl', 'sessionUrl', 'tokenUrl', 'issuer', 'startUrl', 'gatewaySessionUrl', 'gatewayLogoutUrl']\n\n/** Writes the directives as a policy string. */\nexport function serializeCsp(directives: CspDirectives, options: { meta?: boolean } = {}): string {\n return Object.entries(directives)\n .filter(([name, values]) => values.length > 0 && !(options.meta && HEADER_ONLY.has(name)))\n .map(([name, values]) => `${name} ${values.join(' ')}`)\n .join('; ')\n}\n\n/** Derives the app's policy from what it declares. */\nexport function deriveCsp(input: CspInputs): AppCsp {\n const unresolved: CspUnresolved[] = []\n const connect = new Set<string>()\n const media = new Set<string>()\n const style = new Set<string>()\n const font = new Set<string>()\n\n const addConnect = (value: string, source: string): void => {\n const o = originOf(value)\n if (o === undefined) unresolved.push({ source, value, reason: 'the address is a template or expression; its origin is known only at run time' })\n else if (o) connect.add(o)\n }\n\n // Data: absolute `rest` endpoints in the receipts. Relative ones are 'self'.\n for (const [key, receipt] of input.receipts) {\n for (const endpoint of restEndpointsOf(receipt)) addConnect(endpoint, `page:${key}`)\n const urls: string[] = []\n if (isRecord(receipt)) mediaUrlsOf(receipt['blocks'], urls)\n for (const url of urls) {\n const o = originOf(url)\n if (o) media.add(o)\n else if (o === undefined) unresolved.push({ source: `page:${key}`, value: url, reason: 'a media address with an expression in its origin' })\n }\n }\n\n // Connections: declared engines resolve their host; compiled ones cannot be read.\n const configOf = new Map<string, Record<string, unknown>>()\n for (const c of input.connections?.connections ?? []) {\n if (typeof c['name'] === 'string') configOf.set(c['name'], isRecord(c['config']) ? c['config'] : {})\n }\n for (const e of input.engines) {\n const host = isRecord(e.engine) && typeof e.engine['host'] === 'string' ? e.engine['host'] : undefined\n if (host !== undefined) {\n const o = engineHostOrigin(host, configOf.get(e.connection))\n if (o) connect.add(o)\n else unresolved.push({ source: `connection:${e.connection}`, value: host, reason: 'the engine host names config the connection does not provide' })\n } else if (e.moduleUrl) {\n unresolved.push({\n source: `engine:${e.atomId}`,\n value: e.moduleUrl,\n reason: `compiled engine for connection \"${e.connection}\"; the origins its code reaches are not declared`,\n })\n }\n }\n\n // Sign-in: the envelope's addresses, and an external issuer's.\n if (isRecord(input.envelopeAuth)) {\n for (const k of AUTH_ADDRESS_KEYS) {\n const v = input.envelopeAuth[k]\n if (typeof v === 'string') addConnect(v, 'auth')\n }\n }\n const issuer = isRecord(input.authDefinition) && isRecord(input.authDefinition['issuer']) ? input.authDefinition['issuer'] : undefined\n if (issuer) {\n for (const k of ['issuer', 'tokenUrl']) {\n const v = issuer[k]\n if (typeof v === 'string') addConnect(v, 'auth')\n }\n if (typeof issuer['tokenUrl'] !== 'string' && typeof issuer['issuer'] === 'string') {\n unresolved.push({\n source: 'auth',\n value: issuer['issuer'],\n reason: \"the token endpoint is discovered at run time; the policy allows the issuer's own origin only\",\n })\n }\n }\n\n // Media the app declares.\n for (const m of input.media) {\n const o = originOf(m.url)\n if (o) media.add(o)\n }\n\n // Webfonts: the stylesheet and the files it points at.\n if (input.webfontHref) {\n const o = originOf(input.webfontHref)\n if (o) style.add(o)\n if (o === 'https://fonts.googleapis.com') font.add('https://fonts.gstatic.com')\n }\n\n const sorted = (s: Set<string>): string[] => [...s].sort()\n const directives: CspDirectives = {\n 'default-src': [\"'none'\"],\n 'script-src': [\"'self'\", 'blob:', scriptHash(input.importMapText)],\n 'style-src': [\"'self'\", \"'unsafe-inline'\", ...sorted(style)],\n 'img-src': [\"'self'\", 'data:', 'blob:', ...sorted(media)],\n 'media-src': [\"'self'\", 'data:', 'blob:', ...sorted(media)],\n ...(media.size > 0 ? { 'frame-src': sorted(media) } : {}),\n 'font-src': [\"'self'\", ...sorted(font)],\n 'connect-src': [\"'self'\", ...sorted(connect)],\n 'base-uri': [\"'self'\"],\n 'object-src': [\"'none'\"],\n 'frame-ancestors': [\"'none'\"],\n }\n return {\n directives,\n header: serializeCsp(directives),\n meta: serializeCsp(directives, { meta: true }),\n unresolved,\n }\n}\n\n/** The static-host `_headers` file (`/*` and the policy). */\nexport function headersFile(policy: string): string {\n return `/*\\n Content-Security-Policy: ${policy}\\n`\n}\n"]}
1
+ {"version":3,"file":"cs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CAAC;QACzD,UAAU,EAAE,CAAC,QAAQ,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;QACvC,aAAa,EAAE,CAAC,QAAQ,EAAE,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;QAC7C,UAAU,EAAE,CAAC,QAAQ,CAAC;QACtB,YAAY,EAAE,CAAC,QAAQ,CAAC;QACxB,iBAAiB,EAAE,CAAC,QAAQ,CAAC;KAC9B,CAAA;IACD,OAAO;QACL,UAAU;QACV,MAAM,EAAE,YAAY,CAAC,UAAU,CAAC;QAChC,IAAI,EAAE,YAAY,CAAC,UAAU,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;QAC9C,UAAU;KACX,CAAA;AACH,CAAC;AAED,6DAA6D;AAC7D,MAAM,UAAU,WAAW,CAAC,MAAc;IACxC,OAAO,kCAAkC,MAAM,IAAI,CAAA;AACrD,CAAC","sourcesContent":["/**\n * The app's Content Security Policy, derived from what the app declares.\n *\n * A pwapp is static files; what it may load and reach is known at build time\n * from its own declarations, so `pwf build` writes a policy that allows that\n * and nothing else (pwapp-format §2.1):\n *\n * default-src 'none'\n * script-src 'self' blob: 'sha256-<import map>'\n * Blocks and compiled engines are verified and then imported\n * from `blob:` URLs. The import map is the shell's only inline\n * script (an import map cannot be an external file), so its\n * hash is listed; the renderer seeding and the boot call are\n * files (`assets/seed.js`, `assets/boot.js`).\n * style-src 'self' 'unsafe-inline' [+ the webfont stylesheet origin]\n * The renderer draws `<style>` elements at run time (the\n * surface base, visibility, state, responsive and dark-theme\n * rules, computed per page), and blocks set `style`\n * attributes. Neither can be hashed ahead of time.\n * img-src 'self' data: blob: [+ media origins]\n * media-src 'self' data: blob: [+ media origins]\n * frame-src [media origins] — only when there are any\n * font-src 'self' [+ the webfont file origin]\n * connect-src 'self' [+ every origin the app's data and sign-in reach]\n * base-uri 'self' — a host that serves the app under a sub-path\n * injects `<base href>` (pwapp-format §2); 'none' would make\n * the browser ignore it and break path routing.\n * object-src 'none'\n * frame-ancestors 'none' — header only: browsers ignore it in a `<meta>`.\n *\n * Origins come from: absolute `rest` endpoints in the receipts; declared\n * engines' `host` templates filled from `connections.json` config;\n * the envelope `auth.json` addresses and an external issuer; `publish.json`\n * media and absolute media URLs in receipt props. A template that cannot be\n * resolved at build time, and a compiled engine (whose code may reach any\n * origin), is listed in `unresolved` instead of being guessed.\n *\n * @module @pwfabric/cli/dev/csp\n */\nimport { createHash } from 'node:crypto'\nimport { isRecord } from './sources.js'\n\n/** Directive name → its sources, in the order they are written. */\nexport type CspDirectives = Record<string, string[]>\n\n/** Something the policy could not resolve at build time. */\nexport interface CspUnresolved {\n /** What declared it: `connection:<name>`, `engine:<atomId>`, `page:<key>`, `auth`. */\n readonly source: string\n /** The template or address as written. */\n readonly value: string\n readonly reason: string\n}\n\nexport interface AppCsp {\n readonly directives: CspDirectives\n /** The policy as a header value (every directive). */\n readonly header: string\n /** The policy for a `<meta http-equiv>` (without the directives a meta cannot carry). */\n readonly meta: string\n readonly unresolved: readonly CspUnresolved[]\n}\n\nexport interface CspInputs {\n /** The exact text of the shell's inline import map. */\n readonly importMapText: string\n /** Served receipts by page key (after media slots are filled). */\n readonly receipts: ReadonlyMap<string, unknown>\n /** `pwpack/connections.json`. */\n readonly connections?: { readonly connections: readonly Record<string, unknown>[] } | undefined\n /** `engines/manifest.json` entries. */\n readonly engines: readonly { readonly connection: string; readonly atomId: string; readonly moduleUrl?: string; readonly engine?: unknown }[]\n /** The envelope `auth.json`, when the build has one. */\n readonly envelopeAuth?: unknown\n /** `app/definitions/auth.json` (the declaration). */\n readonly authDefinition?: unknown\n /** `publish.json` `media[]`. */\n readonly media: readonly { readonly url: string }[]\n /** The webfont stylesheet the shell links, when any. */\n readonly webfontHref?: string | null\n}\n\n/** Directives a `<meta http-equiv=\"Content-Security-Policy\">` cannot carry (CSP3 §3.3). */\nconst HEADER_ONLY = new Set(['frame-ancestors', 'report-uri', 'report-to', 'sandbox'])\n\n/** The CSP source for an inline script: `'sha256-<base64>'` of its exact text. */\nexport function scriptHash(text: string): string {\n return `'sha256-${createHash('sha256').update(text, 'utf8').digest('base64')}'`\n}\n\nconst LOOPBACK = /^(?:localhost|127\\.0\\.0\\.1|\\[::1\\]|[^/:]+\\.localhost)(?::\\d+)?$/i\n\n/**\n * The origin of an absolute http(s) URL, or null. Expressions (`{{…}}`) or\n * templates (`{…}`) in the scheme or host make it unresolvable (`undefined`).\n */\nexport function originOf(value: string): string | null | undefined {\n const m = /^(https?):\\/\\/([^/?#]*)/i.exec(value.trim())\n if (!m) return null\n const host = m[2] as string\n if (!host || /[{}]/.test(host)) return undefined\n try {\n return new URL(`${(m[1] as string).toLowerCase()}://${host}`).origin\n } catch {\n return undefined\n }\n}\n\n/**\n * The origin a declared engine's `host` reaches (connector-manifest §3.1):\n * `{name}` filled from the connection's string config, the scheme dropped and\n * `https://` prepended, except an explicit `http://` on a loopback host.\n * `undefined` when a placeholder stays unfilled.\n */\nexport function engineHostOrigin(host: string, config: Record<string, unknown> | undefined): string | undefined {\n const filled = host.replace(/\\{([A-Za-z0-9_.-]+)\\}/g, (whole, name: string) => {\n const v = config?.[name]\n return typeof v === 'string' ? v : whole\n })\n if (/[{}]/.test(filled)) return undefined\n const explicitHttp = /^http:\\/\\//i.test(filled.trim())\n const bare = filled.trim().replace(/^[a-z][a-z0-9+.-]*:\\/\\//i, '')\n const hostPart = bare.split(/[/?#]/)[0] ?? ''\n if (!hostPart) return undefined\n const scheme = explicitHttp && LOOPBACK.test(hostPart) ? 'http' : 'https'\n try {\n return new URL(`${scheme}://${hostPart}`).origin\n } catch {\n return undefined\n }\n}\n\n/** A prop that names where a link goes (navigation is not governed by CSP). */\nconst LINK_PROP = /^(?:href|to|link|url|.*Href|.*Link)$/\n\n/** Every absolute URL a receipt's block props carry, except links. */\nfunction mediaUrlsOf(blocks: unknown, out: string[]): void {\n if (!Array.isArray(blocks)) return\n for (const block of blocks) {\n if (!isRecord(block)) continue\n const props = block['props']\n if (isRecord(props)) collectUrls(props, out)\n mediaUrlsOf(block['children'], out)\n }\n}\n\nfunction collectUrls(value: Record<string, unknown> | unknown[], out: string[]): void {\n const entries: [string, unknown][] = Array.isArray(value) ? value.map((v, i) => [String(i), v]) : Object.entries(value)\n for (const [key, v] of entries) {\n if (typeof v === 'string') {\n if (!LINK_PROP.test(key) && /^https?:\\/\\//i.test(v.trim())) out.push(v.trim())\n } else if (Array.isArray(v) || isRecord(v)) {\n collectUrls(v, out)\n }\n }\n}\n\n/** `rest` data sources of a receipt's persistence capability. */\nfunction restEndpointsOf(receipt: unknown): string[] {\n if (!isRecord(receipt) || !Array.isArray(receipt['capabilities'])) return []\n const out: string[] = []\n for (const cap of receipt['capabilities']) {\n if (!isRecord(cap) || !isRecord(cap['config'])) continue\n const sources = cap['config']['dataSources']\n if (!Array.isArray(sources)) continue\n for (const s of sources) {\n if (isRecord(s) && s['kind'] === 'rest' && typeof s['endpoint'] === 'string') out.push(s['endpoint'])\n }\n }\n return out\n}\n\nconst AUTH_ADDRESS_KEYS = ['loginUrl', 'registerUrl', 'logoutUrl', 'sessionUrl', 'tokenUrl', 'issuer', 'startUrl', 'gatewaySessionUrl', 'gatewayLogoutUrl', 'apiBase']\n\n/** Writes the directives as a policy string. */\nexport function serializeCsp(directives: CspDirectives, options: { meta?: boolean } = {}): string {\n return Object.entries(directives)\n .filter(([name, values]) => values.length > 0 && !(options.meta && HEADER_ONLY.has(name)))\n .map(([name, values]) => `${name} ${values.join(' ')}`)\n .join('; ')\n}\n\n/** Derives the app's policy from what it declares. */\nexport function deriveCsp(input: CspInputs): AppCsp {\n const unresolved: CspUnresolved[] = []\n const connect = new Set<string>()\n const media = new Set<string>()\n const style = new Set<string>()\n const font = new Set<string>()\n\n const addConnect = (value: string, source: string): void => {\n const o = originOf(value)\n if (o === undefined) unresolved.push({ source, value, reason: 'the address is a template or expression; its origin is known only at run time' })\n else if (o) connect.add(o)\n }\n\n // Data: absolute `rest` endpoints in the receipts. Relative ones are 'self'.\n for (const [key, receipt] of input.receipts) {\n for (const endpoint of restEndpointsOf(receipt)) addConnect(endpoint, `page:${key}`)\n const urls: string[] = []\n if (isRecord(receipt)) mediaUrlsOf(receipt['blocks'], urls)\n for (const url of urls) {\n const o = originOf(url)\n if (o) media.add(o)\n else if (o === undefined) unresolved.push({ source: `page:${key}`, value: url, reason: 'a media address with an expression in its origin' })\n }\n }\n\n // Connections: declared engines resolve their host; compiled ones cannot be read.\n const configOf = new Map<string, Record<string, unknown>>()\n for (const c of input.connections?.connections ?? []) {\n if (typeof c['name'] === 'string') configOf.set(c['name'], isRecord(c['config']) ? c['config'] : {})\n }\n for (const e of input.engines) {\n const host = isRecord(e.engine) && typeof e.engine['host'] === 'string' ? e.engine['host'] : undefined\n if (host !== undefined) {\n const o = engineHostOrigin(host, configOf.get(e.connection))\n if (o) connect.add(o)\n else unresolved.push({ source: `connection:${e.connection}`, value: host, reason: 'the engine host names config the connection does not provide' })\n } else if (e.moduleUrl) {\n unresolved.push({\n source: `engine:${e.atomId}`,\n value: e.moduleUrl,\n reason: `compiled engine for connection \"${e.connection}\"; the origins its code reaches are not declared`,\n })\n }\n }\n\n // Sign-in: the envelope's addresses, and an external issuer's.\n if (isRecord(input.envelopeAuth)) {\n for (const k of AUTH_ADDRESS_KEYS) {\n const v = input.envelopeAuth[k]\n if (typeof v === 'string') addConnect(v, 'auth')\n }\n }\n const issuer = isRecord(input.authDefinition) && isRecord(input.authDefinition['issuer']) ? input.authDefinition['issuer'] : undefined\n if (issuer) {\n for (const k of ['issuer', 'tokenUrl']) {\n const v = issuer[k]\n if (typeof v === 'string') addConnect(v, 'auth')\n }\n if (typeof issuer['tokenUrl'] !== 'string' && typeof issuer['issuer'] === 'string') {\n unresolved.push({\n source: 'auth',\n value: issuer['issuer'],\n reason: \"the token endpoint is discovered at run time; the policy allows the issuer's own origin only\",\n })\n }\n }\n\n // Media the app declares.\n for (const m of input.media) {\n const o = originOf(m.url)\n if (o) media.add(o)\n }\n\n // Webfonts: the stylesheet and the files it points at.\n if (input.webfontHref) {\n const o = originOf(input.webfontHref)\n if (o) style.add(o)\n if (o === 'https://fonts.googleapis.com') font.add('https://fonts.gstatic.com')\n }\n\n const sorted = (s: Set<string>): string[] => [...s].sort()\n const directives: CspDirectives = {\n 'default-src': [\"'none'\"],\n 'script-src': [\"'self'\", 'blob:', scriptHash(input.importMapText)],\n 'style-src': [\"'self'\", \"'unsafe-inline'\", ...sorted(style)],\n 'img-src': [\"'self'\", 'data:', 'blob:', ...sorted(media)],\n 'media-src': [\"'self'\", 'data:', 'blob:', ...sorted(media)],\n ...(media.size > 0 ? { 'frame-src': sorted(media) } : {}),\n 'font-src': [\"'self'\", ...sorted(font)],\n 'connect-src': [\"'self'\", ...sorted(connect)],\n 'base-uri': [\"'self'\"],\n 'object-src': [\"'none'\"],\n 'frame-ancestors': [\"'none'\"],\n }\n return {\n directives,\n header: serializeCsp(directives),\n meta: serializeCsp(directives, { meta: true }),\n unresolved,\n }\n}\n\n/** The static-host `_headers` file (`/*` and the policy). */\nexport function headersFile(policy: string): string {\n return `/*\\n Content-Security-Policy: ${policy}\\n`\n}\n"]}
@@ -25,7 +25,10 @@ export declare function deriveNavigation(pages: readonly Page[], entry: string):
25
25
  }[];
26
26
  };
27
27
  };
28
- /** What the app declares about who may enter (`app/definitions/auth.json`), as `project.json` carries it. */
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';
@@ -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
- /** What the app declares about who may enter (`app/definitions/auth.json`), as `project.json` carries it. */
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,
40
45
  topology,
@@ -1 +1 @@
1
- {"version":3,"file":"envelope.js","sourceRoot":"","sources":["../../src/dev/envelope.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAA;AAWvC,+EAA+E;AAC/E,MAAM,UAAU,YAAY,CAAC,OAAgB;IAC3C,MAAM,KAAK,GAAG,IAAI,GAAG,EAAU,CAAA;IAC/B,MAAM,IAAI,GAAG,CAAC,IAAa,EAAQ,EAAE;QACnC,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;YACxB,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAA;YAClB,OAAM;QACR,CAAC;QACD,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;YAAE,OAAM;QAC3B,IAAI,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,QAAQ,IAAI,IAAI,CAAC,MAAM,CAAC;YAAE,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAA;QAC7E,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;YAAE,IAAI,CAAC,UAAU,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAA;IACrE,CAAC,CAAA;IACD,IAAI,QAAQ,CAAC,OAAO,CAAC;QAAE,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAA;IAC9C,OAAO,CAAC,GAAG,KAAK,CAAC,CAAA;AACnB,CAAC;AAED,k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CAAA;AAC7F,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,oBAAoB,CAClC,KAA8B,EAC9B,OAAsD,EACtD,WAAiC;IAEjC,IAAI,CAAC,OAAO;QAAE,OAAM;IACpB,MAAM,GAAG,GAAG,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/** 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 }\n}\n"]}
1
+ {"version":3,"file":"envelope.js","sourceRoot":"","sources":["../../src/dev/envelope.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAA;AAWvC,+EAA+E;AAC/E,MAAM,UAAU,YAAY,CAAC,OAAgB;IAC3C,MAAM,KAAK,GAAG,IAAI,GAAG,EAAU,CAAA;IAC/B,MAAM,IAAI,GAAG,CAAC,IAAa,EAAQ,EAAE;QACnC,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;YACxB,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAA;YAClB,OAAM;QACR,CAAC;QACD,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;YAAE,OAAM;QAC3B,IAAI,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,QAAQ,IAAI,IAAI,CAAC,MAAM,CAAC;YAAE,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAA;QAC7E,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;YAAE,IAAI,CAAC,UAAU,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAA;IACrE,CAAC,CAAA;IACD,IAAI,QAAQ,CAAC,OAAO,CAAC;QAAE,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAA;IAC9C,OAAO,CAAC,GAAG,KAAK,CAAC,CAAA;AACnB,CAAC;AAED,kEAAkE;AAClE,MAAM,UAAU,SAAS,CAAC,IAAU;IAClC,MAAM,KAAK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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"]}
@@ -1,4 +1,4 @@
1
- import type { CreateLocalHost } from '../host/types.js';
1
+ import type { CreateLocalHost } from '../host/index.js';
2
2
  import { type AssembleOptions } from './assemble.js';
3
3
  import { type AssembleDiagnostic } from './diagnostics.js';
4
4
  import type { DevServer, DevServerOptions, StartDevServer } from './types.js';