@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.
- package/LICENSE +21 -0
- package/README.md +108 -22
- package/THIRD_PARTY_LICENSES.md +133 -0
- package/bin/cli.js +3 -1
- package/dist/assets/index-DSaseWP_.js +11 -0
- package/dist/assets/index-Do-x8yIt.css +2 -0
- package/dist/index.html +2 -2
- package/dist-cli/cli/published-cli.js +8476 -0
- package/docs/bindings.md +84 -27
- package/docs/bridge/changelog.md +67 -0
- package/docs/bridge/protocol.md +204 -0
- package/docs/bridge/versioning.md +38 -0
- package/docs/data-sources.md +49 -36
- package/docs/host/README.md +177 -0
- package/docs/host/docs/compatibility.md +68 -0
- package/docs/host/docs/handlers.md +199 -0
- package/docs/host/docs/lifecycle.md +117 -0
- package/package.json +9 -28
- package/dist/assets/index-E1j3FxAu.css +0 -2
- package/dist/assets/index-F02ZboyS.js +0 -11
- package/dist-cli/block-csp.js +0 -84
- package/dist-cli/build-block-registry.js +0 -28
- package/dist-cli/convert-values.js +0 -222
- package/dist-cli/convert.js +0 -210
- package/dist-cli/data-sources.js +0 -167
- package/dist-cli/date-value.js +0 -46
- package/dist-cli/dev-shell-launcher.js +0 -226
- package/dist-cli/dev-shell-run.js +0 -72
- package/dist-cli/errors.js +0 -8
- package/dist-cli/materialize.js +0 -105
- package/dist-cli/ports.js +0 -20
- package/dist-cli/prebuilt.js +0 -23
- package/dist-cli/published-cli.js +0 -60
- package/dist-cli/resolve-bindings.js +0 -39
- package/dist-cli/runtime-error-client.js +0 -52
- package/dist-cli/serve-ui.js +0 -110
- package/dist-cli/shared-server.js +0 -70
- package/dist-cli/source-bindings.js +0 -17
- package/dist-cli/utils.js +0 -52
- package/dist-cli/vite-block-server.js +0 -125
- package/dist-cli/vite-middleware.js +0 -111
- package/dist-cli/worker-manifest.js +0 -141
package/dist-cli/block-csp.js
DELETED
|
@@ -1,84 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Network response policies for custom blocks served by the dev shell.
|
|
3
|
-
* Keep directives, media/font sources, and connection-allowlist semantics in sync with
|
|
4
|
-
* notion-next's production policy. Local origins and the HMR exception are documented below.
|
|
5
|
-
*
|
|
6
|
-
* @see https://github.com/makenotion/notion-next/blob/main/src/shared-customBlocks/customBlockBundleCsp.ts
|
|
7
|
-
*/
|
|
8
|
-
/**
|
|
9
|
-
* Keep these paths in sync with getNotionHostedMediaSources and FILE_S3_URLS.production
|
|
10
|
-
* in notion-next. Media exceptions do not grant fetch or script access.
|
|
11
|
-
*/
|
|
12
|
-
const notionMediaSources = [
|
|
13
|
-
"https://s3-us-west-2.amazonaws.com/public.notion-static.com/",
|
|
14
|
-
"https://s3.us-west-2.amazonaws.com/public.notion-static.com/",
|
|
15
|
-
"https://prod-files-secure.s3.us-west-2.amazonaws.com/",
|
|
16
|
-
"https://prod-files-secure-euc1.s3.eu-central-1.amazonaws.com/",
|
|
17
|
-
"https://prod-files-secure-apne1.s3.ap-northeast-1.amazonaws.com/",
|
|
18
|
-
"https://prod-files-secure-apne2.s3.ap-northeast-2.amazonaws.com/",
|
|
19
|
-
"https://s3-us-west-2.amazonaws.com/temporary.notion-static.com/",
|
|
20
|
-
"https://prod-notion-temporary-files-usw2.s3.us-west-2.amazonaws.com/",
|
|
21
|
-
"https://prod-notion-temporary-files-euc1.s3.eu-central-1.amazonaws.com/",
|
|
22
|
-
"https://prod-notion-temporary-files-apne1.s3.ap-northeast-1.amazonaws.com/",
|
|
23
|
-
"https://prod-notion-temporary-files-apne2.s3.ap-northeast-2.amazonaws.com/",
|
|
24
|
-
];
|
|
25
|
-
/** Builds the CSP and Connection-Allowlist headers for a local custom block response. */
|
|
26
|
-
export function buildCustomBlockDevShellResponseHeaders(args) {
|
|
27
|
-
return {
|
|
28
|
-
"Content-Security-Policy": buildCustomBlockDevShellCsp(args),
|
|
29
|
-
"Connection-Allowlist": buildCustomBlockDevShellConnectionAllowlist(args),
|
|
30
|
-
};
|
|
31
|
-
}
|
|
32
|
-
/**
|
|
33
|
-
* Mirrors notion-next's buildCustomBlockBundleCsp with local bundle and embedding origins.
|
|
34
|
-
* The extra WebSocket source permits Vite HMR without broadening other connection sources.
|
|
35
|
-
*/
|
|
36
|
-
function buildCustomBlockDevShellCsp(args) {
|
|
37
|
-
const { blockOrigin, shellOrigin, allowedNetworkOrigins, allowedFrameAncestors, } = args;
|
|
38
|
-
const approved = allowedNetworkOrigins.join(" ");
|
|
39
|
-
const media = notionMediaSources.join(" ");
|
|
40
|
-
// Production has no HMR connection. Allow only this block's WebSocket host and port
|
|
41
|
-
// so Vite can update modules without granting access to sibling blocks or the shell.
|
|
42
|
-
const hmr = new URL(blockOrigin);
|
|
43
|
-
hmr.protocol = "ws:";
|
|
44
|
-
return [
|
|
45
|
-
"default-src 'self'",
|
|
46
|
-
"worker-src 'none'",
|
|
47
|
-
"child-src 'none'",
|
|
48
|
-
`frame-src ${approved || "'none'"}`,
|
|
49
|
-
"object-src 'none'",
|
|
50
|
-
"manifest-src 'none'",
|
|
51
|
-
`media-src 'self' ${media} ${approved}`,
|
|
52
|
-
// The local HTTP origin replaces production's definition-specific bundle sources.
|
|
53
|
-
`connect-src ${blockOrigin} ${hmr.origin} ${approved}`,
|
|
54
|
-
`img-src 'self' data: ${media} ${approved}`,
|
|
55
|
-
`font-src 'self' data: https://fonts.gstatic.com ${approved}`,
|
|
56
|
-
"base-uri 'none'",
|
|
57
|
-
"form-action 'none'",
|
|
58
|
-
// Local hosts replace Notion's production app, relay, and mobile-shell ancestors.
|
|
59
|
-
`frame-ancestors 'self' ${shellOrigin} ${allowedFrameAncestors.join(" ")}`,
|
|
60
|
-
"script-src 'self' 'unsafe-inline'",
|
|
61
|
-
`style-src 'self' 'unsafe-inline' https://fonts.googleapis.com ${approved}`,
|
|
62
|
-
]
|
|
63
|
-
.map(directive => directive.trim())
|
|
64
|
-
.join("; ");
|
|
65
|
-
}
|
|
66
|
-
/**
|
|
67
|
-
* Mirrors notion-next's buildCustomBlockBundleConnectionAllowlist, including redirect and
|
|
68
|
-
* WebRTC blocking. The local block origin replaces production's bundle sources.
|
|
69
|
-
*/
|
|
70
|
-
function buildCustomBlockDevShellConnectionAllowlist(args) {
|
|
71
|
-
const sources = [
|
|
72
|
-
// WebSocket matching rewrites ws: to http:, so this also permits Vite HMR.
|
|
73
|
-
args.blockOrigin,
|
|
74
|
-
...notionMediaSources,
|
|
75
|
-
"https://fonts.googleapis.com",
|
|
76
|
-
"https://fonts.gstatic.com",
|
|
77
|
-
...args.allowedNetworkOrigins,
|
|
78
|
-
];
|
|
79
|
-
// CSP path prefixes need an explicit wildcard in Connection-Allowlist URLPatterns.
|
|
80
|
-
const patterns = sources.map(source => JSON.stringify(source === "*"
|
|
81
|
-
? "*://*:*/*"
|
|
82
|
-
: `${source}${source.endsWith("/") ? "" : "/"}*`));
|
|
83
|
-
return `(${patterns.join(" ")}); redirects=block; webrtc=block`;
|
|
84
|
-
}
|
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
import { DEFAULT_DEV_SHELL_PORT } from "./ports.js";
|
|
2
|
-
/** The registry for a worker's blocks, with unique localhost hostnames. */
|
|
3
|
-
export function buildBlockRegistry(blocks, port = DEFAULT_DEV_SHELL_PORT) {
|
|
4
|
-
const used = new Set();
|
|
5
|
-
return blocks.map(capability => {
|
|
6
|
-
const stem = capability.key
|
|
7
|
-
.toLowerCase()
|
|
8
|
-
.replace(/[^a-z0-9-]+/g, "-")
|
|
9
|
-
.replace(/^-+|-+$/g, "")
|
|
10
|
-
.slice(0, 63)
|
|
11
|
-
.replace(/-+$/g, "") || "block";
|
|
12
|
-
let hostname = stem;
|
|
13
|
-
let suffix = 1;
|
|
14
|
-
// Distinct capability keys can normalize to the same hostname.
|
|
15
|
-
// Add a suffix to keep hostnames unique within the 63-character label limit.
|
|
16
|
-
while (used.has(hostname)) {
|
|
17
|
-
const ending = `-${++suffix}`;
|
|
18
|
-
hostname = stem.slice(0, 63 - ending.length).replace(/-+$/g, "") + ending;
|
|
19
|
-
}
|
|
20
|
-
used.add(hostname);
|
|
21
|
-
return {
|
|
22
|
-
key: capability.key,
|
|
23
|
-
manifest: capability.config.manifest,
|
|
24
|
-
name: capability.key,
|
|
25
|
-
url: `http://${hostname}.localhost:${port}/`,
|
|
26
|
-
};
|
|
27
|
-
});
|
|
28
|
-
}
|
|
@@ -1,222 +0,0 @@
|
|
|
1
|
-
import * as v from "valibot";
|
|
2
|
-
import { localDateValueSchema } from "./date-value.js";
|
|
3
|
-
import { unreachable } from "./utils.js";
|
|
4
|
-
/**
|
|
5
|
-
* Convert one public API property value object to a local data source value.
|
|
6
|
-
* Returns undefined for empty values (blank cells are normal API output; the
|
|
7
|
-
* key is omitted from the row).
|
|
8
|
-
*/
|
|
9
|
-
export function convertPublicApiPropertyValue(publicType, value) {
|
|
10
|
-
if (typeof value !== "object" || value === null) {
|
|
11
|
-
return undefined;
|
|
12
|
-
}
|
|
13
|
-
const payload = value[publicType];
|
|
14
|
-
if (payload === null || payload === undefined) {
|
|
15
|
-
return undefined;
|
|
16
|
-
}
|
|
17
|
-
switch (publicType) {
|
|
18
|
-
case "title":
|
|
19
|
-
case "rich_text":
|
|
20
|
-
return payload
|
|
21
|
-
.map(part => part.plain_text ?? "")
|
|
22
|
-
.join("");
|
|
23
|
-
case "number":
|
|
24
|
-
return payload;
|
|
25
|
-
case "checkbox":
|
|
26
|
-
return payload;
|
|
27
|
-
case "url":
|
|
28
|
-
case "email":
|
|
29
|
-
case "phone_number":
|
|
30
|
-
return payload;
|
|
31
|
-
case "select":
|
|
32
|
-
case "status":
|
|
33
|
-
return payload.name;
|
|
34
|
-
case "multi_select":
|
|
35
|
-
return payload.map(option => option.name ?? "");
|
|
36
|
-
case "date":
|
|
37
|
-
return publicDateToLocal(payload);
|
|
38
|
-
case "people":
|
|
39
|
-
return payload.map(user => ({
|
|
40
|
-
id: user.id,
|
|
41
|
-
table: "notion_user",
|
|
42
|
-
}));
|
|
43
|
-
case "files":
|
|
44
|
-
return filesToText(payload);
|
|
45
|
-
case "relation":
|
|
46
|
-
return payload.map(target => ({
|
|
47
|
-
id: target.id,
|
|
48
|
-
table: "block",
|
|
49
|
-
}));
|
|
50
|
-
case "unique_id": {
|
|
51
|
-
const uniqueId = payload;
|
|
52
|
-
return uniqueId.prefix
|
|
53
|
-
? `${uniqueId.prefix}-${uniqueId.number}`
|
|
54
|
-
: String(uniqueId.number);
|
|
55
|
-
}
|
|
56
|
-
// The production host still serializes formula, rollup, and
|
|
57
|
-
// last_visited_time as plain text. Match it so fixtures predict what a
|
|
58
|
-
// block receives from the real host.
|
|
59
|
-
case "formula":
|
|
60
|
-
return formulaToText(payload);
|
|
61
|
-
case "rollup":
|
|
62
|
-
return rollupToText(payload);
|
|
63
|
-
case "last_visited_time":
|
|
64
|
-
return payload;
|
|
65
|
-
case "created_time":
|
|
66
|
-
case "last_edited_time":
|
|
67
|
-
return timestampToLocal(payload);
|
|
68
|
-
case "created_by":
|
|
69
|
-
case "last_edited_by":
|
|
70
|
-
return [{ id: payload.id, table: "notion_user" }];
|
|
71
|
-
case "verification":
|
|
72
|
-
return payload.state;
|
|
73
|
-
case "button":
|
|
74
|
-
// Buttons carry no data; there is nothing to sample.
|
|
75
|
-
return undefined;
|
|
76
|
-
case "place":
|
|
77
|
-
case "location":
|
|
78
|
-
// No public API payload converter yet: keep something inspectable.
|
|
79
|
-
return JSON.stringify(payload);
|
|
80
|
-
default:
|
|
81
|
-
return unreachable(publicType);
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
function filesToText(files) {
|
|
85
|
-
return files
|
|
86
|
-
.map(file => file.name ?? "")
|
|
87
|
-
.filter(name => name.length > 0)
|
|
88
|
-
.join(", ");
|
|
89
|
-
}
|
|
90
|
-
function formulaToText(formula) {
|
|
91
|
-
switch (formula.type) {
|
|
92
|
-
case "string":
|
|
93
|
-
return formula.string ?? undefined;
|
|
94
|
-
case "number":
|
|
95
|
-
return formula.number != null ? String(formula.number) : undefined;
|
|
96
|
-
case "boolean":
|
|
97
|
-
return formula.boolean != null ? String(formula.boolean) : undefined;
|
|
98
|
-
case "date":
|
|
99
|
-
return formula.date ? dateToText(formula.date) : undefined;
|
|
100
|
-
default:
|
|
101
|
-
return undefined;
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
function rollupToText(rollup) {
|
|
105
|
-
switch (rollup.type) {
|
|
106
|
-
case "number":
|
|
107
|
-
return rollup.number != null ? String(rollup.number) : undefined;
|
|
108
|
-
case "date":
|
|
109
|
-
return rollup.date ? dateToText(rollup.date) : undefined;
|
|
110
|
-
default: {
|
|
111
|
-
const raw = rollup.type === undefined
|
|
112
|
-
? undefined
|
|
113
|
-
: rollup[rollup.type];
|
|
114
|
-
return raw === null || raw === undefined ? undefined : JSON.stringify(raw);
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
/**
|
|
119
|
-
* Best-effort text for a public API date payload: matches production's
|
|
120
|
-
* string shape, not its exact date formatting.
|
|
121
|
-
*/
|
|
122
|
-
function dateToText(date) {
|
|
123
|
-
return date.end ? `${date.start} → ${date.end}` : date.start;
|
|
124
|
-
}
|
|
125
|
-
/**
|
|
126
|
-
* Public API date value (`{ start, end, time_zone }`, ISO 8601 strings) to
|
|
127
|
-
* the local `NotionDateValue` shape. Date-only starts become `date` /
|
|
128
|
-
* `daterange`; timestamped starts become `datetime` / `datetimerange`.
|
|
129
|
-
*/
|
|
130
|
-
function publicDateToLocal(date) {
|
|
131
|
-
const start = date.start;
|
|
132
|
-
const end = date.end ?? undefined;
|
|
133
|
-
const timeZone = date.time_zone ?? undefined;
|
|
134
|
-
if (!start.includes("T")) {
|
|
135
|
-
return end === undefined
|
|
136
|
-
? { type: "date", start_date: start.slice(0, 10) }
|
|
137
|
-
: {
|
|
138
|
-
type: "daterange",
|
|
139
|
-
start_date: start.slice(0, 10),
|
|
140
|
-
end_date: end.slice(0, 10),
|
|
141
|
-
};
|
|
142
|
-
}
|
|
143
|
-
if (end === undefined) {
|
|
144
|
-
return {
|
|
145
|
-
type: "datetime",
|
|
146
|
-
start_date: start.slice(0, 10),
|
|
147
|
-
start_time: start.slice(11, 16),
|
|
148
|
-
...(timeZone !== undefined ? { time_zone: timeZone } : {}),
|
|
149
|
-
};
|
|
150
|
-
}
|
|
151
|
-
return {
|
|
152
|
-
type: "datetimerange",
|
|
153
|
-
start_date: start.slice(0, 10),
|
|
154
|
-
start_time: start.slice(11, 16),
|
|
155
|
-
end_date: end.slice(0, 10),
|
|
156
|
-
end_time: end.slice(11, 16),
|
|
157
|
-
...(timeZone !== undefined ? { time_zone: timeZone } : {}),
|
|
158
|
-
};
|
|
159
|
-
}
|
|
160
|
-
function timestampToLocal(timestamp) {
|
|
161
|
-
return timestamp.includes("T")
|
|
162
|
-
? {
|
|
163
|
-
type: "datetime",
|
|
164
|
-
start_date: timestamp.slice(0, 10),
|
|
165
|
-
start_time: timestamp.slice(11, 16),
|
|
166
|
-
}
|
|
167
|
-
: { type: "date", start_date: timestamp.slice(0, 10) };
|
|
168
|
-
}
|
|
169
|
-
const stringValue = v.string();
|
|
170
|
-
const numberValue = v.pipe(v.number(), v.finite());
|
|
171
|
-
const booleanValue = v.boolean();
|
|
172
|
-
const stringArrayValue = v.array(v.string());
|
|
173
|
-
const pointerArrayValue = v.array(v.object({ id: v.string(), table: v.string() }));
|
|
174
|
-
const anyLocalValue = v.union([
|
|
175
|
-
stringValue,
|
|
176
|
-
numberValue,
|
|
177
|
-
booleanValue,
|
|
178
|
-
localDateValueSchema,
|
|
179
|
-
stringArrayValue,
|
|
180
|
-
pointerArrayValue,
|
|
181
|
-
]);
|
|
182
|
-
const _valueUnionsMatch = true;
|
|
183
|
-
void _valueUnionsMatch;
|
|
184
|
-
/**
|
|
185
|
-
* The value shape each property type must hold in a local file. Mirrors the
|
|
186
|
-
* production host's serialization: the types production still serializes as
|
|
187
|
-
* text are pinned to strings here, deliberately stricter than the dev
|
|
188
|
-
* shell's binding-time checks.
|
|
189
|
-
*/
|
|
190
|
-
const VALUE_SCHEMAS = {
|
|
191
|
-
title: stringValue,
|
|
192
|
-
rich_text: stringValue,
|
|
193
|
-
url: stringValue,
|
|
194
|
-
email: stringValue,
|
|
195
|
-
phone_number: stringValue,
|
|
196
|
-
select: stringValue,
|
|
197
|
-
status: stringValue,
|
|
198
|
-
number: numberValue,
|
|
199
|
-
checkbox: booleanValue,
|
|
200
|
-
multi_select: stringArrayValue,
|
|
201
|
-
date: localDateValueSchema,
|
|
202
|
-
created_time: localDateValueSchema,
|
|
203
|
-
last_edited_time: localDateValueSchema,
|
|
204
|
-
people: pointerArrayValue,
|
|
205
|
-
relation: pointerArrayValue,
|
|
206
|
-
created_by: pointerArrayValue,
|
|
207
|
-
last_edited_by: pointerArrayValue,
|
|
208
|
-
unique_id: stringValue,
|
|
209
|
-
files: stringValue,
|
|
210
|
-
formula: stringValue,
|
|
211
|
-
rollup: stringValue,
|
|
212
|
-
verification: stringValue,
|
|
213
|
-
place: stringValue,
|
|
214
|
-
location: stringValue,
|
|
215
|
-
last_visited_time: stringValue,
|
|
216
|
-
};
|
|
217
|
-
export function matchesPropertyType(value, type) {
|
|
218
|
-
return v.is(VALUE_SCHEMAS[type] ?? anyLocalValue, value);
|
|
219
|
-
}
|
|
220
|
-
export function isDataSourceValue(value) {
|
|
221
|
-
return v.is(anyLocalValue, value);
|
|
222
|
-
}
|
package/dist-cli/convert.js
DELETED
|
@@ -1,210 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* `convert` subcommand: translate a sampled Notion data source (public API
|
|
3
|
-
* shapes: schema `properties`, query `results`) into the dev shell's local
|
|
4
|
-
* JSON data source format, validate the result, and print it to stdout.
|
|
5
|
-
* `ntn workers customblocks sample` pipes through this via stdin; it also runs
|
|
6
|
-
* standalone: `npx @notionhq/custom-blocks-dev-shell convert --in sample.json`.
|
|
7
|
-
*/
|
|
8
|
-
import { readFileSync } from "node:fs";
|
|
9
|
-
import * as v from "valibot";
|
|
10
|
-
import { convertPublicApiPropertyValue, isDataSourceValue, matchesPropertyType, } from "./convert-values.js";
|
|
11
|
-
import { NOTION_PROPERTY_TYPES, sourceFileSchema } from "./data-sources.js";
|
|
12
|
-
import { formatUnknownError } from "./errors.js";
|
|
13
|
-
import { claimUniqueKey, parseCliArgs, slugify } from "./utils.js";
|
|
14
|
-
const SUPPORTED_TYPES = new Set(NOTION_PROPERTY_TYPES);
|
|
15
|
-
/** The spelling of "text" in the local file format. */
|
|
16
|
-
const UNSUPPORTED_TYPE_FALLBACK = "rich_text";
|
|
17
|
-
export function parseConvertArgs(argv) {
|
|
18
|
-
const args = {
|
|
19
|
-
input: undefined,
|
|
20
|
-
name: undefined,
|
|
21
|
-
};
|
|
22
|
-
const rejectUnknown = (arg) => {
|
|
23
|
-
throw new Error(`Unknown convert option "${arg}". Supported: --in <file>, --name <name>.`);
|
|
24
|
-
};
|
|
25
|
-
parseCliArgs({
|
|
26
|
-
argv,
|
|
27
|
-
handlers: {
|
|
28
|
-
"--in": value => {
|
|
29
|
-
args.input = value;
|
|
30
|
-
},
|
|
31
|
-
"--name": value => {
|
|
32
|
-
args.name = value;
|
|
33
|
-
},
|
|
34
|
-
},
|
|
35
|
-
onUnknown: rejectUnknown,
|
|
36
|
-
// This command accepts no positional arguments.
|
|
37
|
-
onPositional: rejectUnknown,
|
|
38
|
-
});
|
|
39
|
-
return args;
|
|
40
|
-
}
|
|
41
|
-
const sampleInputSchema = v.pipe(v.looseObject({
|
|
42
|
-
name: v.optional(v.string()),
|
|
43
|
-
properties: v.optional(v.record(v.string(), v.looseObject({ type: v.string() }))),
|
|
44
|
-
results: v.optional(v.array(v.looseObject({
|
|
45
|
-
id: v.string(),
|
|
46
|
-
properties: v.optional(v.record(v.string(), v.unknown())),
|
|
47
|
-
}))),
|
|
48
|
-
}), v.check(input => input.properties !== undefined || input.results !== undefined, "expected a schema under `properties` and/or sampled pages under `results`"));
|
|
49
|
-
/**
|
|
50
|
-
* Convert a sampled data source (public API shapes) into a local data source
|
|
51
|
-
* object. The input carries the schema under `properties` and/or sampled
|
|
52
|
-
* pages under `results` (query output verbatim). The emitted object always
|
|
53
|
-
* carries a `schema` — taken from `properties` when present, otherwise
|
|
54
|
-
* inferred from the row values — because the shell derives table columns and
|
|
55
|
-
* bindings from the schema alone.
|
|
56
|
-
*/
|
|
57
|
-
export function convertSample(input, overrides = {}) {
|
|
58
|
-
const parsed = v.safeParse(sampleInputSchema, input);
|
|
59
|
-
if (!parsed.success) {
|
|
60
|
-
const issue = parsed.issues[0];
|
|
61
|
-
const path = v.getDotPath(issue);
|
|
62
|
-
throw new Error(`Input is not a sampled data source: ${path ? `${path}: ` : ""}${issue.message}`);
|
|
63
|
-
}
|
|
64
|
-
const sample = parsed.output;
|
|
65
|
-
const warnings = [];
|
|
66
|
-
const mappings = buildPropertyMappings(sample.properties, sample.results, warnings);
|
|
67
|
-
const name = overrides.name ?? (sample.name || undefined);
|
|
68
|
-
const schema = {};
|
|
69
|
-
for (const mapping of mappings.values()) {
|
|
70
|
-
schema[mapping.key] = { name: mapping.name, type: mapping.type };
|
|
71
|
-
}
|
|
72
|
-
const source = {
|
|
73
|
-
type: "syncedFromProd",
|
|
74
|
-
...(name !== undefined ? { name } : {}),
|
|
75
|
-
schema,
|
|
76
|
-
rows: (sample.results ?? []).map(row => convertRow(row, mappings)),
|
|
77
|
-
};
|
|
78
|
-
validateSource(source);
|
|
79
|
-
return { source, warnings };
|
|
80
|
-
}
|
|
81
|
-
/**
|
|
82
|
-
* One mapping per public property name. For schema-only and full samples the
|
|
83
|
-
* mappings come from `properties`; for rows-only samples they are derived
|
|
84
|
-
* from the `type` field each row value carries.
|
|
85
|
-
*/
|
|
86
|
-
function buildPropertyMappings(properties, sampledRows, warnings) {
|
|
87
|
-
const mappings = new Map();
|
|
88
|
-
// `id` is the row identifier; a property named "ID" must not overwrite it.
|
|
89
|
-
const usedKeys = new Set(["id"]);
|
|
90
|
-
const add = (propertyName, publicType) => {
|
|
91
|
-
if (mappings.has(propertyName)) {
|
|
92
|
-
return;
|
|
93
|
-
}
|
|
94
|
-
const unsupported = !SUPPORTED_TYPES.has(publicType);
|
|
95
|
-
if (unsupported) {
|
|
96
|
-
warnings.push(`Property ${JSON.stringify(propertyName)}: public API type ` +
|
|
97
|
-
`${JSON.stringify(publicType)} is not supported by custom blocks; ` +
|
|
98
|
-
`converted to text ("${UNSUPPORTED_TYPE_FALLBACK}") with the ` +
|
|
99
|
-
`placeholder value ${JSON.stringify(`unsupported type: ${publicType}`)}.`);
|
|
100
|
-
}
|
|
101
|
-
mappings.set(propertyName, {
|
|
102
|
-
key: claimUniqueKey(slugify(propertyName) ?? "property", usedKeys),
|
|
103
|
-
name: propertyName,
|
|
104
|
-
type: unsupported ? UNSUPPORTED_TYPE_FALLBACK : publicType,
|
|
105
|
-
publicType,
|
|
106
|
-
unsupported,
|
|
107
|
-
});
|
|
108
|
-
};
|
|
109
|
-
for (const [propertyName, property] of Object.entries(properties ?? {})) {
|
|
110
|
-
add(propertyName, property.type);
|
|
111
|
-
}
|
|
112
|
-
for (const row of sampledRows ?? []) {
|
|
113
|
-
for (const [propertyName, value] of Object.entries(row.properties ?? {})) {
|
|
114
|
-
const publicType = value?.type;
|
|
115
|
-
if (typeof publicType === "string") {
|
|
116
|
-
add(propertyName, publicType);
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
return mappings;
|
|
121
|
-
}
|
|
122
|
-
function convertRow(row, mappings) {
|
|
123
|
-
const converted = { id: row.id };
|
|
124
|
-
for (const [propertyName, value] of Object.entries(row.properties ?? {})) {
|
|
125
|
-
const mapping = mappings.get(propertyName);
|
|
126
|
-
if (mapping === undefined) {
|
|
127
|
-
continue;
|
|
128
|
-
}
|
|
129
|
-
if (mapping.unsupported) {
|
|
130
|
-
converted[mapping.key] = `unsupported type: ${mapping.publicType}`;
|
|
131
|
-
continue;
|
|
132
|
-
}
|
|
133
|
-
const local = convertPublicApiPropertyValue(mapping.publicType, value);
|
|
134
|
-
if (local !== undefined) {
|
|
135
|
-
converted[mapping.key] = local;
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
return converted;
|
|
139
|
-
}
|
|
140
|
-
/**
|
|
141
|
-
* Validate the built source the same way the dev shell will at spin-up, plus
|
|
142
|
-
* a row-value pass the loader doesn't do: every emitted value must match its
|
|
143
|
-
* declared schema type. Failures here are conversion bugs or malformed input;
|
|
144
|
-
* the command must never print a file the shell would reject.
|
|
145
|
-
*/
|
|
146
|
-
export function validateSource(source) {
|
|
147
|
-
const hasSchema = source.schema !== undefined;
|
|
148
|
-
const result = v.safeParse(sourceFileSchema, source);
|
|
149
|
-
if (!result.success) {
|
|
150
|
-
const issue = result.issues[0];
|
|
151
|
-
const path = v.getDotPath(issue);
|
|
152
|
-
throw new Error(`Converted data source is invalid: ${path ? `${path}: ` : ""}${issue.message}`);
|
|
153
|
-
}
|
|
154
|
-
const schema = (source.schema ?? {});
|
|
155
|
-
const rows = (source.rows ?? []);
|
|
156
|
-
const issues = [];
|
|
157
|
-
for (const row of rows) {
|
|
158
|
-
for (const [key, value] of Object.entries(row)) {
|
|
159
|
-
if (key === "id") {
|
|
160
|
-
continue;
|
|
161
|
-
}
|
|
162
|
-
const declared = hasSchema ? schema[key] : undefined;
|
|
163
|
-
if (hasSchema && declared === undefined) {
|
|
164
|
-
issues.push(`row ${JSON.stringify(row.id)}: ${JSON.stringify(key)} is not in the schema`);
|
|
165
|
-
continue;
|
|
166
|
-
}
|
|
167
|
-
const matches = declared
|
|
168
|
-
? matchesPropertyType(value, declared.type)
|
|
169
|
-
: isDataSourceValue(value);
|
|
170
|
-
if (!matches) {
|
|
171
|
-
issues.push(`row ${JSON.stringify(row.id)}: ${JSON.stringify(key)} does not match ${declared ? `type ${JSON.stringify(declared.type)}` : "any supported value shape"}`);
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
if (issues.length > 0) {
|
|
176
|
-
throw new Error(`Converted rows are invalid: ${issues.join("; ")}`);
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
export async function runConvert(argv) {
|
|
180
|
-
const args = parseConvertArgs(argv);
|
|
181
|
-
let raw;
|
|
182
|
-
if (args.input !== undefined) {
|
|
183
|
-
try {
|
|
184
|
-
raw = readFileSync(args.input, "utf-8");
|
|
185
|
-
}
|
|
186
|
-
catch (error) {
|
|
187
|
-
throw new Error(`Could not read ${args.input}: ${formatUnknownError(error)}`);
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
else {
|
|
191
|
-
if (process.stdin.isTTY) {
|
|
192
|
-
throw new Error("No input: pipe `ntn workers customblocks sample` output to convert, or pass --in <file>.");
|
|
193
|
-
}
|
|
194
|
-
raw = readFileSync(0, "utf-8");
|
|
195
|
-
}
|
|
196
|
-
let parsed;
|
|
197
|
-
try {
|
|
198
|
-
parsed = JSON.parse(raw);
|
|
199
|
-
}
|
|
200
|
-
catch (error) {
|
|
201
|
-
throw new Error(`Input is not valid JSON — ${formatUnknownError(error)}`);
|
|
202
|
-
}
|
|
203
|
-
const { source, warnings } = convertSample(parsed, {
|
|
204
|
-
...(args.name !== undefined ? { name: args.name } : {}),
|
|
205
|
-
});
|
|
206
|
-
for (const warning of warnings) {
|
|
207
|
-
console.warn(warning);
|
|
208
|
-
}
|
|
209
|
-
process.stdout.write(`${JSON.stringify(source, null, "\t")}\n`);
|
|
210
|
-
}
|