@notionhq/custom-blocks 0.0.61 → 0.0.62

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.
@@ -0,0 +1,187 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ import { packDirToTarGz } from "./tar.js";
6
+ export const BUILD_OUTPUT_SENTINEL = "<__notion_custom_block__>";
7
+ export const BUILD_OUTPUT_SENTINEL_CLOSE = "</__notion_custom_block__>";
8
+ const WORKER_ENTRY = "dist/index.js";
9
+ /**
10
+ * Build every `_tag: "custom_block"` view declared by the worker.
11
+ *
12
+ * Imports the worker bundle (`<cwd>/dist/index.js`), reads its runtime manifest,
13
+ * and runs the command specified (default `npm run build`)
14
+ */
15
+ export async function buildCustomBlocks(args) {
16
+ const projectRoot = args.cwd ?? process.cwd();
17
+ const entryPath = path.resolve(projectRoot, WORKER_ENTRY);
18
+ const outDir = path.resolve(args.out);
19
+ const blocks = await readCustomBlocks(entryPath);
20
+ if (blocks.length === 0) {
21
+ return { blocks: [] };
22
+ }
23
+ const built = [];
24
+ for (const block of blocks) {
25
+ const bundleDir = path.join(outDir, block.key);
26
+ buildCustomBlock({ block, projectRoot, bundleDir });
27
+ const { checksumCrc32 } = packDirToTarGz(bundleDir);
28
+ built.push({ key: block.key, checksumCrc32, bundleDir });
29
+ }
30
+ return { blocks: built };
31
+ }
32
+ /** Print the build output as the sentinel-wrapped single-line JSON contract. */
33
+ export function printBuildOutput(output) {
34
+ process.stdout.write(`${BUILD_OUTPUT_SENTINEL}${JSON.stringify(output)}${BUILD_OUTPUT_SENTINEL_CLOSE}\n`);
35
+ }
36
+ async function readCustomBlocks(entryPath) {
37
+ const mod = await import(pathToFileURL(entryPath).href);
38
+ const worker = resolveWorker(mod);
39
+ const manifest = readProp(worker, "manifest");
40
+ const capabilities = readProp(manifest, "capabilities");
41
+ if (!Array.isArray(capabilities)) {
42
+ throw new Error(`worker manifest at ${entryPath} has no capabilities array`);
43
+ }
44
+ const blocks = [];
45
+ for (const capability of capabilities) {
46
+ const block = asCustomBlock(capability);
47
+ if (block) {
48
+ blocks.push(block);
49
+ }
50
+ }
51
+ return blocks;
52
+ }
53
+ function resolveWorker(mod) {
54
+ const top = readProp(mod, "default");
55
+ if (top === undefined) {
56
+ throw new Error("worker module has no default export");
57
+ }
58
+ const nested = readProp(top, "default");
59
+ return nested ?? top;
60
+ }
61
+ function readProp(value, key) {
62
+ if (typeof value !== "object" || value === null) {
63
+ return undefined;
64
+ }
65
+ return value[key];
66
+ }
67
+ function asCustomBlock(value) {
68
+ if (typeof value !== "object" || value === null) {
69
+ return undefined;
70
+ }
71
+ const record = value;
72
+ if (record._tag !== "custom_block") {
73
+ return undefined;
74
+ }
75
+ if (typeof record.key !== "string") {
76
+ throw new Error("custom_block capability is missing a string key");
77
+ }
78
+ const config = record.config;
79
+ if (typeof config !== "object" || config === null) {
80
+ throw new Error(`custom_block "${record.key}" is missing config`);
81
+ }
82
+ const source = parseSource(record.key, config.source);
83
+ const dataSources = config.dataSources;
84
+ const manifest = config.manifest;
85
+ return {
86
+ key: record.key,
87
+ config: {
88
+ source,
89
+ ...(isStringRecord(dataSources) ? { dataSources } : {}),
90
+ manifest,
91
+ },
92
+ };
93
+ }
94
+ function parseSource(key, value) {
95
+ if (typeof value !== "object" || value === null) {
96
+ throw new Error(`custom_block "${key}" is missing a source`);
97
+ }
98
+ const source = value;
99
+ if (source.type === "project") {
100
+ if (typeof source.path !== "string") {
101
+ throw new Error(`custom_block "${key}" project source is missing a string path`);
102
+ }
103
+ return {
104
+ type: "project",
105
+ path: source.path,
106
+ ...(typeof source.command === "string"
107
+ ? { command: source.command }
108
+ : {}),
109
+ ...(typeof source.output === "string" ? { output: source.output } : {}),
110
+ };
111
+ }
112
+ if (source.type === "static") {
113
+ if (typeof source.path !== "string") {
114
+ throw new Error(`custom_block "${key}" static source is missing a string path`);
115
+ }
116
+ return { type: "static", path: source.path };
117
+ }
118
+ throw new Error(`custom_block "${key}" has an unsupported source type "${String(source.type)}" — this worker may need a newer @notionhq/workers`);
119
+ }
120
+ function isStringRecord(value) {
121
+ if (typeof value !== "object" || value === null) {
122
+ return false;
123
+ }
124
+ return Object.values(value).every(v => typeof v === "string");
125
+ }
126
+ function buildCustomBlock(args) {
127
+ const { block, projectRoot, bundleDir } = args;
128
+ const sourceDir = resolveSourceDir(block.key, block.config.source, projectRoot);
129
+ fs.rmSync(bundleDir, { recursive: true, force: true });
130
+ fs.mkdirSync(bundleDir, { recursive: true });
131
+ fs.cpSync(sourceDir, bundleDir, { recursive: true });
132
+ }
133
+ const DEFAULT_BUILD_COMMAND = "npm run build";
134
+ const DEFAULT_OUTPUT_DIR = "dist";
135
+ function resolveSourceDir(key, source, projectRoot) {
136
+ if (source.type === "static") {
137
+ const dir = path.resolve(projectRoot, source.path);
138
+ if (!fs.existsSync(dir)) {
139
+ throw new Error(`custom_block "${key}" static dir not found: ${dir}`);
140
+ }
141
+ return dir;
142
+ }
143
+ const projectDir = path.resolve(projectRoot, source.path);
144
+ if (!fs.existsSync(projectDir)) {
145
+ throw new Error(`custom_block "${key}" project dir not found: ${projectDir}`);
146
+ }
147
+ installProjectDeps(key, projectDir);
148
+ const command = source.command ?? DEFAULT_BUILD_COMMAND;
149
+ runCommand(key, command, projectDir);
150
+ const outputDir = path.resolve(projectDir, source.output ?? DEFAULT_OUTPUT_DIR);
151
+ if (!fs.existsSync(outputDir)) {
152
+ throw new Error(`custom_block "${key}" build command "${command}" produced no output at ${outputDir}`);
153
+ }
154
+ return outputDir;
155
+ }
156
+ /**
157
+ * Install a `project` source's own dependencies before building it. `npm ci`
158
+ * when a lockfile is present (faster + deterministic), else `npm install`. No-op
159
+ * when the project has no package.json.
160
+ */
161
+ function installProjectDeps(key, projectDir) {
162
+ if (!fs.existsSync(path.join(projectDir, "package.json"))) {
163
+ return;
164
+ }
165
+ const hasLockfile = fs.existsSync(path.join(projectDir, "package-lock.json"));
166
+ runCommand(key, hasLockfile ? "npm ci" : "npm install", projectDir);
167
+ }
168
+ /**
169
+ * Run a shell command in `cwd`. The child's stdout/stderr are forwarded to our
170
+ * stderr so build/install logs never contaminate the sentinel-wrapped JSON
171
+ * contract this tool writes to stdout.
172
+ */
173
+ function runCommand(key, command, cwd) {
174
+ const result = spawnSync(command, { cwd, shell: true, encoding: "utf8" });
175
+ if (result.stdout) {
176
+ process.stderr.write(result.stdout);
177
+ }
178
+ if (result.stderr) {
179
+ process.stderr.write(result.stderr);
180
+ }
181
+ if (result.error) {
182
+ throw new Error(`custom_block "${key}" build command "${command}" failed to start: ${result.error.message}`);
183
+ }
184
+ if (result.status !== 0) {
185
+ throw new Error(`custom_block "${key}" build command "${command}" exited with code ${String(result.status)}`);
186
+ }
187
+ }
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env node
2
+ import { buildCustomBlocks, printBuildOutput } from "./build.js";
3
+ import { parseUploadsInput, uploadViews } from "./upload.js";
4
+ export async function main(argv) {
5
+ const [command, ...rest] = argv;
6
+ switch (command) {
7
+ case "build":
8
+ return runBuild(rest);
9
+ case "upload":
10
+ return runUpload(rest);
11
+ default:
12
+ printUsage();
13
+ return command === undefined ? 0 : 1;
14
+ }
15
+ }
16
+ async function runBuild(args) {
17
+ const flags = parseFlags(args);
18
+ const out = flags.out;
19
+ if (out === undefined) {
20
+ process.stderr.write("usage: notion-custom-blocks build --out <dir>\n");
21
+ return 1;
22
+ }
23
+ const output = await buildCustomBlocks({ out });
24
+ printBuildOutput(output);
25
+ return 0;
26
+ }
27
+ async function runUpload(args) {
28
+ const flags = parseFlags(args);
29
+ const raw = flags.uploads;
30
+ if (raw === undefined) {
31
+ process.stderr.write("usage: notion-custom-blocks upload --uploads '<json>'\n");
32
+ return 1;
33
+ }
34
+ const uploads = parseUploadsInput(raw);
35
+ const output = await uploadViews(uploads);
36
+ process.stdout.write(`${JSON.stringify(output)}\n`);
37
+ return 0;
38
+ }
39
+ function parseFlags(args) {
40
+ const flags = {};
41
+ for (let i = 0; i < args.length; i++) {
42
+ const arg = args[i];
43
+ if (arg === undefined || !arg.startsWith("--")) {
44
+ continue;
45
+ }
46
+ const name = arg.slice(2);
47
+ const value = args[i + 1];
48
+ if (value === undefined) {
49
+ continue;
50
+ }
51
+ flags[name] = value;
52
+ i++;
53
+ }
54
+ return flags;
55
+ }
56
+ function printUsage() {
57
+ process.stderr.write("Invalid command. See notion-custom-blocks source.");
58
+ }
59
+ main(process.argv.slice(2))
60
+ .then(code => {
61
+ process.exitCode = code;
62
+ })
63
+ .catch((error) => {
64
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
65
+ process.exitCode = 1;
66
+ });
@@ -0,0 +1,102 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import * as zlib from "node:zlib";
4
+ /**
5
+ * Deterministic gzipped-tarball packing for custom-block bundles, shared by the
6
+ * `build` and `upload` phases.
7
+ */
8
+ const BLOCK_SIZE = 512;
9
+ /**
10
+ * Pack a directory into a deterministic gzipped tarball and return both the
11
+ * bytes and their base64 big-endian crc32 checksum (the form
12
+ * `CreateCustomBlockDeploy` signs into the presigned PUT URL).
13
+ */
14
+ export function packDirToTarGz(dir) {
15
+ const entries = collectFiles(dir);
16
+ const tar = writeUstarArchive(entries);
17
+ const tarGz = zlib.gzipSync(tar, {
18
+ level: zlib.constants.Z_BEST_COMPRESSION,
19
+ });
20
+ // Zero the gzip header's MTIME field (bytes 4..7) so repeated packs of the
21
+ // same input are byte-identical. The build phase's crc32 must match the
22
+ // bytes the upload phase PUTs, and gzip otherwise stamps the current time.
23
+ if (tarGz.length >= 8) {
24
+ tarGz.writeUInt32LE(0, 4);
25
+ }
26
+ return { tarGz, checksumCrc32: crc32Base64(tarGz) };
27
+ }
28
+ /** Base64-encoded big-endian crc32, matching the server's `CRC32_BASE64_REGEX`. */
29
+ export function crc32Base64(data) {
30
+ const checksum = zlib.crc32(data) >>> 0;
31
+ const buf = Buffer.alloc(4);
32
+ buf.writeUInt32BE(checksum);
33
+ return buf.toString("base64");
34
+ }
35
+ /** Recursively collect regular files under `dir`, sorted by archive path. */
36
+ function collectFiles(dir) {
37
+ const entries = [];
38
+ function walk(absDir, relDir) {
39
+ const dirents = fs.readdirSync(absDir, { withFileTypes: true });
40
+ for (const dirent of dirents) {
41
+ const abs = path.join(absDir, dirent.name);
42
+ const rel = relDir === "" ? dirent.name : `${relDir}/${dirent.name}`;
43
+ if (dirent.isDirectory()) {
44
+ walk(abs, rel);
45
+ }
46
+ else if (dirent.isFile()) {
47
+ entries.push({ name: rel, contents: fs.readFileSync(abs) });
48
+ }
49
+ }
50
+ }
51
+ walk(dir, "");
52
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
53
+ return entries;
54
+ }
55
+ /** Serialize entries as a minimal POSIX ustar archive. */
56
+ function writeUstarArchive(entries) {
57
+ const chunks = [];
58
+ for (const entry of entries) {
59
+ chunks.push(writeUstarHeader(entry.name, entry.contents.length));
60
+ chunks.push(entry.contents);
61
+ const remainder = entry.contents.length % BLOCK_SIZE;
62
+ if (remainder !== 0) {
63
+ chunks.push(Buffer.alloc(BLOCK_SIZE - remainder));
64
+ }
65
+ }
66
+ // Two zero blocks mark end-of-archive.
67
+ chunks.push(Buffer.alloc(BLOCK_SIZE * 2));
68
+ return Buffer.concat(chunks);
69
+ }
70
+ function writeUstarHeader(name, size) {
71
+ const header = Buffer.alloc(BLOCK_SIZE);
72
+ const nameBytes = Buffer.from(name, "utf8");
73
+ if (nameBytes.length > 100) {
74
+ // ustar splits long paths into name/prefix; keep bundles simple by
75
+ // requiring short paths rather than emitting a GNU/PAX extension.
76
+ throw new Error(`tar entry path too long (max 100 bytes): ${name}`);
77
+ }
78
+ nameBytes.copy(header, 0);
79
+ writeOctal(header, 100, 8, 0o644); // mode
80
+ writeOctal(header, 108, 8, 0); // uid
81
+ writeOctal(header, 116, 8, 0); // gid
82
+ writeOctal(header, 124, 12, size); // size
83
+ writeOctal(header, 136, 12, 0); // mtime
84
+ header.write("0", 156, 1, "ascii"); // typeflag: regular file
85
+ header.write("ustar\0", 257, 6, "ascii"); // magic
86
+ header.write("00", 263, 2, "ascii"); // version
87
+ // Checksum field: spaces during computation, then octal value.
88
+ header.fill(" ", 148, 156);
89
+ let checksum = 0;
90
+ for (let i = 0; i < BLOCK_SIZE; i++) {
91
+ checksum += header[i] ?? 0;
92
+ }
93
+ header.write(checksum.toString(8).padStart(6, "0"), 148, 6, "ascii");
94
+ header.write("\0 ", 154, 2, "ascii");
95
+ return header;
96
+ }
97
+ function writeOctal(header, offset, length, value) {
98
+ // Numeric fields are octal ASCII, null-terminated, right-justified.
99
+ const str = value.toString(8).padStart(length - 1, "0");
100
+ header.write(str, offset, length - 1, "ascii");
101
+ header.write("\0", offset + length - 1, 1, "ascii");
102
+ }
@@ -0,0 +1,60 @@
1
+ import { packDirToTarGz } from "./tar.js";
2
+ const DEFAULT_DEPS = { fetch: globalThis.fetch };
3
+ export async function uploadViews(uploads, deps = DEFAULT_DEPS) {
4
+ const uploaded = {};
5
+ for (const [key, target] of Object.entries(uploads)) {
6
+ const { tarGz, checksumCrc32 } = packDirToTarGz(target.bundleDir);
7
+ const response = await deps.fetch(target.uploadUrl, {
8
+ method: "PUT",
9
+ headers: {
10
+ "Content-Type": "application/gzip",
11
+ "x-amz-checksum-crc32": checksumCrc32,
12
+ },
13
+ body: new Uint8Array(tarGz),
14
+ });
15
+ if (!response.ok) {
16
+ const text = await safeReadText(response);
17
+ throw new Error(`upload failed for block "${key}": ${response.status} ${response.statusText}${text ? `\n${text}` : ""}`);
18
+ }
19
+ uploaded[key] = true;
20
+ }
21
+ return { uploaded };
22
+ }
23
+ export function parseUploadsInput(raw) {
24
+ let parsed;
25
+ try {
26
+ parsed = JSON.parse(raw);
27
+ }
28
+ catch (error) {
29
+ throw new Error(`--uploads is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
30
+ }
31
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
32
+ throw new Error("--uploads must be a JSON object of { key: target }");
33
+ }
34
+ const result = {};
35
+ for (const [key, value] of Object.entries(parsed)) {
36
+ if (typeof value !== "object" || value === null) {
37
+ throw new Error(`--uploads["${key}"] must be an object`);
38
+ }
39
+ const record = value;
40
+ if (typeof record.uploadUrl !== "string") {
41
+ throw new Error(`--uploads["${key}"].uploadUrl must be a string`);
42
+ }
43
+ if (typeof record.bundleDir !== "string") {
44
+ throw new Error(`--uploads["${key}"].bundleDir must be a string`);
45
+ }
46
+ result[key] = {
47
+ uploadUrl: record.uploadUrl,
48
+ bundleDir: record.bundleDir,
49
+ };
50
+ }
51
+ return result;
52
+ }
53
+ async function safeReadText(response) {
54
+ try {
55
+ return await response.text();
56
+ }
57
+ catch {
58
+ return "";
59
+ }
60
+ }
package/dist/version.js CHANGED
@@ -4,4 +4,4 @@
4
4
  *
5
5
  * WARNING: Generated during SDK publish. Do not edit in the published package.
6
6
  */
7
- export const NCBLOCK_SDK_VERSION = "0.0.61"
7
+ export const NCBLOCK_SDK_VERSION = "0.0.62"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@notionhq/custom-blocks",
3
- "version": "0.0.61",
3
+ "version": "0.0.62",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -32,7 +32,8 @@
32
32
  }
33
33
  },
34
34
  "bin": {
35
- "ncblock": "./bin/cli/cli.js"
35
+ "ncblock": "./bin/cli/cli.js",
36
+ "notion-custom-blocks": "./bin/notion-custom-blocks/cli.js"
36
37
  },
37
38
  "scripts": {
38
39
  "test": "vitest run --environment jsdom",