Skip to content
Open
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
10 changes: 10 additions & 0 deletions bin/configs/typescript-fetch-date-anchor-utc.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
generatorName: typescript-fetch
outputDir: samples/client/petstore/typescript-fetch/builds/date-anchor-utc
inputSpec: modules/openapi-generator/src/test/resources/3_0/typescript-fetch/date-handling.yaml
templateDir: modules/openapi-generator/src/main/resources/typescript-fetch
additionalProperties:
dateLibrary: date
dateAnchor: utc
npmVersion: 1.0.0
npmName: '@openapitools/typescript-fetch-petstore'
npmRepository: https://skimdb.npmjs.com/registry
1 change: 1 addition & 0 deletions docs/generators/typescript-fetch.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
|dateAnchor|Option. How a `format: date` value is anchored to an instant. Only applies when dateLibrary=date.|<dl><dt>**local**</dt><dd>Local calendar. A `format: date` value is parsed to local midnight and serialized from the local calendar (default since 7.25.0).</dd><dt>**utc**</dt><dd>UTC. A `format: date` value is parsed with `new Date(value)` and serialized as the UTC calendar day (`toISOString().substring(0, 10)`), the behaviour up to 7.24.</dd></dl>|local|
|dateLibrary|Option. Date library to use.|<dl><dt>**date**</dt><dd>Native Date. `format: date` and `format: date-time` are both mapped to Date and (de)serialized by the runtime.</dd><dt>**string**</dt><dd>Plain string. Values are passed through untouched, leaving date handling to the consumer.</dd><dt>**temporal**</dt><dd>Native Temporal. `format: date` is mapped to Temporal.PlainDate and `format: date-time` is mapped to Temporal.Instant and (de)serialized by the runtime. (Experimental support) </dd></dl>|date|
|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|<dl><dt>**false**</dt><dd>The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.</dd><dt>**true**</dt><dd>Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.</dd></dl>|true|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,10 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
public static final String DATE_LIBRARY_DATE = "date";
public static final String DATE_LIBRARY_STRING = "string";
public static final String DATE_LIBRARY_TEMPORAL = "temporal";
public static final String DATE_ANCHOR = "dateAnchor";
public static final String DATE_ANCHOR_DESC = "Option. How a `format: date` value is anchored to an instant. Only applies when dateLibrary=date.";
public static final String DATE_ANCHOR_LOCAL = "local";
public static final String DATE_ANCHOR_UTC = "utc";
public static final String STRING_ENUMS = "stringEnums";
public static final String STRING_ENUMS_DESC = "Generate string enums instead of objects for enum values.";
public static final String IMPORT_FILE_EXTENSION_SWITCH = "importFileExtension";
Expand All @@ -96,6 +100,7 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
protected boolean addedModelIndex = false;
protected boolean withoutRuntimeChecks = false;
protected String dateLibrary = DATE_LIBRARY_DATE;
protected String dateAnchor = DATE_ANCHOR_LOCAL;
protected boolean stringEnums = false;
protected String fileNaming = PASCAL_CASE;
protected String apiDocPath = "docs";
Expand Down Expand Up @@ -172,6 +177,13 @@ public TypeScriptFetchClientCodegen() {
dateOptions.put(DATE_LIBRARY_TEMPORAL, "Native Temporal. `format: date` is mapped to Temporal.PlainDate and `format: date-time` is mapped to Temporal.Instant and (de)serialized by the runtime. (Experimental support) ");
dateLibraryOption.setEnum(dateOptions);
this.cliOptions.add(dateLibraryOption);

CliOption dateAnchorOption = new CliOption(DATE_ANCHOR, DATE_ANCHOR_DESC).defaultValue(this.getDateAnchor());
Map<String, String> dateAnchorOptions = new LinkedHashMap<>();
dateAnchorOptions.put(DATE_ANCHOR_LOCAL, "Local calendar. A `format: date` value is parsed to local midnight and serialized from the local calendar (default since 7.25.0).");
dateAnchorOptions.put(DATE_ANCHOR_UTC, "UTC. A `format: date` value is parsed with `new Date(value)` and serialized as the UTC calendar day (`toISOString().substring(0, 10)`), the behaviour up to 7.24.");
dateAnchorOption.setEnum(dateAnchorOptions);
this.cliOptions.add(dateAnchorOption);
this.cliOptions.add(new CliOption(SAGAS_AND_RECORDS, "Setting this property to true will generate additional files for use with redux-saga and immutablejs.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString()));
this.cliOptions.add(new CliOption(STRING_ENUMS, STRING_ENUMS_DESC, SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString()));
this.cliOptions.add(new CliOption(IMPORT_FILE_EXTENSION_SWITCH, IMPORT_FILE_EXTENSION_SWITCH_DESC).defaultValue(""));
Expand Down Expand Up @@ -238,6 +250,19 @@ public void setDateLibrary(String dateLibrary) {
this.dateLibrary = dateLibrary;
}

public String getDateAnchor() {
return this.dateAnchor;
}

public void setDateAnchor(String dateAnchor) {
if (DATE_ANCHOR_LOCAL.equals(dateAnchor) || DATE_ANCHOR_UTC.equals(dateAnchor)) {
this.dateAnchor = dateAnchor;
} else {
throw new IllegalArgumentException("Invalid dateAnchor '" +
dateAnchor + "'. Must be 'local' or 'utc'");
}
}

public Boolean getStringEnums() {
return this.stringEnums;
}
Expand Down Expand Up @@ -359,6 +384,10 @@ public void processOpts() {
this.setDateLibrary(additionalProperties.get(DATE_LIBRARY).toString());
}

if (additionalProperties.containsKey(DATE_ANCHOR)) {
this.setDateAnchor(additionalProperties.get(DATE_ANCHOR).toString());
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
}

if (!withoutRuntimeChecks) {
this.modelTemplateFiles.put("models.mustache", ".ts");
}
Expand Down Expand Up @@ -390,6 +419,13 @@ public void processOpts() {
additionalProperties.put("isDateLibraryString", DATE_LIBRARY_STRING.equals(this.dateLibrary));
additionalProperties.put("isDateLibraryTemporal", DATE_LIBRARY_TEMPORAL.equals(this.dateLibrary));

if (DATE_ANCHOR_UTC.equals(this.dateAnchor) && !DATE_LIBRARY_DATE.equals(this.dateLibrary)) {
LOGGER.warn("{}={} only applies when {}={}; ignoring {}={}.",
DATE_ANCHOR, this.dateAnchor, DATE_LIBRARY, DATE_LIBRARY_DATE, DATE_ANCHOR, this.dateAnchor);
}
additionalProperties.put(DATE_ANCHOR, this.dateAnchor);
additionalProperties.put("isDateAnchorUtc", DATE_ANCHOR_UTC.equals(this.dateAnchor) && DATE_LIBRARY_DATE.equals(this.dateLibrary));

if (additionalProperties.containsKey(SAGAS_AND_RECORDS)) {
this.setSagasAndRecords(convertPropertyToBoolean(SAGAS_AND_RECORDS));
if (this.getSagasAndRecords()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -411,8 +411,14 @@ export function parseDate(value: Temporal.PlainDate | string): Temporal.PlainDat
* Every generated date call site routes through these.
*
* `format: date` is a calendar date, with no time and no offset, so it is converted
{{#isDateAnchorUtc}}
* against UTC on both ends: the UTC calendar day is preserved everywhere.
* `format: date-time` is an instant and uses UTC.
{{/isDateAnchorUtc}}
{{^isDateAnchorUtc}}
* against the local calendar on both ends: they have to agree or the date shifts by
* a day. `format: date-time` is an instant and uses UTC.
{{/isDateAnchorUtc}}
*/
export function serializeDateTime(value: Date): string {
return value.toISOString();
Expand All @@ -423,17 +429,26 @@ export function serializeDate(value: Date): string {
if (isNaN(value.getTime())) {
throw new RangeError('Invalid time value');
}
{{#isDateAnchorUtc}}
return value.toISOString().substring(0, 10);
{{/isDateAnchorUtc}}
{{^isDateAnchorUtc}}
const year = ('000' + value.getFullYear()).slice(-4);
const month = ('0' + (value.getMonth() + 1)).slice(-2);
const day = ('0' + value.getDate()).slice(-2);
return `${year}-${month}-${day}`;
{{/isDateAnchorUtc}}
}


export function parseDate(value: Date | string): Date {
if (value instanceof Date) {
return value;
}
{{#isDateAnchorUtc}}
return new Date(value);
{{/isDateAnchorUtc}}
{{^isDateAnchorUtc}}
// `new Date("2026-08-05")` would parse as UTC midnight: a different day west of UTC.
// Local midnight is the stated day everywhere. setFullYear avoids the 1900 offset the
// multi-argument constructor applies to years 0-99.
Expand All @@ -453,6 +468,7 @@ export function parseDate(value: Date | string): Date {
return date;
}
return new Date(value);
{{/isDateAnchorUtc}}
}

export function parseDateTime(value: any): Date {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ public class TypeScriptFetchClientOptionsProvider implements TypeScriptSharedCli
public static final String STRING_ENUMS = "false";
public static final String FILE_NAMING_VALUE = PASCAL_CASE;
public static final String DATE_LIBRARY_VALUE = TypeScriptFetchClientCodegen.DATE_LIBRARY_STRING;
public static final String DATE_ANCHOR_VALUE = TypeScriptFetchClientCodegen.DATE_ANCHOR_UTC;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: This fixture pairs dateAnchor=utc with dateLibrary=string, which the generator ignores and warns about on every options test run. Use a value that does not trigger the ignored-option path, such as the local default, or pick a dateLibrary that the options test can actually exercise.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptFetchClientOptionsProvider.java, line 35:

<comment>This fixture pairs `dateAnchor=utc` with `dateLibrary=string`, which the generator ignores and warns about on every options test run. Use a value that does not trigger the ignored-option path, such as the `local` default, or pick a dateLibrary that the options test can actually exercise.</comment>

<file context>
@@ -32,6 +32,7 @@ public class TypeScriptFetchClientOptionsProvider implements TypeScriptSharedCli
     public static final String STRING_ENUMS = "false";
     public static final String FILE_NAMING_VALUE = PASCAL_CASE;
     public static final String DATE_LIBRARY_VALUE = TypeScriptFetchClientCodegen.DATE_LIBRARY_STRING;
+    public static final String DATE_ANCHOR_VALUE = TypeScriptFetchClientCodegen.DATE_ANCHOR_UTC;
 
 
</file context>
Suggested change
public static final String DATE_ANCHOR_VALUE = TypeScriptFetchClientCodegen.DATE_ANCHOR_UTC;
public static final String DATE_ANCHOR_VALUE = TypeScriptFetchClientCodegen.DATE_ANCHOR_LOCAL;



@Override
Expand All @@ -52,6 +53,7 @@ public Map<String, String> createOptions() {
.put(TypeScriptFetchClientCodegen.IMPORT_FILE_EXTENSION_SWITCH, IMPORT_FILE_EXTENSION_VALUE)
.put(TypeScriptFetchClientCodegen.FILE_NAMING, FILE_NAMING_VALUE)
.put(TypeScriptFetchClientCodegen.DATE_LIBRARY, DATE_LIBRARY_VALUE)
.put(TypeScriptFetchClientCodegen.DATE_ANCHOR, DATE_ANCHOR_VALUE)
.put(TypeScriptFetchClientCodegen.STRING_ENUMS, STRING_ENUMS)
.put(TypeScriptFetchClientCodegen.USE_SQUARE_BRACKETS_IN_ARRAY_NAMES, Boolean.FALSE.toString())
.put(TypeScriptFetchClientCodegen.VALIDATION_ATTRIBUTES, Boolean.FALSE.toString())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1493,6 +1493,54 @@ public void testDateLibraryDateFallsBackToStringWithoutRuntimeChecks() throws IO
TestUtils.assertFileNotContains(modelsIndex, "startsOn: Date;");
}

@Test(description = "Verify dateAnchor=local is the default: format: date is anchored to the local calendar")
public void testDateAnchorLocalIsTheDefault() throws IOException {
File output = generate(new HashMap<>(), DATE_HANDLING_SPEC);

Path runtime = Paths.get(output + "/runtime.ts");
TestUtils.assertFileContains(runtime, "const year = ('000' + value.getFullYear()).slice(-4);");
TestUtils.assertFileContains(runtime, "date.setHours(0, 0, 0, 0);");
TestUtils.assertFileNotContains(runtime, "return value.toISOString().substring(0, 10);");
}

@Test(description = "Verify dateAnchor=utc restores the pre-7.25 UTC anchoring of format: date")
public void testDateAnchorUtc() throws IOException {
Map<String, Object> properties = new HashMap<>();
properties.put(TypeScriptFetchClientCodegen.DATE_ANCHOR, TypeScriptFetchClientCodegen.DATE_ANCHOR_UTC);

File output = generate(properties, DATE_HANDLING_SPEC);

Path runtime = Paths.get(output + "/runtime.ts");
TestUtils.assertFileContains(runtime, "return value.toISOString().substring(0, 10);");
TestUtils.assertFileContains(runtime, "export function parseDate(value: Date | string): Date {\n if (value instanceof Date) {\n return value;\n }\n return new Date(value);\n}");
TestUtils.assertFileNotContains(runtime, "setFullYear(year, month, day)");
TestUtils.assertFileNotContains(runtime, "date.setHours(0, 0, 0, 0);");

Path event = Paths.get(output + "/models/Event.ts");
TestUtils.assertFileContains(event, "startsOn: Date;");
TestUtils.assertFileContains(event, "'startsOn': (json['startsOn'] == null ? json['startsOn'] : parseDate(json['startsOn']))");
TestUtils.assertFileContains(event, "'startsOn': value['startsOn'] == null ? value['startsOn'] : serializeDate(value['startsOn'])");
}

@Test(description = "Verify dateAnchor=utc is ignored when dateLibrary is not date")
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
public void testDateAnchorUtcIsIgnoredWithoutDateLibraryDate() throws IOException {
Map<String, Object> properties = new HashMap<>();
properties.put(TypeScriptFetchClientCodegen.DATE_ANCHOR, TypeScriptFetchClientCodegen.DATE_ANCHOR_UTC);
properties.put(TypeScriptFetchClientCodegen.DATE_LIBRARY, TypeScriptFetchClientCodegen.DATE_LIBRARY_STRING);

File output = generate(properties, DATE_HANDLING_SPEC);

Path runtime = Paths.get(output + "/runtime.ts");
TestUtils.assertFileNotContains(runtime, "export function parseDate(");
TestUtils.assertFileNotContains(runtime, "export function serializeDate(");
TestUtils.assertFileNotContains(runtime, "return value.toISOString().substring(0, 10);");

TypeScriptFetchClientCodegen codegen = new TypeScriptFetchClientCodegen();
codegen.additionalProperties().putAll(properties);
codegen.processOpts();
Assert.assertEquals(codegen.additionalProperties().get("isDateAnchorUtc"), Boolean.FALSE);
}

@Test(description = "Verify format: date is serialized as a calendar date in every parameter location, not as a date-time")
public void testDateFormatIsSerializedAsACalendarDate() throws IOException {
File output = generate(new HashMap<>(), DATE_HANDLING_SPEC);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ protected void verifyOptions() {
verify(clientCodegen).setStringEnums(Boolean.parseBoolean(TypeScriptFetchClientOptionsProvider.STRING_ENUMS));
verify(clientCodegen).setFileNaming(TypeScriptFetchClientOptionsProvider.FILE_NAMING_VALUE);
verify(clientCodegen).setDateLibrary(TypeScriptFetchClientOptionsProvider.DATE_LIBRARY_VALUE);
verify(clientCodegen).setDateAnchor(TypeScriptFetchClientOptionsProvider.DATE_ANCHOR_VALUE);
}

@Test(description = "Verify if an exception is thrown when invalid values are used with fileNaming option")
Expand All @@ -72,4 +73,18 @@ public void testFileNamingInvalidValues() {
);
}

@Test(description = "Verify if an exception is thrown when invalid values are used with dateAnchor option")
public void testDateAnchorInvalidValues() {
final TypeScriptFetchClientCodegen codegen = new TypeScriptFetchClientCodegen();
Assert.assertThrows(IllegalArgumentException.class, () ->
codegen.setDateAnchor(null)
);
Assert.assertThrows(IllegalArgumentException.class, () ->
codegen.setDateAnchor("")
);
Assert.assertThrows(IllegalArgumentException.class, () ->
codegen.setDateAnchor("UTC")
);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
wwwroot/*.js
node_modules
typings
dist
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator

# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.

# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs

# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux

# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux

# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
.gitignore
.npmignore
README.md
docs/DefaultApi.md
docs/Event.md
docs/Holidays.md
docs/Venue.md
package.json
src/apis/DefaultApi.ts
src/apis/index.ts
src/index.ts
src/models/Event.ts
src/models/Holidays.ts
src/models/Venue.ts
src/models/index.ts
src/runtime.ts
tsconfig.esm.json
tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
7.28.0-SNAPSHOT
Loading
Loading