@notionhq/custom-blocks-dev-shell 0.1.114 → 0.1.116

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +108 -22
  3. package/THIRD_PARTY_LICENSES.md +133 -0
  4. package/bin/cli.js +3 -1
  5. package/dist/assets/index-DSaseWP_.js +11 -0
  6. package/dist/assets/index-Do-x8yIt.css +2 -0
  7. package/dist/index.html +2 -2
  8. package/dist-cli/cli/published-cli.js +8476 -0
  9. package/docs/bindings.md +84 -27
  10. package/docs/bridge/changelog.md +67 -0
  11. package/docs/bridge/protocol.md +204 -0
  12. package/docs/bridge/versioning.md +38 -0
  13. package/docs/data-sources.md +49 -36
  14. package/docs/host/README.md +177 -0
  15. package/docs/host/docs/compatibility.md +68 -0
  16. package/docs/host/docs/handlers.md +199 -0
  17. package/docs/host/docs/lifecycle.md +117 -0
  18. package/package.json +9 -28
  19. package/dist/assets/index-E1j3FxAu.css +0 -2
  20. package/dist/assets/index-F02ZboyS.js +0 -11
  21. package/dist-cli/block-csp.js +0 -84
  22. package/dist-cli/build-block-registry.js +0 -28
  23. package/dist-cli/convert-values.js +0 -222
  24. package/dist-cli/convert.js +0 -210
  25. package/dist-cli/data-sources.js +0 -167
  26. package/dist-cli/date-value.js +0 -46
  27. package/dist-cli/dev-shell-launcher.js +0 -226
  28. package/dist-cli/dev-shell-run.js +0 -72
  29. package/dist-cli/errors.js +0 -8
  30. package/dist-cli/materialize.js +0 -105
  31. package/dist-cli/ports.js +0 -20
  32. package/dist-cli/prebuilt.js +0 -23
  33. package/dist-cli/published-cli.js +0 -60
  34. package/dist-cli/resolve-bindings.js +0 -39
  35. package/dist-cli/runtime-error-client.js +0 -52
  36. package/dist-cli/serve-ui.js +0 -110
  37. package/dist-cli/shared-server.js +0 -70
  38. package/dist-cli/source-bindings.js +0 -17
  39. package/dist-cli/utils.js +0 -52
  40. package/dist-cli/vite-block-server.js +0 -125
  41. package/dist-cli/vite-middleware.js +0 -111
  42. package/dist-cli/worker-manifest.js +0 -141
