Skip to content

Commit

Permalink
refactor: fix some .d.ts output, avoid writing attest snapshots early (
Browse files Browse the repository at this point in the history
  • Loading branch information
ssalbdivad authored May 2, 2024
1 parent 17f48ab commit 2c6dd54
Show file tree
Hide file tree
Showing 19 changed files with 101 additions and 104 deletions.
4 changes: 2 additions & 2 deletions .github/actions/setup/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ runs:
using: composite
steps:
- name: Setup pnpm
uses: pnpm/action-setup@v2
uses: pnpm/action-setup@v3
with:
version: 8.3.1
version: 9

- name: Setup Node (${{ inputs.node }})
uses: actions/setup-node@v3
Expand Down
6 changes: 0 additions & 6 deletions .github/workflows/pr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,6 @@ jobs:
- name: prChecks
run: pnpm prChecks

- name: TSC Diagnostics Diff
uses: beerose/[email protected]
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
leave-comment: true

compatibility:
needs: core
timeout-minutes: 20
Expand Down
6 changes: 1 addition & 5 deletions ark/attest/__tests__/demo.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import {
attest,
contextualize,
getPrimaryTsVersionUnderTest
} from "@arktype/attest"
import { attest, contextualize } from "@arktype/attest"
import { type } from "arktype"

const o = { ark: "type" } as const
Expand Down
4 changes: 2 additions & 2 deletions ark/attest/__tests__/utils.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { readFile, shell } from "@arktype/fs"
import { dirName, readFile, shell } from "@arktype/fs"
import { copyFileSync, rmSync } from "node:fs"

export const runThenGetContents = (templatePath: string): string => {
const tempPath = templatePath + ".temp.ts"
copyFileSync(templatePath, tempPath)
try {
shell(`pnpm tsx ${tempPath}`)
shell(`node --import=tsx ${tempPath}`, { cwd: dirName() })
} catch (e) {
console.error(e)
}
Expand Down
9 changes: 7 additions & 2 deletions ark/attest/bench/baseline.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { snapshot } from "@arktype/util"
import process from "node:process"
import { queueSnapshotUpdate } from "../cache/snapshots.js"
import {
queueSnapshotUpdate,
writeSnapshotUpdatesOnExit
} from "../cache/snapshots.js"
import type { BenchAssertionContext, BenchContext } from "./bench.js"
import {
stringifyMeasure,
Expand Down Expand Up @@ -29,6 +32,8 @@ export const queueBaselineUpdateIfNeeded = (
snapFunctionName: ctx.kind,
baselinePath: ctx.qualifiedPath
})

if (ctx.kind === "types") writeSnapshotUpdatesOnExit()
}

/** Pretty print comparison and set the process.exitCode to 1 if delta threshold is exceeded */
Expand Down Expand Up @@ -69,4 +74,4 @@ const handleNegativeDelta = (formattedDelta: string, ctx: BenchContext) => {
1
)}! Consider setting a new baseline.`
)
}
}
44 changes: 15 additions & 29 deletions ark/attest/cache/snapshots.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,15 @@ export const getSnapshotByName = (
*/
export const queueSnapshotUpdate = (args: SnapshotArgs): void => {
const config = getConfig()
writeSnapUpdate(config.defaultAssertionCachePath, args)
writeSnapshotUpdatesOnExit()
const path = config.defaultAssertionCachePath
if (existsSync(path)) {
const existing = readJson(path)
writeJson(path, {
...existing,
updates:
Array.isArray(existing.updates) ? [...existing.updates, args] : [args]
})
} else writeJson(path, { updates: [args] })
}

export type QueuedUpdate = {
Expand Down Expand Up @@ -112,38 +119,23 @@ export const writeSnapshotUpdatesOnExit = (): void => {

const writeCachedInlineSnapshotUpdates = () => {
const config = getConfig()
const updates: QueuedUpdate[] = []

if (existsSync(config.assertionCacheDir))
updates.push(...getQueuedUpdates(config.defaultAssertionCachePath))

writeUpdates(updates)
writeSnapUpdate(config.defaultAssertionCachePath)
}

const writeSnapUpdate = (path: string, update?: SnapshotArgs) => {
const assertions =
existsSync(path) ? readJson(path) : { updates: [] as SnapshotArgs[] }
let snapshotData: SnapshotArgs[] | undefined

assertions.updates =
update !== undefined ? [...(assertions.updates ?? []), update] : []
if (!existsSync(config.defaultAssertionCachePath)) return

writeJson(path, assertions)
}
const updateQueue = (queue: QueuedUpdate[], path: string) => {
let snapshotData: SnapshotArgs[] | undefined
try {
snapshotData = readJson(path).updates
snapshotData = readJson(config.defaultAssertionCachePath).updates
} catch {
// If we can't read the snapshot, log an error and move onto the next update
console.error(
`Unable to read snapshot data from expected location ${path}.`
`Unable to read snapshot data from expected location ${config.defaultAssertionCachePath}.`
)
}
if (snapshotData) {
try {
snapshotData.forEach(snapshot =>
queue.push(snapshotArgsToQueuedUpdate(snapshot))
writeUpdates(
snapshotData.map(snapshot => snapshotArgsToQueuedUpdate(snapshot))
)
} catch (error) {
// If writeInlineSnapshotToFile throws an error, log it and move on to the next update
Expand All @@ -152,12 +144,6 @@ const updateQueue = (queue: QueuedUpdate[], path: string) => {
}
}

const getQueuedUpdates = (path: string) => {
const queuedUpdates: QueuedUpdate[] = []
updateQueue(queuedUpdates, path)
return queuedUpdates
}

const snapshotArgsToQueuedUpdate = ({
position,
serializedValue,
Expand Down
4 changes: 2 additions & 2 deletions ark/attest/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ export { caller, type CallerOfOptions } from "@arktype/fs"
export { attest } from "./assert/attest.js"
export { bench } from "./bench/bench.js"
export {
getBenchAssertionsAtPosition as getTypeBenchAssertionsAtPosition,
getTypeAssertionsAtPosition as getTypeRelationshipAssertionsAtPosition
getBenchAssertionsAtPosition,
getTypeAssertionsAtPosition
} from "./cache/getCachedAssertions.js"
export type {
ArgAssertionData,
Expand Down
2 changes: 1 addition & 1 deletion ark/attest/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
"@typescript/analyze-trace": "0.10.1"
},
"devDependencies": {
"typescript": "5.5.0-beta"
"typescript": "5.4.5"
},
"peerDependencies": {
"typescript": "*"
Expand Down
8 changes: 7 additions & 1 deletion ark/repo/.eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,13 @@ module.exports = defineConfig({
"no-case-declarations": "off",
/** In tests we use expect-error constantly, but in src if we
* ever have to there should be an explanation */
"@typescript-eslint/ban-ts-comment": "warn"
"@typescript-eslint/ban-ts-comment": [
"warn",
{
// some errors are environment dependent or e.g. don't appear in build output
"ts-ignore": "allow-with-description"
}
]
},
overrides: [
{
Expand Down
2 changes: 2 additions & 0 deletions ark/repo/mocha.globalSetup.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { cleanup, setup } from "@arktype/attest"

process.env.TZ = "America/New_York"

export const mochaGlobalSetup = setup

export const mochaGlobalTeardown = cleanup
3 changes: 2 additions & 1 deletion ark/schema/constraints/constraint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ export interface BaseConstraintDeclaration extends RawNodeDeclaration {
}

export abstract class RawConstraint<
/** @ts-expect-error allow instantiation assignment to the base type */
/** uses -ignore rather than -expect-error because this is not an error in .d.ts
* @ts-ignore allow instantiation assignment to the base type */
out d extends BaseConstraintDeclaration = BaseConstraintDeclaration
> extends RawNode<d> {
readonly [arkKind] = "constraint"
Expand Down
6 changes: 5 additions & 1 deletion ark/schema/constraints/props/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
} from "@arktype/util"
import type { Node, SchemaDef } from "../../node.js"
import type { RawSchema } from "../../schema.js"
import type { UnitNode } from "../../schemas/unit.js"
import type { BaseMeta, declareNode } from "../../shared/declare.js"
import { Disjoint } from "../../shared/disjoint.js"
import { implementNode, type SchemaKind } from "../../shared/implement.js"
Expand Down Expand Up @@ -47,7 +48,10 @@ export const indexImplementation = implementNode<IndexDeclaration>({
const key = ctx.$.schema(def)
if (!key.extends(ctx.$.keywords.propertyKey))
return throwParseError(writeInvalidPropertyKeyMessage(key.expression))
const enumerableBranches = key.branches.filter(b => b.hasKind("unit"))
// TODO: explicit manual annotation once we can upgrade to 5.5
const enumerableBranches = key.branches.filter((b): b is UnitNode =>
b.hasKind("unit")
)
if (enumerableBranches.length) {
return throwParseError(
writeEnumerableIndexBranches(
Expand Down
29 changes: 15 additions & 14 deletions ark/schema/node.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import {
Callable,
type Dict,
type Guardable,
type Json,
type conform,
flatMorph,
includes,
isArray,
type listable,
shallowClone,
throwError
throwError,
type Dict,
type Guardable,
type Json,
type conform,
type listable
} from "@arktype/util"
import type { RawConstraint } from "./constraints/constraint.js"
import type { PredicateNode } from "./constraints/predicate.js"
Expand All @@ -36,19 +36,19 @@ import type {
attachmentsOf
} from "./shared/declare.js"
import {
basisKinds,
constraintKinds,
precedenceOfKind,
propKinds,
refinementKinds,
schemaKinds,
type BasisKind,
type NodeKind,
type OpenNodeKind,
type PropKind,
type RefinementKind,
type SchemaKind,
type UnknownAttachments,
basisKinds,
constraintKinds,
precedenceOfKind,
propKinds,
refinementKinds,
schemaKinds
type UnknownAttachments
} from "./shared/implement.js"
import {
TraversalContext,
Expand All @@ -59,7 +59,8 @@ import {
export type UnknownNode = RawNode | Schema

export abstract class RawNode<
/** @ts-expect-error allow instantiation assignment to the base type */
/** uses -ignore rather than -expect-error because this is not an error in .d.ts
* @ts-ignore allow instantiation assignment to the base type */
out d extends RawNodeDeclaration = RawNodeDeclaration
> extends Callable<(data: d["prerequisite"]) => unknown, attachmentsOf<d>> {
constructor(public attachments: UnknownAttachments) {
Expand Down
17 changes: 9 additions & 8 deletions ark/schema/schema.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import {
throwParseError,
type Callable,
type Json,
type conform,
throwParseError
type conform
} from "@arktype/util"
import type { constrain } from "./constraints/ast.js"
import type { Predicate } from "./constraints/predicate.js"
import {
type PrimitiveConstraintKind,
throwInvalidOperandError
throwInvalidOperandError,
type PrimitiveConstraintKind
} from "./constraints/util.js"
import type { NodeDef, reducibleKindOf } from "./kinds.js"
import { type Node, RawNode } from "./node.js"
import { RawNode, type Node } from "./node.js"
import type { constraintKindOf } from "./schemas/intersection.js"
import type {
Morph,
Expand All @@ -29,9 +29,9 @@ import { Disjoint } from "./shared/disjoint.js"
import { ArkErrors } from "./shared/errors.js"
import type { NodeKind, SchemaKind, kindRightOf } from "./shared/implement.js"
import {
type inferIntersection,
intersectNodesRoot,
pipeNodesRoot
pipeNodesRoot,
type inferIntersection
} from "./shared/intersections.js"
import {
arkKind,
Expand All @@ -55,7 +55,8 @@ export type TypeOnlySchemaKey =
| "tOut"

export abstract class RawSchema<
/** @ts-expect-error allow instantiation assignment to the base type */
/** uses -ignore rather than -expect-error because this is not an error in .d.ts
* @ts-ignore allow instantiation assignment to the base type */
out d extends RawSchemaDeclaration = RawSchemaDeclaration
>
extends RawNode<d>
Expand Down
6 changes: 2 additions & 4 deletions ark/schema/shared/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,8 @@ import type { NodeKind } from "./implement.js"
import type { TraversalContext } from "./traversal.js"
import { arkKind, pathToPropString, type TraversalPath } from "./utils.js"

export const throwArkError = (
...args: ConstructorParameters<typeof ArkError>
): never => {
throw new ArkError(...args)
export const throwArkError = (message: string): never => {
throw new ArkError(message)
}

export class ArkError extends TypeError {
Expand Down
19 changes: 11 additions & 8 deletions ark/type/parser/objectLiteral.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
import {
tsKeywords,
type NodeDef,
type RawSchema,
tsKeywords,
type UnitNode,
type writeInvalidPropertyKeyMessage
} from "@arktype/schema"
import {
printable,
spliterate,
stringAndSymbolicEntriesOf,
throwParseError,
type Dict,
type ErrorMessage,
type Key,
type merge,
printable,
type show,
spliterate,
stringAndSymbolicEntriesOf,
throwParseError
type show
} from "@arktype/util"
import type { ParseContext } from "../scope.js"
import type { inferDefinition, validateDefinition } from "./definition.js"
Expand Down Expand Up @@ -62,8 +63,10 @@ export const parseObjectLiteral = (def: Dict, ctx: ParseContext): RawSchema => {
const value = ctx.$.parse(entry.value, ctx)

// extract enumerable named props from the index signature
const [enumerable, nonEnumerable] = spliterate(key.branches, k =>
k.hasKind("unit")
// TODO: remove explicit annotation once we can use TS 5.5
const [enumerable, nonEnumerable] = spliterate(
key.branches,
(k): k is UnitNode => k.hasKind("unit")
)

if (enumerable.length) {
Expand Down
Loading

0 comments on commit 2c6dd54

Please sign in to comment.