Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 10 additions & 33 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,48 +4,25 @@ import { type TemplateInput, Typebars } from "./src";
const tp = new Typebars();

const params = {
names: '{{#if hasUsers}}{{map users "name"}}{{else}}{{defaultNames}}{{/if}}',
accountIds: ["{{default accountDepartmentId accountId}}"],
};

const coerceSchema = {} as JSONSchema7;

const inputSchema = {
type: "object",
properties: {
defaultNames: {
type: "array",
items: {
type: "string",
},
},
hasUsers: {
type: "boolean",
accountId: {
type: "string",
},
users: {
type: "array",
items: {
type: "object",
properties: {
name: {
type: "string",
},
},
},
accountDepartmentId: {
type: "string",
},
},
required: ["accountId"], // accountDepartmentId is not required, so is optional
} as JSONSchema7;

const result = tp.analyzeAndExecute(
params as TemplateInput,
inputSchema,
{
hasUsers: false,
defaultNames: ["alice", "bob"],
users: [],
},
{
coerceSchema,
},
);
const result = tp.analyzeAndExecute(params as TemplateInput, inputSchema, {
accountDepartmentId: null,
accountId: "salut",
});

console.log(JSON.stringify(result, null, 2));
78 changes: 77 additions & 1 deletion src/analyzer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -466,7 +466,38 @@ function processMustache(
}

// ── Simple expression ────────────────────────────────────────────────────
return resolveExpressionWithDiagnostics(stmt.path, ctx, stmt) ?? {};
const resolved = resolveExpressionWithDiagnostics(stmt.path, ctx, stmt) ?? {};

// When the expression points to an optional property (not in `required`),
// the output can be null at runtime. Wrap the resolved schema with null
// so the output schema accurately reflects this.
// $root returns the entire context — optionality does not apply.
if (stmt.path.type === "PathExpression") {
const segments = extractPathSegments(stmt.path);
if (segments.length > 0) {
const { cleanSegments, identifier } =
extractExpressionIdentifier(segments);
if (!isRootSegments(cleanSegments)) {
let targetSchema =
identifier !== null
? ctx.identifierSchemas?.[identifier]
: ctx.current;
// For aggregated identifiers (array schema), check optionality
// within the items schema, not the array itself.
if (targetSchema && identifier !== null) {
const itemSchema = resolveArrayItems(targetSchema, ctx.root);
if (itemSchema !== undefined) {
targetSchema = itemSchema;
}
}
if (targetSchema && !isPathFullyRequired(targetSchema, cleanSegments)) {
return withNullType(resolved);
}
}
}
}

return resolved;
}

// ─── map helper — special-case analysis ──────────────────────────────────────
Expand Down Expand Up @@ -1438,6 +1469,51 @@ function resolveWithIdentifier(
return resolved;
}

// ─── Nullable Schema Wrapping ────────────────────────────────────────────────

/**
* Wraps a JSON Schema with `null` to indicate the value can be nullish.
*
* - If the schema already includes `null`, it is returned as-is.
* - For schemas with a simple `type` string, the type becomes an array
* (e.g. `{ type: "string" }` → `{ type: ["string", "null"] }`).
* - For schemas with a type array, `"null"` is appended.
* - For complex schemas (oneOf, anyOf, etc.), a `oneOf` wrapper is used.
*/
function withNullType(schema: JSONSchema7): JSONSchema7 {
if (schema.type === "null") return schema;

if (typeof schema.type === "string") {
return { ...schema, type: [schema.type, "null"] };
}

if (Array.isArray(schema.type)) {
if (schema.type.includes("null")) return schema;
return { ...schema, type: [...schema.type, "null"] };
}

// Complex schema (oneOf, anyOf, allOf, etc.) — wrap with oneOf
return simplifySchema({ oneOf: [schema, { type: "null" }] });
}

/**
* Checks whether EVERY segment along a property path is required.
*
* Unlike `isPropertyRequired` (which only checks the last segment),
* this function verifies that no intermediate segment is optional.
* If any segment along the path is optional, the entire expression
* can produce `null`/`undefined` at runtime.
*
* Example: for path `["user", "name"]`, checks both that `user` is
* required in the root schema AND that `name` is required in `user`.
*/
function isPathFullyRequired(schema: JSONSchema7, segments: string[]): boolean {
for (let i = 1; i <= segments.length; i++) {
if (!isPropertyRequired(schema, segments.slice(0, i))) return false;
}
return true;
}

// ─── Utilities ───────────────────────────────────────────────────────────────

/**
Expand Down
28 changes: 28 additions & 0 deletions test-optional.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import type { JSONSchema7 } from "json-schema";
import { type TemplateInput, Typebars } from "./src";

const tp = new Typebars();

const params = {
accountIds: ["{{accountDepartmentId}}"],
};

const inputSchema = {
type: "object",
properties: {
accountId: {
type: "string",
},
accountDepartmentId: {
type: "string",
},
},
required: ["accountId"], // accountDepartmentId is not required, so is optional
} as JSONSchema7;

const result = tp.analyzeAndExecute(params as TemplateInput, inputSchema, {
accountDepartmentId: null, // optional property not provided
accountId: "salut",
});

console.log(JSON.stringify(result, null, 2));
26 changes: 26 additions & 0 deletions test-trace.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import type { JSONSchema7 } from "json-schema";
import { analyze } from "./src/analyzer.ts";

const inputSchema = {
type: "object",
properties: {
accountId: { type: "string" },
accountDepartmentId: { type: "string" },
},
required: ["accountId"],
} as JSONSchema7;

// Test case: array with optional property reference
const result = analyze(["{{accountDepartmentId}}"], inputSchema);

console.log("=== Array with optional property ===");
console.log("Output schema:", JSON.stringify(result.outputSchema, null, 2));
console.log(
"Expected: items should include null type since property is optional",
);

// For comparison, test with required property
const result2 = analyze(["{{accountId}}"], inputSchema);

console.log("\n=== Array with required property ===");
console.log("Output schema:", JSON.stringify(result2.outputSchema, null, 2));
18 changes: 10 additions & 8 deletions tests/aggregated-identifiers.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ const aggregatedSchema: JSONSchema7 = {
amount: { type: "number" },
active: { type: "boolean" },
},
required: ["accountId", "amount", "active"],
},
};

Expand All @@ -53,6 +54,7 @@ const scalarSchema: JSONSchema7 = {
seqOutput: { type: "string" },
count: { type: "number" },
},
required: ["seqOutput", "count"],
};

// ═════════════════════════════════════════════════════════════════════════════
Expand Down Expand Up @@ -455,8 +457,10 @@ describe("Aggregated identifiers — analyze()", () => {
properties: {
city: { type: "string" },
},
required: ["city"],
},
},
required: ["info"],
},
};

Expand Down Expand Up @@ -488,18 +492,11 @@ describe("Aggregated identifiers — analyze()", () => {
properties: {
accountId: { type: "string" },
},
required: ["accountId"],
},
},
};

// For $ref resolution, the root schema used by the analyzer
// is the inputSchema (ctx.root). Since identifierSchemas are
// independent, we place the definitions where the resolver can
// find them. The analyzer's ctx.root is the inputSchema — but
// resolveSchemaPath in resolveWithIdentifier uses idSchema itself,
// so the $ref must be resolvable within the idSchema.
// resolveSchemaPath calls resolveRef which needs root — which is
// the inputSchema. So we pass the definitions in the inputSchema.
const inputSchema: JSONSchema7 = {
type: "object",
definitions: {
Expand All @@ -508,6 +505,7 @@ describe("Aggregated identifiers — analyze()", () => {
properties: {
accountId: { type: "string" },
},
required: ["accountId"],
},
},
};
Expand Down Expand Up @@ -947,6 +945,7 @@ describe("Aggregated identifiers — backward compatibility", () => {
1: {
type: "object",
properties: { meetingId: { type: "string" } },
required: ["meetingId"],
},
},
},
Expand Down Expand Up @@ -1042,6 +1041,7 @@ describe("Aggregated identifiers — workflow merge scenario", () => {
2: {
type: "object",
properties: { seqOutput: { type: "string" } },
required: ["seqOutput"],
},
4: {
type: "array",
Expand All @@ -1051,6 +1051,7 @@ describe("Aggregated identifiers — workflow merge scenario", () => {
accountId: { type: "string" },
processedId: { type: "string" },
},
required: ["accountId", "processedId"],
},
},
};
Expand Down Expand Up @@ -1107,6 +1108,7 @@ describe("Aggregated identifiers — workflow merge scenario", () => {
accountId: { type: "string" },
amount: { type: "number" },
},
required: ["accountId", "amount"],
},
},
};
Expand Down
Loading
Loading