Repository navigation
feat(block-schema): more strict block schema based on discriminated union of block types - #201
Conversation
📝 WalkthroughWalkthroughCentralizes block schemas into packages/blocks/src/deserialize-file/deepnote-file-schema.ts as a discriminated union (DeepnoteBlock) and exports concrete block variant types. Removes many locally exported block-type interfaces across blocks/* and updates those modules to import types from the shared schema. Adds an input-select metadata field (deepnote_variable_selected_variable) and other input metadata. Makes metadata and execution-field access defensive (optional chaining / guarded extraction). Conversion now validates via the schema, sorts keys alphabetically before emitting, and adjusts tests to account for optional execution fields and the new schema types. Sequence Diagram(s)sequenceDiagram
participant File as Deepnote file (YAML/JSON)
participant Parser as deepnote-file-schema.parse
participant Blocks as blocks/* (generators)
participant Convert as convert/* (serializers)
participant Output as Jupyter/Deepnote output
File->>Parser: load & validate blocks (discriminated union)
Note right of Parser: unified block schemas\nincludes new input-select metadata
Parser-->>Blocks: typed DeepnoteBlock objects
Blocks->>Blocks: generate code/markdown (use optional chaining)
Blocks-->>Convert: blocks (execution fields guarded)
Convert->>Convert: sortKeysAlphabetically(parsed)
Convert-->>Output: emit cells/doc (stable keys, guarded execution/outputs)
Suggested reviewers
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #201 +/- ##
==========================================
+ Coverage 91.30% 91.52% +0.21%
==========================================
Files 40 40
Lines 1979 2029 +50
Branches 631 645 +14
==========================================
+ Hits 1807 1857 +50
Misses 172 172 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
packages/convert/src/jupyter-to-deepnote.ts (1)
231-243: Type assertion masks potential discriminated union mismatches.The
as DeepnoteBlockassertion bypasses compile-time verification that the constructed object satisfies all block type variants. If specific block types require additional fields, this won't be caught.Consider validating the constructed block against the schema before returning:
// At the end of convertCellToBlock, before returning: const block = { /* ... current construction ... */ } const validated = deepnoteBlockSchema.parse(block) // throws if invalid return validatedThis ensures runtime validation catches any mismatches between the constructed object and the discriminated union requirements.
packages/blocks/src/markdown.test.ts (1)
186-198: Double type assertion bypasses type safety.The
as unknown as ImageBlockcast circumvents TypeScript's type checking. While the comment explains it's for testing sanitization of arbitrary values, this pattern can hide genuine type mismatches.Consider alternatives:
- Create a test helper that constructs valid ImageBlocks
- Use type satisfaction (
satisfies ImageBlock) to maintain some type checking- Mock only the specific fields needed for the test
♻️ Alternative approach using type satisfaction
- // Using type assertion since the test checks sanitization of arbitrary width values - const block = { + const block: ImageBlock = { id: '123', - type: 'image' as const, + type: 'image', content: '', blockGroup: 'abc', sortingKey: 'a0', metadata: { deepnote_img_src: 'https://example.com/image.png', deepnote_img_width: '500', deepnote_img_alignment: 'center', }, - } as unknown as ImageBlock + }If this fails compilation, it indicates the schema should be updated to allow the test data.
packages/blocks/src/blocks/big-number-blocks.ts (1)
6-9: Missing optional chaining on metadata access.Lines 6-9 access
block.metadata.deepnote_big_number_titleetc. directly, but other refactored files (button-blocks.ts:14, visualization-blocks.ts:6-8) use optional chaining (block.metadata?.field). If metadata is optional in the shared schema, this will throw at runtime.🔧 Proposed fix
export function createPythonCodeForBigNumberBlock(block: BigNumberBlock): string { return pythonCode.executeBigNumber( - block.metadata.deepnote_big_number_title ?? '', - block.metadata.deepnote_big_number_value ?? '', - block.metadata.deepnote_big_number_comparison_title, - block.metadata.deepnote_big_number_comparison_value + block.metadata?.deepnote_big_number_title ?? '', + block.metadata?.deepnote_big_number_value ?? '', + block.metadata?.deepnote_big_number_comparison_title, + block.metadata?.deepnote_big_number_comparison_value ) }
🤖 Fix all issues with AI agents
In @packages/blocks/src/blocks/text-blocks.ts:
- Around line 113-118: The cast to TodoTextBlockMetadata in the text-cell-todo
branch is redundant and can hide schema type drift; instead, use the
schema-inferred metadata directly (access block.metadata.checked) or narrow the
block to the TextCellTodoBlock type before reading metadata so you don't bypass
compiler-checked types—remove the explicit "as TodoTextBlockMetadata" cast in
the block.type === 'text-cell-todo' branch and read checked from the inferred
metadata (or add a local type guard that asserts TextCellTodoBlock) so the
checkbox logic uses the schema type rather than a manual cast.
In @packages/convert/src/deepnote-to-jupyter.ts:
- Around line 131-137: The current type assertion on DeepnoteBlock (assigned to
executableBlock) bypasses the discriminated union; implement a type guard
function isExecutableBlock(block: DeepnoteBlock): block is DeepnoteBlock & {
executionStartedAt?: string; executionFinishedAt?: string; executionCount?:
number; outputs?: unknown[] } that checks the block.type for the executable
kind(s) (e.g., 'code'), then replace the assertion by setting executableBlock
only when isExecutableBlock(block) returns true (e.g., const executableBlock =
isExecutableBlock(block) ? block : null) and update subsequent accesses to use
the guarded executableBlock.
In @packages/convert/src/jupyter-to-deepnote.ts:
- Line 210: The code assigns blockType by force-casting untrusted
deepnoteCellType from notebook metadata to DeepnoteBlock['type'] which bypasses
validation; update the logic in jupyter-to-deepnote.ts (around the blockType
assignment) to validate deepnoteCellType at runtime before using it — either
check it against the allowed DeepnoteBlock types (e.g., an isValidDeepnoteType
helper or a set/enum of allowed values) or run it through the DeepnoteBlock
schema validator (e.g., DeepnoteBlockSchema.parse/validate) and fall back to the
existing ternary (cell.cell_type === 'code' ? 'code' : 'markdown') if invalid,
ensuring no direct type assertion of metadata values.
📜 Review details
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (24)
examples/2_blocks.deepnotepackages/blocks/src/blocks.tspackages/blocks/src/blocks/big-number-blocks.tspackages/blocks/src/blocks/button-blocks.tspackages/blocks/src/blocks/code-blocks.tspackages/blocks/src/blocks/data-frame.test.tspackages/blocks/src/blocks/data-frame.tspackages/blocks/src/blocks/image-blocks.tspackages/blocks/src/blocks/input-blocks.test.tspackages/blocks/src/blocks/input-blocks.tspackages/blocks/src/blocks/sql-blocks.tspackages/blocks/src/blocks/text-blocks.tspackages/blocks/src/blocks/visualization-blocks.tspackages/blocks/src/deserialize-file/deepnote-file-schema.tspackages/blocks/src/deserialize-file/deserialize-deepnote-file.test.tspackages/blocks/src/markdown.test.tspackages/blocks/src/python-code.test.tspackages/convert/src/deepnote-to-jupyter.tspackages/convert/src/deepnote-to-percent.test.tspackages/convert/src/jupyter-to-deepnote.test.tspackages/convert/src/jupyter-to-deepnote.tspackages/convert/src/marimo-to-deepnote.tspackages/convert/src/roundtrip.test.tspackages/reactivity/src/ast-analyzer.test.ts
💤 Files with no reviewable changes (1)
- packages/blocks/src/blocks.ts
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.{ts,tsx}: Place test files next to source files with.test.tsor.test.tsxextension
Use strict type checking in TypeScript files
Prefer type safety over convenience in TypeScript
Useconstfor immutable values
Avoidanytypes - use proper type definitions
Follow Biome's rules (configured inbiome.json)
Use literal keys instead of bracket notation when possible
Prefer single quotes for strings (except when avoiding escapes)
Keep code clean and readable following Biome standards
Files:
packages/convert/src/roundtrip.test.tspackages/convert/src/jupyter-to-deepnote.test.tspackages/convert/src/jupyter-to-deepnote.tspackages/blocks/src/blocks/input-blocks.test.tspackages/reactivity/src/ast-analyzer.test.tspackages/blocks/src/blocks/data-frame.test.tspackages/convert/src/deepnote-to-jupyter.tspackages/convert/src/deepnote-to-percent.test.tspackages/blocks/src/deserialize-file/deserialize-deepnote-file.test.tspackages/blocks/src/blocks/code-blocks.tspackages/blocks/src/blocks/big-number-blocks.tspackages/convert/src/marimo-to-deepnote.tspackages/blocks/src/blocks/input-blocks.tspackages/blocks/src/blocks/button-blocks.tspackages/blocks/src/blocks/image-blocks.tspackages/blocks/src/blocks/data-frame.tspackages/blocks/src/deserialize-file/deepnote-file-schema.tspackages/blocks/src/blocks/visualization-blocks.tspackages/blocks/src/python-code.test.tspackages/blocks/src/blocks/sql-blocks.tspackages/blocks/src/markdown.test.tspackages/blocks/src/blocks/text-blocks.ts
**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.test.{ts,tsx}: Use Vitest as the testing framework
Follow existing test patterns in the codebase (seepackages/blocks/src/blocks/*.test.ts)
Test edge cases, error handling, and special characters
Files:
packages/convert/src/roundtrip.test.tspackages/convert/src/jupyter-to-deepnote.test.tspackages/blocks/src/blocks/input-blocks.test.tspackages/reactivity/src/ast-analyzer.test.tspackages/blocks/src/blocks/data-frame.test.tspackages/convert/src/deepnote-to-percent.test.tspackages/blocks/src/deserialize-file/deserialize-deepnote-file.test.tspackages/blocks/src/python-code.test.tspackages/blocks/src/markdown.test.ts
packages/blocks/**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
For functions that generate code, test the exact output format
Files:
packages/blocks/src/blocks/input-blocks.test.tspackages/blocks/src/blocks/data-frame.test.tspackages/blocks/src/deserialize-file/deserialize-deepnote-file.test.tspackages/blocks/src/python-code.test.tspackages/blocks/src/markdown.test.ts
packages/blocks/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
packages/blocks/src/**/*.{ts,tsx}: UseescapePythonString()for safely embedding strings in Python code in the blocks package
Usets-dedentfor clean multiline template strings in code generation
Always include DataFrame config when generating code for code/SQL blocks
Files:
packages/blocks/src/blocks/input-blocks.test.tspackages/blocks/src/blocks/data-frame.test.tspackages/blocks/src/deserialize-file/deserialize-deepnote-file.test.tspackages/blocks/src/blocks/code-blocks.tspackages/blocks/src/blocks/big-number-blocks.tspackages/blocks/src/blocks/input-blocks.tspackages/blocks/src/blocks/button-blocks.tspackages/blocks/src/blocks/image-blocks.tspackages/blocks/src/blocks/data-frame.tspackages/blocks/src/deserialize-file/deepnote-file-schema.tspackages/blocks/src/blocks/visualization-blocks.tspackages/blocks/src/python-code.test.tspackages/blocks/src/blocks/sql-blocks.tspackages/blocks/src/markdown.test.tspackages/blocks/src/blocks/text-blocks.ts
🧬 Code graph analysis (7)
packages/convert/src/jupyter-to-deepnote.ts (2)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (1)
DeepnoteBlock(325-325)packages/blocks/src/index.ts (1)
DeepnoteBlock(3-3)
packages/reactivity/src/ast-analyzer.test.ts (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (1)
DeepnoteBlock(325-325)
packages/blocks/src/blocks/data-frame.ts (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (2)
CodeBlock(341-341)SqlBlock(342-342)
packages/blocks/src/blocks/visualization-blocks.ts (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (1)
VisualizationBlock(344-344)
packages/blocks/src/blocks/sql-blocks.ts (2)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (1)
SqlBlock(342-342)packages/blocks/src/blocks/python-utils.ts (1)
sanitizePythonVariableName(9-27)
packages/blocks/src/markdown.test.ts (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (1)
ImageBlock(332-332)
packages/blocks/src/blocks/text-blocks.ts (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (7)
TextCellPBlock(337-337)TextCellH1Block(334-334)TextCellH2Block(335-335)TextCellH3Block(336-336)TextCellBulletBlock(338-338)TextCellTodoBlock(339-339)TextCellCalloutBlock(340-340)
🔇 Additional comments (43)
packages/reactivity/src/ast-analyzer.test.ts (1)
15-15: Correct use of double assertion for invalid test data.The
unknownintermediate cast is necessary becauseDeepnoteBlockis now a discriminated union that excludestype: 'unsupported'. This pattern properly bypasses the type system to test runtime filtering behavior.packages/convert/src/deepnote-to-jupyter.ts (1)
147-148: Guard these accesses conditionally.Once the type assertion is replaced with a proper type guard (see comment on lines 131-137), wrap these field accesses in conditional logic to maintain type safety.
Also applies to: 162-162, 164-164
packages/convert/src/marimo-to-deepnote.ts (1)
404-404: Type narrowing improves safety.Explicit union type prevents invalid block types at compile time.
packages/convert/src/roundtrip.test.ts (1)
440-447: Type narrowing correctly guards code-specific fields.The type check ensures
executionStartedAtandexecutionFinishedAtare only accessed on code blocks, aligning with the discriminated union schema.packages/blocks/src/blocks/input-blocks.test.ts (1)
4-13: Import consolidation aligns with centralized schema.Type definitions correctly imported from the shared schema, maintaining clear separation between types and implementations.
packages/blocks/src/deserialize-file/deserialize-deepnote-file.test.ts (1)
174-177: Type guard correctly limits execution field access to code blocks.The conditional check ensures type safety when accessing fields specific to code blocks in the discriminated union.
packages/convert/src/deepnote-to-percent.test.ts (1)
246-246: The block type'text-cell-p'is properly defined in the schema as part of a structured family of text cell types (paragraph, headings, bullets, todos, callouts). The change from the generic'text'type to granular types is valid.packages/blocks/src/blocks/data-frame.ts (2)
3-3: LGTM! Import consolidation aligns with centralized schema.The import from the shared schema is clean and follows the PR's refactoring pattern.
7-7: Good defensive programming with optional chaining.The change from
block.metadata.deepnote_table_statetoblock.metadata?.deepnote_table_state ?? {}safely handles potentially undefined metadata, which is important given the schema consolidation.packages/blocks/src/blocks/data-frame.test.ts (1)
4-4: LGTM! Import path updated to use shared schema.The import consolidation is correct and all tests remain unchanged, ensuring no regression.
packages/blocks/src/python-code.test.ts (2)
4-19: LGTM! Import consolidation aligns with shared schema pattern.The consolidated imports from
deepnote-file-schemaare clean and consistent with the PR's refactoring objectives.
93-93: Field is required in schema but unused in code generation.
deepnote_big_number_formatis defined as a required field (z.string()) in the schema, so the test data correctly includes it. However, this field is never referenced increatePythonCodeForBigNumberBlock()orexecuteBigNumber(). Either implement the field's functionality or mark it as.optional()in the schema if it's not yet needed.packages/blocks/src/blocks/image-blocks.ts (3)
1-1: LGTM! Import from shared schema.The consolidated import is consistent with the PR's centralization pattern.
25-27: Good use of optional chaining with safe defaults.The optional chaining with fallback to empty strings (
?? '') safely handles potentially undefined metadata while providing appropriate defaults for HTML attributes.
32-34: Well-implemented type guard.The
isImageBlocktype guard correctly narrows the type fromDeepnoteBlocktoImageBlockby checking thetypeproperty.packages/blocks/src/markdown.test.ts (2)
12-12: LGTM! Import updated to shared schema.The import consolidation is correct and consistent with the PR's refactoring pattern.
19-19: Good use of const assertions for type literals.The
as constassertions improve type precision by treating'markdown'as a literal type rather thanstring.Also applies to: 34-34
packages/convert/src/jupyter-to-deepnote.test.ts (7)
165-165: LGTM!Switched from
.toBeUndefined()to'outputs' in markdownBlockcheck—correctly tests absence rather than undefined value.
171-174: LGTM!Type guard ensures
executionCountandoutputsare only accessed on code blocks. Consistent with discriminated union pattern.
180-182: LGTM!Same defensive pattern applied consistently.
232-234: LGTM!Guards
executionCountaccess appropriately.
409-417: LGTM!Properly guards code-specific
outputsproperty.
449-449: LGTM!Consistent with line 165 pattern.
1330-1333: LGTM!Final occurrence correctly guarded.
packages/blocks/src/blocks/button-blocks.ts (1)
1-1: LGTM!Import from shared schema and optional chaining on metadata access are correct.
Also applies to: 14-14
packages/blocks/src/blocks/code-blocks.ts (1)
3-3: LGTM!Clean refactor to shared schema imports.
packages/blocks/src/blocks/visualization-blocks.ts (1)
1-1: LGTM!Import from shared schema and consistent optional chaining on metadata access.
Also applies to: 6-8
packages/blocks/src/blocks/sql-blocks.ts (3)
3-3: LGTM!Import updated to use centralized schema.
8-18: LGTM!Optional chaining and nullish coalescing correctly handle potentially undefined metadata/content fields per the updated schema.
50-52: LGTM!Type guard correctly narrows
DeepnoteBlocktoSqlBlock.packages/blocks/src/blocks/text-blocks.ts (4)
1-22: LGTM!Clean import consolidation and backwards-compatible type aliases.
94-129: LGTM!Local
contentvariable with nullish coalescing correctly handles optional content across all branches.
131-164: LGTM!Same resilient pattern applied consistently.
166-172: LGTM!Separator block handling is straightforward.
packages/blocks/src/blocks/input-blocks.ts (3)
3-14: LGTM!All input block types imported from centralized schema.
65-175: LGTM!Direct metadata access is correct—input block schemas define metadata as required (non-optional).
177-221: LGTM!Type guards correctly narrow to specific input block types.
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (5)
7-49: LGTM!Base metadata schemas with
.passthrough()allow schema evolution while preserving known fields.
84-117: LGTM!Factory helpers reduce boilerplate effectively.
295-323: LGTM!Discriminated union on
typeenables proper type narrowing.
331-375: LGTM!Clean type exports with union types for related block groups.
230-244:bigNumberBlockSchemametadata is not optional, unlike all other block schemas.Every other block schema (code, SQL, visualization, button, markdown, image, separator) marks metadata
.optional(), butbigNumberBlockSchemadoesn't. This is inconsistent. Confirm if this deviation is intentional or an oversight.examples/2_blocks.deepnote (1)
95-95: All concerns verified and code is correct.
- Field properly defined in schema as required string (line 265 of deepnote-file-schema.ts)
- Empty string is correct choice: represents "no variable selected" vs
deepnote_variable_default_value: nullwhich means "no default set"- Schema uses
.passthrough()but strictly requires this field (intentional breaking change per PR's "more strict block schema" goal)- Example file properly updated
| sortingKey: sortingKey ?? createSortingKey(index), | ||
| type: blockType, | ||
| } | ||
| } as DeepnoteBlock |
There was a problem hiding this comment.
note to self - we must factor out this typecast here
|
@coderabbitai - please check the schema changes in |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: Length of output: 17284 @saltenasl: Here are all breaking changes in the schema: 1. Block Type Removal & Fragmentation
2. Discriminated Union Enforcement
3. Required Metadata FieldsSeveral blocks now require metadata fields:
4. Stricter Field ValidationscontentHash regex:contentHash: z.string().regex(/^(md5|sha256):[a-f0-9]+$/i)
Datetime strings:
Enum constraints:
5. Content Field ConstraintsThese blocks now require empty content:
Non-empty content will fail validation for these types. 6. Execution Fields ScopeExecution-related fields are now only valid on executable blocks:
7. Type Safety Impact
Migration PathFiles using the old schema will need:
|
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/blocks/src/blocks/text-blocks.ts (1)
85-85: Redundant.toLowerCase()with strict schema.The discriminated union guarantees
block.typeis an exact string literal; case normalization is unnecessary.♻️ Simplify
- return textBlockTypes.includes(block.type.toLowerCase()) + return textBlockTypes.includes(block.type)
🤖 Fix all issues with AI agents
In @packages/convert/src/utils.ts:
- Around line 78-83: The function sortKeysAlphabetically uses an unsound cast by
creating a plain object and asserting it as T; constrain the generic to be
indexable or return a safer type: change the signature to either <T extends
Record<string, unknown>>(obj: T): T and build the result as const sorted:
Partial<T> = {} then assign keys and return sorted as T, or change the return
type to Partial<T> (or Record<string, unknown>) to avoid asserting a freshly
constructed object as an arbitrary T; update references to
sortKeysAlphabetically accordingly.
📜 Review details
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (5)
packages/blocks/src/blocks/text-blocks.tspackages/blocks/src/markdown.test.tspackages/convert/src/jupyter-to-deepnote.tspackages/convert/src/utils.test.tspackages/convert/src/utils.ts
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.{ts,tsx}: Place test files next to source files with.test.tsor.test.tsxextension
Use strict type checking in TypeScript files
Prefer type safety over convenience in TypeScript
Useconstfor immutable values
Avoidanytypes - use proper type definitions
Follow Biome's rules (configured inbiome.json)
Use literal keys instead of bracket notation when possible
Prefer single quotes for strings (except when avoiding escapes)
Keep code clean and readable following Biome standards
Files:
packages/convert/src/jupyter-to-deepnote.tspackages/convert/src/utils.test.tspackages/convert/src/utils.tspackages/blocks/src/markdown.test.tspackages/blocks/src/blocks/text-blocks.ts
**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.test.{ts,tsx}: Use Vitest as the testing framework
Follow existing test patterns in the codebase (seepackages/blocks/src/blocks/*.test.ts)
Test edge cases, error handling, and special characters
Files:
packages/convert/src/utils.test.tspackages/blocks/src/markdown.test.ts
packages/blocks/**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
For functions that generate code, test the exact output format
Files:
packages/blocks/src/markdown.test.ts
packages/blocks/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
packages/blocks/src/**/*.{ts,tsx}: UseescapePythonString()for safely embedding strings in Python code in the blocks package
Usets-dedentfor clean multiline template strings in code generation
Always include DataFrame config when generating code for code/SQL blocks
Files:
packages/blocks/src/markdown.test.tspackages/blocks/src/blocks/text-blocks.ts
🧬 Code graph analysis (4)
packages/convert/src/jupyter-to-deepnote.ts (3)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (2)
DeepnoteBlock(325-325)deepnoteBlockSchema(295-323)packages/blocks/src/index.ts (2)
DeepnoteBlock(3-3)deepnoteBlockSchema(11-11)packages/convert/src/utils.ts (1)
sortKeysAlphabetically(78-84)
packages/convert/src/utils.test.ts (1)
packages/convert/src/utils.ts (3)
sortKeysAlphabetically(78-84)createSortingKey(8-33)isMarkdownBlockType(58-69)
packages/blocks/src/markdown.test.ts (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (8)
TextCellH1Block(334-334)TextCellH2Block(335-335)TextCellH3Block(336-336)TextCellBulletBlock(338-338)TextCellTodoBlock(339-339)TextCellCalloutBlock(340-340)TextCellPBlock(337-337)ImageBlock(332-332)
packages/blocks/src/blocks/text-blocks.ts (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (7)
TextCellPBlock(337-337)TextCellH1Block(334-334)TextCellH2Block(335-335)TextCellH3Block(336-336)TextCellBulletBlock(338-338)TextCellTodoBlock(339-339)TextCellCalloutBlock(340-340)
🔇 Additional comments (7)
packages/convert/src/utils.test.ts (1)
1-116: LGTM!Comprehensive test coverage with good edge-case handling. The numeric key ordering caveat (lines 61-69) is well-documented.
packages/convert/src/jupyter-to-deepnote.ts (2)
231-246: Verify fail-fast error handling is intentional.
deepnoteBlockSchema.parse()throws on validation failure. IfconvertCellToBlockis called with malformed Jupyter cells (e.g., invalid metadata, wrong types), conversion will crash without graceful degradation.Is this the intended behavior? If so, consider documenting it. If not, use
.safeParse()and handle errors.Alternative: graceful fallback
const parseResult = deepnoteBlockSchema.safeParse({ blockGroup, content: source, // ... rest of fields }) if (!parseResult.success) { // Log warning and fall back to basic block structure console.warn(`Invalid block at index ${index}:`, parseResult.error) return createFallbackBlock(cell, index, idGenerator) } return sortKeysAlphabetically(parseResult.data)
210-210: Type assertion acknowledged in past review.The developer confirmed this is safe for roundtrip conversion and noted the need to factor out the typecast. Since it's tracked and understood, skipping further comment.
packages/blocks/src/markdown.test.ts (4)
3-14: Imports correctly updated to centralized schema.The migration from local type definitions to the shared
deepnote-file-schemamodule aligns with the discriminated union approach.
19-170: Test blocks correctly migrated to new schema.All test blocks updated with proper discriminated types (
as constfor literals, specific TextCell* variants) and include the newsortingKeyfield.
209-346: stripMarkdown tests correctly updated.All test blocks migrated to new discriminated types. Error handling tests properly validate unsupported block type behavior, and the CodeBlock test correctly includes
executionCountas an executable block field.
187-205: Type cast is intentional and correctly tests sanitization logic.The test uses
as unknown as ImageBlockto test howsanitizeWidth()handles arbitrary numeric values outside the enum schema. This is valid: schema validation occurs during deserialization, not unit test execution. The function is designed to extract digits from any string input—the type cast is documented and appropriate for testing edge cases.No changes needed.
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/convert/src/deepnote-to-jupyter.ts (1)
131-161: Use type guard based on discriminant instead ofinchecks.The
inoperator checks are safer than type assertions but don't leverage the discriminated union. For discriminated unions, check the discriminant (block.type) and let TypeScript narrow the type:function isExecutableBlock(block: DeepnoteBlock): block is Extract<DeepnoteBlock, { executionCount?: number }> { return block.type === 'code' || block.type === 'sql' // add other executable types } const execFields = isExecutableBlock(block) ? { executionStartedAt: block.executionStartedAt, executionFinishedAt: block.executionFinishedAt, executionCount: block.executionCount ?? null, outputs: block.outputs } : { executionStartedAt: undefined, executionFinishedAt: undefined, executionCount: null, outputs: undefined }Then use
execFields.*in metadata and cell construction.As per coding guidelines, prefer type safety over convenience.
📜 Review details
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
packages/convert/src/deepnote-to-jupyter.ts
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.{ts,tsx}: Place test files next to source files with.test.tsor.test.tsxextension
Use strict type checking in TypeScript files
Prefer type safety over convenience in TypeScript
Useconstfor immutable values
Avoidanytypes - use proper type definitions
Follow Biome's rules (configured inbiome.json)
Use literal keys instead of bracket notation when possible
Prefer single quotes for strings (except when avoiding escapes)
Keep code clean and readable following Biome standards
Files:
packages/convert/src/deepnote-to-jupyter.ts
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (1)
430-435: Inconsistent timestamp validation in metadata.
createdAt,exportedAt, andmodifiedAtusez.string()without.datetime()validation, but execution timestamps (lines 70-71, 417, 419) require ISO datetime strings. Consider applying.datetime()here too for consistency.
🤖 Fix all issues with AI agents
In @packages/blocks/src/deserialize-file/deepnote-file-schema.ts:
- Line 9: The schema entry cell_id uses z.unknown().optional(), which gives no
type safety; update it to a more specific union of expected types (e.g., replace
with z.union([z.string(), z.number()]).optional() or
z.string().nullable().optional() depending on actual shapes) or, if truly
variable, add a comment explaining the allowed shapes and replace z.unknown()
with a documented union like z.union([z.string(), z.number(),
z.object({...})]).optional() so consumers get proper typing from the cell_id
schema.
📜 Review details
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.{ts,tsx}: Place test files next to source files with.test.tsor.test.tsxextension
Use strict type checking in TypeScript files
Prefer type safety over convenience in TypeScript
Useconstfor immutable values
Avoidanytypes - use proper type definitions
Follow Biome's rules (configured inbiome.json)
Use literal keys instead of bracket notation when possible
Prefer single quotes for strings (except when avoiding escapes)
Keep code clean and readable following Biome standards
Files:
packages/blocks/src/deserialize-file/deepnote-file-schema.ts
packages/blocks/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
packages/blocks/src/**/*.{ts,tsx}: UseescapePythonString()for safely embedding strings in Python code in the blocks package
Usets-dedentfor clean multiline template strings in code generation
Always include DataFrame config when generating code for code/SQL blocks
Files:
packages/blocks/src/deserialize-file/deepnote-file-schema.ts
🔇 Additional comments (6)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (6)
79-112: Factory helpers correctly compose block schemas.Both
createTextCellBlockSchemaandcreateInputBlockSchemaproperly spread base fields and extend metadata schemas. The conditionalnoDefaultValuehandling is clean.
118-155: Non-executable block schemas correctly structured.Empty content constraints for image/separator blocks align with PR objectives. Text cell variants properly use factory helper. Enum values for image width and callout colors are well-defined.
161-239: Executable block schemas correctly enforce constraints.Empty content requirements (notebook-function, visualization, button) and required metadata fields (big-number title/value/format, notebook-function function_notebook_id) align with PR breaking changes. Execution fields properly scoped to executable variants.
245-284: Input block schemas properly require metadata per PR objectives.All input blocks inherit required
deepnote_variable_name. Input-select correctly requires four metadata fields (options, custom_options, selected_variable, select_type). Input-slider requires min/max/step. File input appropriately omits default value.
290-318: Discriminated union correctly composed.All 24 block schemas included with unique
typeliterals. Generictexttype properly removed in favor of explicit text-cell variants as per PR objectives. Union enables type narrowing in consumer code.
320-370: Type exports comprehensive and well-organized.Individual block types,
InputBlock, andTextCellBlockunion types provide convenient type access for consumers. Exporting granular types alongside the discriminated union supports flexible type narrowing.
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/convert/src/deepnote-to-percent.test.ts (1)
1-465: Consider adding validation failure tests.Migration to
text-cell-*types is complete across all test files. Optionally, add test cases that verify the oldtexttype blocks fail validation under the new discriminated union schema.
🤖 Fix all issues with AI agents
In @packages/blocks/src/deserialize-file/deepnote-file-schema.ts:
- Around line 237-247: bigNumberBlockSchema's metadata is currently required
because the metadata object is not given a default; update the metadata schema
in bigNumberBlockSchema to use .default({}) so metadata is optional by default
(or alternatively make the individual fields optional if required metadata was
unintended) — locate the metadata object inside bigNumberBlockSchema (the
metadata: executableCellMetadataSchema.extend({...}) block containing
deepnote_big_number_title, deepnote_big_number_value, etc.) and apply
.default({}) to that extended schema to prevent metadata being required when
absent.
In @packages/convert/src/deepnote-to-marimo.test.ts:
- Line 292: The test object sets metadata: {} explicitly even though the schema
already uses .default({}); remove the explicit metadata property from the test
fixture in deepnote-to-marimo.test.ts (the object literal containing "metadata:
{}") so the code relies on the schema default instead, and run tests to confirm
no behavior change.
📜 Review details
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (10)
packages/blocks/src/blocks/input-blocks.test.tspackages/blocks/src/deserialize-file/deepnote-file-schema.tspackages/blocks/src/python-code.test.tspackages/convert/src/deepnote-to-jupyter.test.tspackages/convert/src/deepnote-to-jupyter.tspackages/convert/src/deepnote-to-marimo.test.tspackages/convert/src/deepnote-to-percent.test.tspackages/convert/src/deepnote-to-quarto.test.tspackages/convert/src/roundtrip-all-formats.test.tspackages/convert/src/roundtrip.test.ts
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.{ts,tsx}: Place test files next to source files with.test.tsor.test.tsxextension
Use strict type checking in TypeScript files
Prefer type safety over convenience in TypeScript
Useconstfor immutable values
Avoidanytypes - use proper type definitions
Follow Biome's rules (configured inbiome.json)
Use literal keys instead of bracket notation when possible
Prefer single quotes for strings (except when avoiding escapes)
Keep code clean and readable following Biome standards
Files:
packages/convert/src/deepnote-to-jupyter.test.tspackages/convert/src/deepnote-to-marimo.test.tspackages/convert/src/deepnote-to-quarto.test.tspackages/convert/src/roundtrip.test.tspackages/convert/src/deepnote-to-jupyter.tspackages/convert/src/deepnote-to-percent.test.tspackages/blocks/src/blocks/input-blocks.test.tspackages/blocks/src/python-code.test.tspackages/convert/src/roundtrip-all-formats.test.tspackages/blocks/src/deserialize-file/deepnote-file-schema.ts
**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.test.{ts,tsx}: Use Vitest as the testing framework
Follow existing test patterns in the codebase (seepackages/blocks/src/blocks/*.test.ts)
Test edge cases, error handling, and special characters
Files:
packages/convert/src/deepnote-to-jupyter.test.tspackages/convert/src/deepnote-to-marimo.test.tspackages/convert/src/deepnote-to-quarto.test.tspackages/convert/src/roundtrip.test.tspackages/convert/src/deepnote-to-percent.test.tspackages/blocks/src/blocks/input-blocks.test.tspackages/blocks/src/python-code.test.tspackages/convert/src/roundtrip-all-formats.test.ts
packages/blocks/**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
For functions that generate code, test the exact output format
Files:
packages/blocks/src/blocks/input-blocks.test.tspackages/blocks/src/python-code.test.ts
packages/blocks/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
packages/blocks/src/**/*.{ts,tsx}: UseescapePythonString()for safely embedding strings in Python code in the blocks package
Usets-dedentfor clean multiline template strings in code generation
Always include DataFrame config when generating code for code/SQL blocks
Files:
packages/blocks/src/blocks/input-blocks.test.tspackages/blocks/src/python-code.test.tspackages/blocks/src/deserialize-file/deepnote-file-schema.ts
🧬 Code graph analysis (1)
packages/convert/src/deepnote-to-jupyter.ts (2)
packages/convert/src/index.ts (1)
JupyterCell(84-84)packages/convert/src/types/jupyter.ts (1)
JupyterCell(6-16)
🔇 Additional comments (23)
packages/convert/src/deepnote-to-percent.test.ts (4)
146-146: Schema alignment: metadata addition.Correct addition for stricter schema validation.
186-186: Schema alignment: metadata addition.Correct addition for stricter schema validation.
248-248: Required migration: 'text' → 'text-cell-p'.Correctly migrates to discriminated union schema. The test properly validates that text-cell-p blocks convert to markdown cells in percent format.
Also applies to: 252-252
432-432: Schema alignment: metadata addition.Correct addition for stricter schema validation.
packages/convert/src/roundtrip.test.ts (1)
443-449: Type narrowing correctly handles discriminated union.The conditional check ensures execution timing fields are only accessed on
codeblocks, properly reflecting the new discriminated union schema where these fields exist only on executable variants.packages/convert/src/deepnote-to-jupyter.ts (2)
131-134: Defensive extraction handles discriminated union correctly.Using the
inoperator to guard execution field access is appropriate for the new schema where these fields exist only on executable block types.
137-150: Metadata merge order is correct.Spreading
block.metadatafirst, then applying explicit fields ensures proper precedence. Extracted execution variables are safely applied to metadata.packages/blocks/src/python-code.test.ts (2)
381-385: New required metadata fields added correctly.The added fields (
deepnote_variable_options,deepnote_variable_custom_options,deepnote_variable_selected_variable,deepnote_variable_select_type) align with the PR's breaking change #3, which makes these fields required on InputSelectBlock.
93-93: No action needed. The fielddeepnote_big_number_formatis defined asz.string()with no constraints, so empty strings are valid values.packages/convert/src/roundtrip-all-formats.test.ts (1)
475-500: Empty metadata objects align with schema requirements.Adding
metadata: {}to test blocks ensures fixtures match the new schema structure.packages/convert/src/deepnote-to-quarto.test.ts (1)
121-121: Test fixture updated for schema consistency.Adding
metadata: {}ensures the test block matches the new schema structure.packages/blocks/src/blocks/input-blocks.test.ts (3)
4-13: LGTM: Type centralization.Importing from shared schema aligns with PR goals and improves maintainability.
132-136: New required metadata fields added.Test data correctly includes
deepnote_variable_options,deepnote_variable_custom_options,deepnote_variable_selected_variable, anddeepnote_variable_select_typeas required by the updated schema.Also applies to: 154-158, 177-181
202-204: LGTM: Required slider metadata.Correctly adds required slider bounds and step fields per updated schema.
packages/convert/src/deepnote-to-jupyter.test.ts (1)
467-470: LGTM: Consistent with schema.Input-select metadata correctly updated with required fields.
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (8)
7-48: LGTM: Flexible metadata schemas.Using
.passthrough()allows additional fields while validating known ones. All fields appropriately optional.
51-54: Required field for input blocks.
deepnote_variable_nameis now required for all input blocks. This breaking change aligns with PR objectives.
60-77: LGTM: Base field definitions.ContentHash regex and datetime validations match PR requirements. ExecutionCount correctly nullable.
87-163: LGTM: Non-executable blocks.Correctly enforces empty content for image/separator blocks and uses appropriate enum constraints.
169-231: LGTM: Executable blocks.Empty content correctly enforced for notebook-function, visualization, and button. Enum constraints and defaults properly applied.
253-349: LGTM: Input block schemas.Required metadata fields for select and slider blocks align with test changes. The
z.preprocesspattern for null handling indeepnote_variable_default_valueprevents breaking changes as noted in commit messages.
355-383: LGTM: Discriminated union structure.All 23 block variants properly included. Union enforces strict type checking per PR objectives.
385-543: LGTM: Type exports and file schema.Comprehensive type exports and helper unions. File schema correctly uses datetime validation for execution timestamps per PR objectives.
|
@coderabbitai please map all the fields that have breaking changes in the schemas i added. I will want to pre-process those fields so they will still have breaking changes in TS types, however, the old files should be handled gracefully when parsing. I need a list of all fields and i will then decide from there how to handle each. |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: Length of output: 18868 @saltenasl: Here's a complete field-by-field mapping of all breaking changes: 1. Block Type Discrimination (Core Breaking Change)
2. Required Metadata Fields (Previously Optional/Missing)BigNumberBlock
All Input Blocks (base requirement)
InputTextBlock & InputTextareaBlock
InputCheckboxBlock
InputSelectBlock
InputSliderBlock
InputDateBlock
InputDateRangeBlock
InputFileBlock
NotebookFunctionBlock
3. Stricter Validation PatternscontentHash (ALL block types)
Execution Timestamps (all executable blocks)
File-level Execution Timestamps
Enum ConstraintsImageBlock metadata
TextCellCalloutBlock metadata
SqlBlock metadata
ButtonBlock metadata
InputSelectBlock metadata
File-level execution
File-level environment
4. Content Field Constraints (Must Be Empty)These blocks require
Impact: Non-empty content will fail validation 5. Execution Fields Scope (Field Presence)These fields now ONLY exist on executable blocks:
Cannot be present on:
Impact: Non-executable blocks with these fields will fail discriminated union validation 6. Special Preprocessing NoteAlready handled gracefully in schema:
Summary by Preprocessing Strategy Needed:
|
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In @packages/blocks/src/deserialize-file/deepnote-file-schema.ts:
- Around line 240-254: bigNumberBlockSchema currently requires the metadata
object while all other block schemas use metadata.default({}); update
bigNumberBlockSchema's metadata definition to add .default({}) on the
executableCellMetadataSchema.extend(...) so metadata becomes optional like other
blocks and parsing won't fail when metadata is omitted; locate the metadata
property in bigNumberBlockSchema and append .default({}) to that schema
definition.
📜 Review details
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.{ts,tsx}: Place test files next to source files with.test.tsor.test.tsxextension
Use strict type checking in TypeScript files
Prefer type safety over convenience in TypeScript
Useconstfor immutable values
Avoidanytypes - use proper type definitions
Follow Biome's rules (configured inbiome.json)
Use literal keys instead of bracket notation when possible
Prefer single quotes for strings (except when avoiding escapes)
Keep code clean and readable following Biome standards
Files:
packages/blocks/src/deserialize-file/deepnote-file-schema.ts
packages/blocks/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
packages/blocks/src/**/*.{ts,tsx}: UseescapePythonString()for safely embedding strings in Python code in the blocks package
Usets-dedentfor clean multiline template strings in code generation
Always include DataFrame config when generating code for code/SQL blocks
Files:
packages/blocks/src/deserialize-file/deepnote-file-schema.ts
🧬 Code graph analysis (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (1)
packages/blocks/src/index.ts (2)
deepnoteBlockSchema(11-11)DeepnoteBlock(3-3)
🔇 Additional comments (8)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (8)
14-61: Well-structured base schemas with good backward compatibility.The layered approach (base → executable → specialized) and use of
.passthrough()enable graceful handling of legacy and future fields.
67-84: Clean field separation for discriminated union.Base and executable field sets are well-designed. Regex and datetime validations are appropriate.
94-170: Consistent non-executable block schemas.All schemas follow the same pattern: base fields, type literal, optional content (or empty for image/separator), and defaulted metadata. Enum constraints tighten validation as intended.
176-239: Consistent executable block schemas.Code, SQL, notebook-function, visualization, and button schemas follow consistent patterns with appropriate use of
emptyContent()and defaulted metadata.
260-356: Well-designed input block schemas with strong defaults.The null-to-undefined preprocessing pattern for
default_valuefields is elegant. Comprehensive defaults ensure backward compatibility.
362-390: Properly structured discriminated union.All block schemas correctly included. Grouping by category aids readability.
392-442: Comprehensive type exports.Individual types and union helpers (InputBlock, TextCellBlock) provide good ergonomics for consumers.
448-551: File-level schemas correctly integrated.New discriminated block schema properly referenced. Enum constraints and datetime validation align with stricter validation goals.
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (1)
504-509: Inconsistent timestamp validation.
execution.startedAt/finishedAtuse.datetime()butmetadata.createdAt/exportedAt/modifiedAtare plain strings. Apply consistent validation if all should be ISO format.♻️ If ISO format is required
metadata: z.object({ checksum: z.string().optional(), - createdAt: z.string(), - exportedAt: z.string().optional(), - modifiedAt: z.string().optional(), + createdAt: z.string().datetime(), + exportedAt: z.string().datetime().optional(), + modifiedAt: z.string().datetime().optional(), }),
🤖 Fix all issues with AI agents
In @packages/blocks/src/deserialize-file/deepnote-file-schema.ts:
- Around line 40-46: The schema uses z.record(z.any()) for deepnote_table_state
and function_notebook_export_states which allows any value; change these to
z.record(z.unknown()) to tighten runtime validation while keeping the fields
opaque — update the definitions of deepnote_table_state and
function_notebook_export_states to use z.record(z.unknown()). Ensure any code
that reads these records handles unknown-typed values appropriately (e.g.,
validating before accessing specific properties).
- Around line 268-269: The repeated z.preprocess(val => (val === null ?
undefined : val), ...) logic should be extracted into a small helper (e.g.
nullToUndefined or preprocessNullToUndefined) and reused; add a helper function
that accepts a Zod schema and returns z.preprocess(val => val === null ?
undefined : val, schema), then replace each inline usage (including the
deepnote_variable_default_value field and the other seven occurrences) with
helper(schema) to deduplicate the logic while keeping existing schemas intact.
- Around line 198-209: The metadata property in notebookFunctionBlockSchema
currently defines function_notebook_id as z.string().nullable(), which makes the
key required even when null; change it to z.string().nullable().optional() so
the field can be omitted or null, matching the pattern used by
deepnote_app_block_group_id and ensuring partial metadata objects validate
correctly; keep the surrounding metadata schema default({ function_notebook_id:
null }) intact.
📜 Review details
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.{ts,tsx}: Place test files next to source files with.test.tsor.test.tsxextension
Use strict type checking in TypeScript files
Prefer type safety over convenience in TypeScript
Useconstfor immutable values
Avoidanytypes - use proper type definitions
Follow Biome's rules (configured inbiome.json)
Use literal keys instead of bracket notation when possible
Prefer single quotes for strings (except when avoiding escapes)
Keep code clean and readable following Biome standards
Files:
packages/blocks/src/deserialize-file/deepnote-file-schema.ts
packages/blocks/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
packages/blocks/src/**/*.{ts,tsx}: UseescapePythonString()for safely embedding strings in Python code in the blocks package
Usets-dedentfor clean multiline template strings in code generation
Always include DataFrame config when generating code for code/SQL blocks
Files:
packages/blocks/src/deserialize-file/deepnote-file-schema.ts
🔇 Additional comments (6)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (6)
7-8: Looks good.Preprocess helper correctly coerces any content to empty string for content-less blocks.
67-84: LGTM.Base and executable field definitions are well-structured. Regex validation for
contentHashand datetime validation for timestamps are appropriate.
94-170: Clean implementation.Non-executable block schemas follow consistent patterns. Enum constraints for image dimensions/alignment and callout colors are well-defined.
316-322: Mixed types: string value with numeric bounds.
deepnote_variable_valueisstringwhiledeepnote_slider_min_value/max_value/steparenumber. Intentional for compatibility, or should value be numeric?
364-392: Well-structured discriminated union.All 24 block variants correctly included. The
typediscriminator enables efficient validation and type narrowing.
536-550: Good deprecation documentation.JSDoc comment clearly marks the legacy
settings.environmentfield. Consumers can migrate to top-levelenvironment.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In @packages/blocks/src/deserialize-file/deepnote-file-schema.ts:
- Around line 82-84: The "Schema factory helpers" comment block (the separator
and header text "Schema factory helpers") is empty and should be removed or
populated; either delete the three-line header/section (the "//
============================================================================="
separators and the "// Schema factory helpers" line) to avoid an empty section,
or implement and export the intended factory helper functions (e.g., add
properly named factory functions and their exports) in place of the header so
the section is meaningful.
📜 Review details
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.{ts,tsx}: Place test files next to source files with.test.tsor.test.tsxextension
Use strict type checking in TypeScript files
Prefer type safety over convenience in TypeScript
Useconstfor immutable values
Avoidanytypes - use proper type definitions
Follow Biome's rules (configured inbiome.json)
Use literal keys instead of bracket notation when possible
Prefer single quotes for strings (except when avoiding escapes)
Keep code clean and readable following Biome standards
Files:
packages/blocks/src/deserialize-file/deepnote-file-schema.ts
packages/blocks/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
packages/blocks/src/**/*.{ts,tsx}: UseescapePythonString()for safely embedding strings in Python code in the blocks package
Usets-dedentfor clean multiline template strings in code generation
Always include DataFrame config when generating code for code/SQL blocks
Files:
packages/blocks/src/deserialize-file/deepnote-file-schema.ts
🧬 Code graph analysis (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (1)
packages/blocks/src/index.ts (2)
deepnoteBlockSchema(11-11)DeepnoteBlock(3-3)
🔇 Additional comments (9)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (9)
7-8: Clean backward compatibility helper.The
emptyContentpreprocessor correctly coerces any value to an empty string for blocks that don't use content. The pattern ensures old data is normalized while enforcing the constraint.
63-80: Solid field definitions.Regex for
contentHash, datetime validation for execution timestamps, and scoping of execution fields to executable blocks all align with requirements.
90-166: Non-executable blocks implemented correctly.All variants use proper base fields,
emptyContent()where required, and enum constraints match the spec. The discriminated types are well-structured.
236-252: Verify required vs. default for BigNumberBlock fields.PR objectives state
deepnote_big_number_title,deepnote_big_number_value, anddeepnote_big_number_formatare required. Using.default('')makes them optional (with fallback). If backward compatibility is needed, this is correct; otherwise, remove.default()and omit.optional().Is this backward-compat intentional, or should these be truly required fields?
258-354: Input blocks well-structured.Preprocessing
null → undefinedensures backward compatibility. The newdeepnote_variable_selected_variablefield (line 301) and enum constraints align with requirements. Consistent patterns across all input variants.
360-388: Discriminated union correctly implemented.Using
z.discriminatedUnion('type', [...])enables TypeScript to narrow types based on the discriminator. All 26 block variants are included.
390-441: Type exports comprehensive.All block variants exported. The
InputBlockandTextCellBlockunion types provide convenient subsets for consumers.
446-549: File-level schemas complete.Environment enum (line 454), execution datetime validation (lines 487, 489), triggeredBy enum (line 491), and the deprecated notice (lines 533-536) all align with requirements. The file structure properly references
deepnoteBlockSchemafor block validation.
54-57: The.default('unnamed_variable')is intentional for backward compatibility—this schema deserializes potentially legacy files that may lack the field. The app layer (per tests) always provides meaningful names when blocks are created/updated. This design is correct.
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Fix all issues with AI agents
In @packages/blocks/src/deserialize-file/deepnote-file-schema.ts:
- Around line 290-309: inputSelectBlockSchema sets deepnote_variable_value as
z.union([z.string(), z.array(z.string())]) but uses default(''), causing a type
mismatch for multi-select scenarios; change the default to an array (e.g.,
default([])) so the default value matches the union's array option and aligns
with multi-select users (update the default for deepnote_variable_value inside
inputSelectBlockSchema).
- Around line 7-8: The helper emptyContent() currently uses z.preprocess(() =>
'', z.literal('').optional()), which is redundant because the preprocesser
always returns the empty string so the schema can never be undefined; remove the
.optional() and change the inner schema to z.literal('') (i.e., use
z.preprocess(() => '', z.literal('')) in emptyContent) so the produced type is
correctly '' instead of string | undefined while keeping the same runtime
behavior.
- Around line 62-71: The schema in baseBlockFields currently requires sortingKey
which will cause validation failures for older files missing that field; either
make sortingKey optional in baseBlockFields (add .optional()) or add a
preprocessing step before validation that populates a sensible fallback
sortingKey for blocks missing it (e.g., derive from id or creation order) so
deserialization remains backward compatible; update references where
baseBlockFields is used so the sanitizer/factory sets the fallback when needed.
📜 Review details
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.{ts,tsx}: Place test files next to source files with.test.tsor.test.tsxextension
Use strict type checking in TypeScript files
Prefer type safety over convenience in TypeScript
Useconstfor immutable values
Avoidanytypes - use proper type definitions
Follow Biome's rules (configured inbiome.json)
Use literal keys instead of bracket notation when possible
Prefer single quotes for strings (except when avoiding escapes)
Keep code clean and readable following Biome standards
Files:
packages/blocks/src/deserialize-file/deepnote-file-schema.ts
packages/blocks/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
packages/blocks/src/**/*.{ts,tsx}: UseescapePythonString()for safely embedding strings in Python code in the blocks package
Usets-dedentfor clean multiline template strings in code generation
Always include DataFrame config when generating code for code/SQL blocks
Files:
packages/blocks/src/deserialize-file/deepnote-file-schema.ts
🧬 Code graph analysis (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (1)
packages/blocks/src/index.ts (2)
deepnoteBlockSchema(11-11)DeepnoteBlock(3-3)
🔇 Additional comments (5)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (5)
14-56: Well-structured base metadata hierarchy.Good use of
.passthrough()for forward compatibility. Schema composition is clean.
85-161: Non-executable block schemas look solid.Consistent structure.
emptyContent()correctly enforces empty content for image/separator. Text cell variants properly extendtextCellMetadataSchema.
167-247: Executable block schemas are well-defined.
notebookFunctionBlockSchemacorrectly enforcesfunction_notebook_idas nullable with sensible default. Enum constraints are appropriate.
371-451: Discriminated union and type exports are comprehensive.Clean organization.
InputBlockandTextCellBlockunions will help with type guards downstream.
508-560: File schema correctly integrates the new block discriminated union.Structure is solid.
|
@coderabbitai this PR introduces quite a few breaking changes in the deepnote file schema, some of them have been addressed by e.g. providing sensible defaults - this is applicable only when parsing, TS types will still have breaking changes. Can you please list all of the breaking changes in a table format so i can use this in the changelog when informing consumers about them? Include if it has been automatically handled when parsing files (TS types will still have the breaking change). |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: Length of output: 19301 @saltenasl: Here's a comprehensive table of all breaking changes for the changelog: Breaking Changes in Deepnote File Schema
Summary by Handling Status✅ Automatically Handled When Parsing (26 items):
❌ Requires Manual Migration (23 items):
N/A - API Changes (4 items):
|
Summary by CodeRabbit
New Features
Refactor
Bug Fixes
Tests
✏️ Tip: You can customize this high-level summary in your review settings.