@@ -1,167 +0,0 @@
1
- /**
2
- * Load a worker's dev shell data sources from `<dataDir>/*.json` — one source
3
- * per file, hand-authored. Every file is validated here, before it reaches
4
- * the shell, so a malformed source fails spin-up naming the file and the
5
- * problem instead of breaking the UI.
6
- */
7
- import { existsSync, readdirSync, readFileSync } from "node:fs";
8
- import { basename, resolve } from "node:path";
9
- import * as v from "valibot";
10
- import { formatUnknownError } from "./errors.js";
11
- const DEV_SHELL_DATA_SOURCE_TYPES = [
12
- "built-in",
13
- "worker",
14
- "manual",
15
- "syncedFromProd",
16
- ];
17
- const DEV_SHELL_STATUS_GROUP_NAMES = [
18
- "To-do",
19
- "In progress",
20
- "Complete",
21
- "Current",
22
- "Future",
23
- ];
24
- // Local copy of the SDK's NOTION_PROPERTY_TYPES: the compiled CLI runs under
25
- // plain node, which can't import the SDK's published TS source at runtime.
26
- // The `satisfies` below plus the type-only import keep the two lists locked
27
- // together — a drift on either side fails typecheck.
28
- export const NOTION_PROPERTY_TYPES = [
29
- "title",
30
- "rich_text",
31
- "number",
32
- "checkbox",
33
- "url",
34
- "email",
35
- "phone_number",
36
- "select",
37
- "multi_select",
38
- "status",
39
- "date",
40
- "people",
41
- "files",
42
- "unique_id",
43
- "relation",
44
- "place",
45
- "formula",
46
- "rollup",
47
- "button",
48
- "verification",
49
- "last_visited_time",
50
- "location",
51
- "created_time",
52
- "last_edited_time",
53
- "created_by",
54
- "last_edited_by",
55
- ];
56
- const _allPropertyTypesListed = true;
57
- void _allPropertyTypesListed;
58
- const _allStatusGroupNamesListed = true;
59
- void _allStatusGroupNamesListed;
60
- export function readDataSources(dataDir) {
61
- if (!existsSync(dataDir)) {
62
- return [];
63
- }
64
- return readdirSync(dataDir)
65
- .filter(name => name.endsWith(".json"))
66
- .map(name => readSource(resolve(dataDir, name)))
67
- .sort((left, right) => left.name.localeCompare(right.name));
68
- }
69
- const nonEmptyString = v.pipe(v.string(), v.nonEmpty());
70
- const statusOptionsSchema = v.array(v.object({
71
- id: nonEmptyString,
72
- name: nonEmptyString,
73
- }));
74
- const statusGroupsSchema = v.array(v.object({
75
- id: nonEmptyString,
76
- name: v.picklist(DEV_SHELL_STATUS_GROUP_NAMES),
77
- option_ids: v.array(nonEmptyString),
78
- }));
79
- const sourcePropertySchema = v.object({
80
- name: v.optional(v.string()),
81
- description: v.optional(v.string()),
82
- type: v.picklist(NOTION_PROPERTY_TYPES),
83
- options: v.optional(statusOptionsSchema),
84
- groups: v.optional(statusGroupsSchema),
85
- });
86
- export const sourceFileSchema = v.object({
87
- type: v.optional(v.picklist(DEV_SHELL_DATA_SOURCE_TYPES), "worker"),
88
- name: v.optional(nonEmptyString),
89
- icon: v.optional(v.string()),
90
- schema: v.optional(v.record(v.string(), sourcePropertySchema), {}),
91
- rows: v.optional(v.array(v.looseObject({ id: nonEmptyString })), []),
92
- });
93
- /**
94
- * Parse and validate one source file. Structural mistakes throw with the file
95
- * and problem named; the filename defines identity and the default `name`, and
96
- * omitted `schema`/`rows` to empty — so the minimal valid file is `{}`.
97
- */
98
- function readSource(file) {
99
- let parsed;
100
- try {
101
- parsed = JSON.parse(readFileSync(file, "utf-8"));
102
- }
103
- catch (error) {
104
- throw new Error(`${file}: not valid JSON — ${formatUnknownError(error)}`);
105
- }
106
- if (Array.isArray(parsed)) {
107
- throw new Error(`${file}: must be a JSON object`);
108
- }
109
- const result = v.safeParse(sourceFileSchema, parsed);
110
- if (!result.success) {
111
- const issue = result.issues[0];
112
- const path = v.getDotPath(issue);
113
- throw new Error(`${file}: ${path ? `${path}: ` : ""}${issue.message}`);
114
- }
115
- for (const [propertyKey, property] of Object.entries(result.output.schema)) {
116
- if (property.options !== undefined &&
117
- property.type !== "select" &&
118
- property.type !== "multi_select" &&
119
- property.type !== "status") {
120
- throw new Error(`${file}: schema.${propertyKey}: options require a Select, Multi-select, or Status property`);
121
- }
122
- if (property.groups !== undefined && property.type !== "status") {
123
- throw new Error(`${file}: schema.${propertyKey}: groups require a Status property`);
124
- }
125
- const optionIds = new Set((property.options ?? []).map(option => option.id));
126
- const missingOptionId = (property.groups ?? [])
127
- .flatMap(group => group.option_ids)
128
- .find(optionId => !optionIds.has(optionId));
129
- if (missingOptionId !== undefined) {
130
- throw new Error(`${file}: schema.${propertyKey}: group references unknown option ID "${missingOptionId}"`);
131
- }
132
- }
133
- const { type, icon, schema, rows } = result.output;
134
- const filename = basename(file, ".json");
135
- return {
136
- type,
137
- key: filename,
138
- filename,
139
- name: result.output.name ?? filename,
140
- ...(icon !== undefined ? { icon } : {}),
141
- schema: Object.fromEntries(Object.entries(schema).map(([propertyKey, property]) => [
142
- propertyKey,
143
- toNotionPropertySchema(propertyKey, property),
144
- ])),
145
- rows,
146
- };
147
- }
148
- function toNotionPropertySchema(propertyKey, property) {
149
- const base = {
150
- name: property.name ?? propertyKey,
151
- ...(property.description !== undefined
152
- ? { description: property.description }
153
- : {}),
154
- };
155
- if (property.type === "select" || property.type === "multi_select") {
156
- return { ...base, type: property.type, options: property.options ?? [] };
157
- }
158
- if (property.type === "status") {
159
- return {
160
- ...base,
161
- type: "status",
162
- options: property.options ?? [],
163
- groups: property.groups ?? [],
164
- };
165
- }
166
- return { ...base, type: property.type };
167
- }
@@ -1,46 +0,0 @@
1
- import * as v from "valibot";
2
- // The published CLI cannot import the private protocol package at runtime.
3
- // Keep this schema aligned with protocol/src/dataSources/dateValue.ts.
4
- const dateReminder = v.object({
5
- unit: v.picklist(["year", "month", "week", "day"]),
6
- value: v.number(),
7
- time: v.string(),
8
- defaultTimeZone: v.optional(v.string()),
9
- });
10
- const timeReminder = v.object({
11
- unit: v.picklist(["hour", "minute"]),
12
- value: v.number(),
13
- });
14
- const noReminder = v.object({ unit: v.literal("none") });
15
- const dateOrNoReminder = v.optional(v.union([dateReminder, noReminder]));
16
- const dateTimeOrNoReminder = v.optional(v.union([dateReminder, timeReminder, noReminder]));
17
- /** Date values used by both the dev shell CLI and its browser binding editor. */
18
- export const localDateValueSchema = v.variant("type", [
19
- v.object({
20
- type: v.literal("date"),
21
- start_date: v.string(),
22
- reminder: dateOrNoReminder,
23
- }),
24
- v.object({
25
- type: v.literal("daterange"),
26
- start_date: v.string(),
27
- end_date: v.string(),
28
- reminder: dateOrNoReminder,
29
- }),
30
- v.object({
31
- type: v.literal("datetime"),
32
- start_date: v.string(),
33
- start_time: v.string(),
34
- time_zone: v.optional(v.string()),
35
- reminder: dateTimeOrNoReminder,
36
- }),
37
- v.object({
38
- type: v.literal("datetimerange"),
39
- start_date: v.string(),
40
- start_time: v.string(),
41
- end_date: v.string(),
42
- end_time: v.string(),
43
- time_zone: v.optional(v.string()),
44
- reminder: dateTimeOrNoReminder,
45
- }),
46
- ]);
@@ -1,226 +0,0 @@
1
- /**
2
- * Shared orchestration for the repository and published dev shell launchers.
3
- *
4
- * It builds the worker and reads its manifest, creates one Vite middleware instance per
5
- * custom block, and owns resource cleanup. Each launcher entry point
6
- * supplies a small shell adapter, but otherwise delegates to this module.
7
- */
8
- import { existsSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";
9
- import { basename, join, resolve } from "node:path";
10
- import { buildBlockRegistry, } from "./build-block-registry.js";
11
- import { readDataSources } from "./data-sources.js";
12
- import { DevShellRun, installProcessSignalHandlers, } from "./dev-shell-run.js";
13
- import { formatUnknownErrorWithStack } from "./errors.js";
14
- import { materializeWorkerSchemaDataSources } from "./materialize.js";
15
- import { DEFAULT_DEV_SHELL_PORT, parsePort } from "./ports.js";
16
- import { resolveLaunchBindings } from "./resolve-bindings.js";
17
- import { SharedServer } from "./shared-server.js";
18
- import { parseBindingOverride, } from "./source-bindings.js";
19
- import { parseCliArgs } from "./utils.js";
20
- import { writeBlockViteConfig } from "./vite-block-server.js";
21
- import { mountVite } from "./vite-middleware.js";
22
- import { blockCapabilities, findWorkerDir, generateWorkerManifest, } from "./worker-manifest.js";
23
- const dim = "\x1b[2m";
24
- const bold = "\x1b[1m";
25
- const cyan = "\x1b[36m";
26
- const reset = "\x1b[0m";
27
- const label = (name) => `${cyan}[${name}]${reset}`;
28
- export async function prepareWorkerLaunchPlan(workerDir, options = {}) {
29
- const root = resolve(workerDir);
30
- if (!existsSync(resolve(root, "node_modules"))) {
31
- throw new Error(`No node_modules in ${root}. Install the worker's dependencies first ` +
32
- `(e.g. \`npm install\`), then rerun.`);
33
- }
34
- const { manifest, manifestPath } = await generateWorkerManifest(root, {
35
- build: options.build,
36
- });
37
- const capabilities = blockCapabilities(manifest);
38
- const registry = buildBlockRegistry(capabilities, options.shellPort ?? DEFAULT_DEV_SHELL_PORT);
39
- const configDir = options.configDir ?? join(root, ".dev-shell");
40
- const blocks = capabilities.map((capability, index) => {
41
- const blockDir = resolve(root, capability.config.source.path);
42
- const hostname = new URL(registry[index].url).hostname;
43
- return {
44
- capability,
45
- blockDir,
46
- hostname,
47
- configFile: writeBlockViteConfig(blockDir, capability, configDir, hostname),
48
- };
49
- });
50
- const dataDir = resolve(root, "data");
51
- materializeWorkerSchemaDataSources(manifest, dataDir);
52
- return {
53
- workerDir: root,
54
- configDir,
55
- dataDir,
56
- manifestPath,
57
- blocks,
58
- registry,
59
- dataSources: readDataSources(dataDir),
60
- };
61
- }
62
- export function parseWorkerLaunchArgs(argv) {
63
- const args = {
64
- worker: undefined,
65
- shellPort: DEFAULT_DEV_SHELL_PORT,
66
- strictPort: false,
67
- bindings: [],
68
- };
69
- let hasPositionalWorker = false;
70
- parseCliArgs({
71
- argv,
72
- handlers: {
73
- "--bind": value => {
74
- args.bindings.push(parseBindingOverride(value));
75
- },
76
- "--worker": value => {
77
- if (value.length === 0) {
78
- throw new Error("--worker requires a path to a worker directory.");
79
- }
80
- // Reject --worker after a positional worker path.
81
- if (hasPositionalWorker) {
82
- throw new Error("Cannot combine --worker with a positional worker path.");
83
- }
84
- args.worker = value;
85
- },
86
- "--port": value => {
87
- args.shellPort = parsePort("--port", value);
88
- args.strictPort = true;
89
- },
90
- },
91
- onUnknown: arg => {
92
- throw new Error(`Unknown dev shell option "${arg}". Supported: --worker <dir>, ` +
93
- `--port <port>, --bind <capabilityKey>.<dataSourceKey>=<sampleDataFileName>.`);
94
- },
95
- onPositional: arg => {
96
- // The published launcher passes its optional worker path positionally.
97
- // Reject a second positional path.
98
- if (hasPositionalWorker) {
99
- throw new Error("Only one positional worker path may be provided.");
100
- }
101
- // Reject a positional path after --worker.
102
- if (args.worker !== undefined) {
103
- throw new Error("Cannot combine --worker with a positional worker path.");
104
- }
105
- hasPositionalWorker = true;
106
- args.worker = arg;
107
- },
108
- });
109
- return args;
110
- }
111
- function logNamed(name, message) {
112
- console.log(`${label(name)} ${message}`);
113
- }
114
- function printSummary(args, registry) {
115
- console.log("");
116
- console.log(`${bold}Dev shell${reset}`);
117
- console.log(` ${label("dev-shell")} ${dim}http://localhost:${args.shellPort}${reset}`);
118
- if (registry.length > 0) {
119
- console.log("");
120
- console.log(`${bold}Blocks${reset}`);
121
- for (const entry of registry) {
122
- console.log(` ${label(entry.key)} ${dim}${entry.url}${reset}`);
123
- }
124
- }
125
- console.log("");
126
- }
127
- function resolveWorkerLaunch(options) {
128
- const args = parseWorkerLaunchArgs(options.argv);
129
- const workerDir = args.worker === undefined
130
- ? findWorkerDir(options.detectFromDir)
131
- : resolve(options.workerBaseDir, args.worker);
132
- if (workerDir === undefined) {
133
- throw new Error("No worker found: run from inside a worker directory, or pass --worker <dir>.");
134
- }
135
- if (args.worker === undefined) {
136
- console.log(`Detected a worker at ${workerDir}.`);
137
- }
138
- return { args, workerDir };
139
- }
140
- function logWorkerPlan(workerName, plan) {
141
- logNamed(workerName, `Wrote ${plan.manifestPath}`);
142
- if (plan.blocks.length === 0) {
143
- logNamed(workerName, "Worker declares no custom blocks.");
144
- }
145
- logNamed(workerName, plan.dataSources.length > 0
146
- ? `Data sources from data: ${plan.dataSources
147
- .map(source => source.name)
148
- .join(", ")}`
149
- : "No data sources — create data/<key>.json files " +
150
- "(format: node_modules/@notionhq/custom-blocks-dev-shell/docs/data-sources.md).");
151
- }
152
- function applyBindingsAndLog(args, plan, workerDir) {
153
- const { registryBindings } = resolveLaunchBindings(plan.blocks.map(block => block.capability), plan.dataSources, args.bindings);
154
- for (const entry of plan.registry) {
155
- const bindings = registryBindings.get(entry.key);
156
- if (bindings !== undefined) {
157
- entry.sampleFilesByDataSource = bindings;
158
- }
159
- }
160
- logWorkerPlan(basename(workerDir), plan);
161
- }
162
- export async function launchDevShell(options) {
163
- const { installSignalHandlers = true } = options;
164
- const shared = new SharedServer();
165
- const beforeCleanup = () => shared.close();
166
- const run = options.createRun?.(beforeCleanup) ?? new DevShellRun(beforeCleanup);
167
- if (installSignalHandlers) {
168
- installProcessSignalHandlers(run);
169
- }
170
- try {
171
- const { args, workerDir } = resolveWorkerLaunch(options);
172
- const originalCwd = process.cwd();
173
- // One worker owns the process for the run, including Vite config reloads
174
- // and plugin callbacks. Resolve CLI paths before changing directories.
175
- process.chdir(workerDir);
176
- run.addResource(() => process.chdir(originalCwd));
177
- args.shellPort = await shared.listen(args.shellPort, args.strictPort);
178
- const tempRoot = join(workerDir, ".dev-shell");
179
- mkdirSync(tempRoot, { recursive: true });
180
- const configDir = mkdtempSync(join(tempRoot, "run-"));
181
- run.addResource(() => rmSync(configDir, { recursive: true, force: true }));
182
- logNamed(basename(workerDir), "Extracting worker manifest...");
183
- const plan = await prepareWorkerLaunchPlan(workerDir, {
184
- shellPort: args.shellPort,
185
- configDir,
186
- });
187
- if (run.closing) {
188
- return;
189
- }
190
- applyBindingsAndLog(args, plan, workerDir);
191
- const closeShell = await options.createShellLaunch({
192
- plan,
193
- shared,
194
- log: logNamed,
195
- });
196
- if (closeShell) {
197
- run.addResource(closeShell);
198
- }
199
- for (const block of plan.blocks) {
200
- if (run.closing) {
201
- return;
202
- }
203
- const close = await mountVite({
204
- projectDir: workerDir,
205
- hostname: block.hostname,
206
- // TODO(custom-blocks): Let users limit network origins and embedding hosts.
207
- blockPolicy: {
208
- allowedNetworkOrigins: ["*"],
209
- allowedFrameAncestors: ["*"],
210
- },
211
- shared,
212
- config: { configFile: block.configFile, root: block.blockDir },
213
- });
214
- run.addResource(close);
215
- }
216
- if (run.closing) {
217
- return;
218
- }
219
- printSummary(args, plan.registry);
220
- }
221
- catch (error) {
222
- console.error(`Failed to start dev shell:\n${formatUnknownErrorWithStack(error)}`);
223
- process.exitCode = 1;
224
- run.shutdown("SIGTERM");
225
- }
226
- }
@@ -1,72 +0,0 @@
1
- /** Own the listener and Vite resources for one dev shell run. */
2
- const SHUTDOWN_GRACE_MS = 1500;
3
- export class DevShellRun {
4
- beforeCleanup;
5
- resources = [];
6
- shuttingDown = false;
7
- constructor(beforeCleanup) {
8
- this.beforeCleanup = beforeCleanup;
9
- }
10
- get closing() {
11
- return this.shuttingDown;
12
- }
13
- addResource(resource) {
14
- if (this.closing) {
15
- void closeResource(resource);
16
- return;
17
- }
18
- this.resources.push(resource);
19
- }
20
- shutdown(signal) {
21
- if (signal === "exit") {
22
- const alreadyClosing = this.closing;
23
- this.shuttingDown = true;
24
- if (!alreadyClosing) {
25
- void closeResource(this.beforeCleanup);
26
- }
27
- // Exit handlers cannot await promises. Start all remaining cleanup,
28
- // including file removal when an earlier async cleanup timed out.
29
- for (let resource = this.resources.pop(); resource; resource = this.resources.pop()) {
30
- void closeResource(resource);
31
- }
32
- return;
33
- }
34
- if (this.closing) {
35
- process.exit(process.exitCode ?? 130);
36
- return;
37
- }
38
- this.shuttingDown = true;
39
- console.log("\n\x1b[2mShutting down...\x1b[0m");
40
- void this.finishShutdown();
41
- }
42
- async finishShutdown() {
43
- const timeout = setTimeout(() => {
44
- process.exit(process.exitCode ?? 130);
45
- }, SHUTDOWN_GRACE_MS);
46
- await closeResource(this.beforeCleanup);
47
- for (let resource = this.resources.pop(); resource; resource = this.resources.pop()) {
48
- await closeResource(resource);
49
- }
50
- clearTimeout(timeout);
51
- process.exit(process.exitCode ?? 0);
52
- }
53
- }
54
- async function closeResource(resource) {
55
- try {
56
- await resource();
57
- }
58
- catch (error) {
59
- console.error("Dev shell cleanup failed:", error);
60
- }
61
- }
62
- export function installProcessSignalHandlers(run) {
63
- for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
64
- process.on(signal, () => run.shutdown(signal));
65
- }
66
- process.on("exit", () => run.shutdown("exit"));
67
- process.on("uncaughtException", error => {
68
- console.error(error);
69
- process.exitCode = 1;
70
- run.shutdown("SIGTERM");
71
- });
72
- }
@@ -1,8 +0,0 @@
1
- /** Format an unknown error as a message without a stack trace. */
2
- export function formatUnknownError(error) {
3
- return error instanceof Error ? error.message : String(error);
4
- }
5
- /** Format an unknown error with its stack when one is available. */
6
- export function formatUnknownErrorWithStack(error) {
7
- return error instanceof Error ? (error.stack ?? error.message) : String(error);
8
- }
@@ -1,105 +0,0 @@
1
- /**
2
- * Materialize a worker's declared data sources as `data/worker_<key>.json`
3
- * files: the schema with no rows, mirroring a managed database before any
4
- * sync. Rows are added by editing the file; `data-sources.ts` reads and
5
- * validates whatever ends up in the directory.
6
- *
7
- * A block's data source can come from a `worker.database` or from an inline
8
- * schema declared on the block (`worker.customBlock({ dataSources })`); both
9
- * are materialized so all sources are treated equivalently — just files in
10
- * `data/`. The `worker_` prefix keeps generated sources from ever colliding
11
- * with hand-authored files, so both can coexist.
12
- *
13
- * Files are written only when absent, so hand-edited or hand-authored sources
14
- * survive across restarts; delete a file to regenerate it from the schema.
15
- */
16
- import { existsSync, mkdirSync, writeFileSync } from "node:fs";
17
- import { resolve } from "node:path";
18
- import { blockCapabilities } from "./worker-manifest.js";
19
- // Worker authoring type names → public data source (NotionPropertyType) names.
20
- const TYPE_ALIASES = {
21
- text: "rich_text",
22
- file: "files",
23
- };
24
- /**
25
- * Generated files are namespaced so they never shadow authored files. The
26
- * filename carries the prefix, while the display name stays as declared, so the sidebar
27
- * shows the clean name.
28
- */
29
- const WORKER_PREFIX = "worker_";
30
- export function materializeWorkerSchemaDataSources(manifest, dataDir) {
31
- // One descriptor per data source key: databases first (source of truth for
32
- // anything they back), then inline block schemas for keys no database
33
- // provides.
34
- const descriptors = new Map();
35
- for (const database of manifest.databases) {
36
- descriptors.set(database.key, {
37
- name: database.config.initialTitle ?? database.key,
38
- properties: (database.config.schema?.properties ?? {}),
39
- });
40
- }
41
- for (const block of blockCapabilities(manifest)) {
42
- for (const [key, slot] of Object.entries(block.config.manifest.dataSources)) {
43
- const properties = (slot.properties ?? {});
44
- const existing = descriptors.get(key);
45
- if (existing !== undefined) {
46
- // Same key from two blocks with different shapes: slot keys are only
47
- // unique per block, so one file can't serve both. First block wins;
48
- // say so instead of leaving the loser silently unbindable.
49
- if (existing.blockKey !== undefined &&
50
- !samePropertySchemas(existing.properties, properties)) {
51
- console.warn(`Blocks "${existing.blockKey}" and "${block.key}" both declare data source ` +
52
- `"${key}" with different schemas; ${WORKER_PREFIX}${key}.json uses the ` +
53
- `schema from "${existing.blockKey}". Author a data/ file for "${block.key}" by hand.`);
54
- }
55
- continue;
56
- }
57
- descriptors.set(key, {
58
- name: slot.name ?? key,
59
- properties,
60
- blockKey: block.key,
61
- });
62
- }
63
- }
64
- // A worker with no data sources gets no data/ at all — the folder would
65
- // only suggest the shell expects files there.
66
- if (descriptors.size === 0) {
67
- return;
68
- }
69
- mkdirSync(dataDir, { recursive: true });
70
- for (const [key, descriptor] of descriptors) {
71
- // Replace path-hostile characters so the filename stays inside `dataDir`.
72
- const file = resolve(dataDir, `${WORKER_PREFIX}${fileSafe(key)}.json`);
73
- if (existsSync(file)) {
74
- continue;
75
- }
76
- writeFileSync(file, `${JSON.stringify(buildSource(descriptor), null, 2)}\n`);
77
- }
78
- }
79
- function fileSafe(key) {
80
- return key.replace(/[^a-zA-Z0-9_-]/g, "-");
81
- }
82
- function samePropertySchemas(left, right) {
83
- const leftKeys = Object.keys(left).sort();
84
- const rightKeys = Object.keys(right).sort();
85
- return (leftKeys.length === rightKeys.length &&
86
- leftKeys.every((key, index) => key === rightKeys[index] &&
87
- left[key].type === right[key].type &&
88
- (left[key].name ?? key) === (right[key].name ?? key)));
89
- }
90
- function buildSource(descriptor) {
91
- const { name, properties } = descriptor;
92
- const schema = {};
93
- for (const [propertyKey, property] of Object.entries(properties)) {
94
- schema[propertyKey] = {
95
- name: property.name ?? propertyKey,
96
- type: TYPE_ALIASES[property.type] ?? property.type,
97
- };
98
- }
99
- return {
100
- type: "worker",
101
- name,
102
- schema,
103
- rows: [],
104
- };
105
- }
package/dist-cli/ports.js DELETED
@@ -1,20 +0,0 @@
1
- /**
2
- * Port defaults and validation shared by the repository and published launchers.
3
- */
4
- /**
5
- * The default port for the dev shell, all blocks, and hot reload.
6
- * By default, the dev shell starts on this port.
7
- * If this port is occupied, the launcher tries higher ports in sequence until it finds an available port.
8
- * The --port option overrides this value and disables automatic port selection.
9
- */
10
- export const DEFAULT_DEV_SHELL_PORT = 9873;
11
- /** Highest valid TCP port. */
12
- const MAX_PORT = 65535;
13
- /** Parse and validate a named CLI port option. */
14
- export function parsePort(name, raw) {
15
- const port = Number(raw);
16
- if (!Number.isInteger(port) || port <= 0 || port > MAX_PORT) {
17
- throw new Error(`${name} requires a port number, got "${raw}".`);
18
- }
19
- return port;
20
- }
@@ -1,23 +0,0 @@
1
- /**
2
- * Copy the shell's pre-built sources (`data/*.json`, shipped in the
3
- * package) into a worker's data directory. Like materialization, existing
4
- * worker data always wins: a bundled source is skipped when its filename is
5
- * already taken. The filename defines the source identity.
6
- */
7
- import { copyFileSync, existsSync, mkdirSync } from "node:fs";
8
- import { resolve } from "node:path";
9
- import { readDataSources } from "./data-sources.js";
10
- export function copyPrebuiltDataSources(prebuiltDir, dataDir) {
11
- mkdirSync(dataDir, { recursive: true });
12
- const written = [];
13
- for (const source of readDataSources(prebuiltDir)) {
14
- const filename = `${source.filename}.json`;
15
- const target = resolve(dataDir, filename);
16
- if (existsSync(target)) {
17
- continue;
18
- }
19
- copyFileSync(resolve(prebuiltDir, filename), target);
20
- written.push(filename);
21
- }
22
- return written.sort();
23
- }