Skip to content

Commit

Permalink
Fix race condition, add a bunch of silly console logs
Browse files Browse the repository at this point in the history
  • Loading branch information
davidkpiano committed Mar 13, 2024
1 parent bf56844 commit 307659f
Show file tree
Hide file tree
Showing 7 changed files with 160 additions and 27 deletions.
69 changes: 44 additions & 25 deletions apps/extension/server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -301,9 +301,14 @@ async function handleDocumentChange(textDocument: TextDocument): Promise<void> {
message: displayedMachine.error.message,
});
} else {
const { configError, machineResult } =
const extractionResult =
extractionResults[displayedMachine.machineIndex];

if (!extractionResult) {
throw new Error('Oops');
}
const { configError, machineResult } = extractionResult;

if (configError) {
connection.sendNotification('extractionError', {
message: configError,
Expand Down Expand Up @@ -671,8 +676,15 @@ connection.onRequest('getMachineAtIndex', ({ uri, machineIndex }) => {
throw new Error('There were no machines recognized in this document');
}

const machineResult =
cachedDocument.extractionResults[machineIndex].machineResult;
const extractionResult = cachedDocument.extractionResults[machineIndex];

if (!extractionResult) {
throw new Error(
'no extraction result found for given index ' + machineIndex,
);
}

const machineResult = extractionResult.machineResult;

if (!machineResult) {
throw new Error(
Expand Down Expand Up @@ -726,8 +738,15 @@ connection.onRequest('getMachineAtCursorPosition', ({ uri, position }) => {
);
}

const machineResult =
cachedDocument.extractionResults[machineResultIndex].machineResult;
const extractionResult = cachedDocument.extractionResults[machineResultIndex];

if (!extractionResult) {
throw new Error(
'no extraction result found for given index ' + machineResultIndex,
);
}

const machineResult = extractionResult.machineResult;

return {
config: machineResult.toConfig()!,
Expand All @@ -754,30 +773,27 @@ connection.onRequest('applyMachineEdits', ({ machineEdits, reason }) => {
const cachedDocument = documentsCache.get(displayedUri)!;
const isLayoutStringOnlyUpdate =
machineEdits.length === 1 &&
machineEdits[0].type === 'update_layout_string';
machineEdits[0]!.type === 'update_layout_string';

let modified: ReturnType<
MachineExtractResult['modify'] | MachineExtractResult['restore']
>;

const extractionResult =
cachedDocument.extractionResults[displayedMachine.machineIndex];
if (!extractionResult) {
throw new Error('No extraction result found');
}
if (!isLayoutStringOnlyUpdate && reason === 'undo') {
const item = cachedDocument.undoStack.pop();

if (item) {
modified =
cachedDocument.extractionResults[
displayedMachine.machineIndex
].machineResult.restore(item);
modified = extractionResult.machineResult.restore(item);
} else {
modified =
cachedDocument.extractionResults[
displayedMachine.machineIndex
].machineResult.modify(machineEdits);
modified = extractionResult.machineResult.modify(machineEdits);
}
} else {
const modifyResult =
cachedDocument.extractionResults[
displayedMachine.machineIndex
].machineResult.modify(machineEdits);
const modifyResult = extractionResult.machineResult.modify(machineEdits);

modified = modifyResult;

Expand Down Expand Up @@ -808,12 +824,10 @@ connection.onRequest('applyMachineEdits', ({ machineEdits, reason }) => {

// this kinda also should update types, but at the moment we don't need it
// and the whole thing will be refactored anyway
cachedDocument.extractionResults[
displayedMachine.machineIndex
].machineResult = getMachineExtractResult({
extractionResult.machineResult = getMachineExtractResult({
file,
fileContent: newDocumentText,
node: machineNodes[displayedMachine.machineIndex],
node: machineNodes[displayedMachine.machineIndex]!, // TODO: check
})!;

return {
Expand Down Expand Up @@ -859,9 +873,14 @@ connection.onRequest('getNodePosition', ({ path }) => {
return;
}

const machineResult =
cachedDocument.extractionResults[displayedMachine.machineIndex]
.machineResult;
const extractionResult =
cachedDocument.extractionResults[displayedMachine.machineIndex];

if (!extractionResult) {
throw new Error('No extraction result found');
}

const machineResult = extractionResult.machineResult;

const node = machineResult.getStateNodeByPath(path);

Expand Down
3 changes: 2 additions & 1 deletion apps/extension/server/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"noEmit": true,
"skipLibCheck": true,
"esModuleInterop": true,
"exactOptionalPropertyTypes": true
"exactOptionalPropertyTypes": true,
"noUncheckedIndexedAccess": true
},
"include": ["src"],
"exclude": ["node_modules", ".vscode-test"]
Expand Down
1 change: 1 addition & 0 deletions new-packages/ts-project/__tests__/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,7 @@ function findNodeByStatePath(
let marker = digraph.nodes[digraph.root];
let parentId = digraph.root;

console.log(291, path);
for (const segment of path) {
const node = Object.values(digraph.nodes).find(
(node) => node.parentId === parentId && node.data.key === segment,
Expand Down
9 changes: 9 additions & 0 deletions new-packages/ts-project/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,7 @@ function createProjectMachine({
// this might become a problem, especially when dealing with copy-pasting
// the implementation will have to account for that in the future
const newNode: Node = patch.value;
console.log(578);
const parentStateNode = findNodeByAstPath(
host.ts,
createMachineCall,
Expand All @@ -601,6 +602,8 @@ function createProjectMachine({
break;
}
assert(patch.path.length === 2);
console.log('>>', patch);
console.log(Object.keys(currentState.astPaths.nodes));
const sourceNode = findNodeByAstPath(
host.ts,
createMachineCall,
Expand Down Expand Up @@ -633,6 +636,7 @@ function createProjectMachine({
break;
}
const nodeId = patch.path[1];
console.log(578);
const stateNode = findNodeByAstPath(
host.ts,
createMachineCall,
Expand All @@ -641,6 +645,7 @@ function createProjectMachine({
assert(host.ts.isObjectLiteralExpression(stateNode));

if (patch.path[2] === 'data' && patch.path[3] === 'key') {
console.log(647);
const parenStatetNode = findNodeByAstPath(
host.ts,
createMachineCall,
Expand Down Expand Up @@ -796,6 +801,7 @@ function createProjectMachine({
break;
}
const edge = currentState.digraph!.edges[patch.path[1]];
console.log(803);
const transitionNode = findNodeByAstPath(
host.ts,
createMachineCall,
Expand Down Expand Up @@ -880,6 +886,7 @@ function createProjectMachine({
// there is no way to know where to look for this parent
// so if it wasn't a node we try to find it in the edges
const edge = currentState.digraph!.edges[block.parentId];
console.log(888);
const transitionNode = findNodeByAstPath(
host.ts,
createMachineCall,
Expand Down Expand Up @@ -924,6 +931,7 @@ function createProjectMachine({
);
break;
}
console.log(933);
const stateNode = findNodeByAstPath(
host.ts,
createMachineCall,
Expand Down Expand Up @@ -1103,6 +1111,7 @@ function createProjectMachine({
switch (patch.path[0]) {
case 'nodes': {
const nodeId = patch.path[1];
console.log(1113);
const stateNode = findNodeByAstPath(
host.ts,
createMachineCall,
Expand Down
1 change: 1 addition & 0 deletions new-packages/ts-project/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,7 @@ export function findNodeByAstPath(

let current = call.arguments[0];

console.log(268, path);
for (const segment of path) {
if (ts.isObjectLiteralExpression(current)) {
const retrieved = current.properties[segment];
Expand Down
101 changes: 100 additions & 1 deletion new-packages/vscode-xstate/src/languageClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ import type { ExtractorDigraphDef, Patch } from '@xstate/ts-project';
import * as vscode from 'vscode';
import {
ActorRef,
ExtractEvent,
Snapshot,
assertEvent,
assign,
fromCallback,
fromPromise,
sendTo,
Expand Down Expand Up @@ -45,6 +47,8 @@ export const languageClientMachine = setup({
context: {
extensionContext: vscode.ExtensionContext;
languageClient: LanguageClient;
patchesToApply: ExtractEvent<LanguageClientEvent, 'APPLY_PATCHES'>[];
nextPatch: ExtractEvent<LanguageClientEvent, 'APPLY_PATCHES'> | undefined;
};
events: LanguageClientEvent;
children: {
Expand Down Expand Up @@ -190,6 +194,67 @@ export const languageClientMachine = setup({
},
),
webviewLogic,
applyPatches: fromPromise(async ({ input }) => {
console.log('applying patches');
const { context, event } = input;
assertEvent(event, 'APPLY_PATCHES');
const { type, ...params } = event;
const textEdits = await context.languageClient.sendRequest(
applyPatches,
params,
);

const workspaceEdit = new vscode.WorkspaceEdit();
for (const textEdit of textEdits) {
switch (textEdit.type) {
case 'delete': {
workspaceEdit.delete(
vscode.Uri.parse(params.uri),
new vscode.Range(
new vscode.Position(
textEdit.range.start.line,
textEdit.range.start.character,
),
new vscode.Position(
textEdit.range.end.line,
textEdit.range.end.character,
),
),
);
break;
}
case 'insert': {
workspaceEdit.insert(
vscode.Uri.parse(params.uri),
new vscode.Position(
textEdit.position.line,
textEdit.position.character,
),
textEdit.newText,
);
break;
}
case 'replace': {
workspaceEdit.replace(
vscode.Uri.parse(params.uri),
new vscode.Range(
new vscode.Position(
textEdit.range.start.line,
textEdit.range.start.character,
),
new vscode.Position(
textEdit.range.end.line,
textEdit.range.end.character,
),
),
textEdit.newText,
);
break;
}
}
}
return vscode.workspace.applyEdit(workspaceEdit);
}),
},
}).createMachine({
context: ({ input }) => {
Expand All @@ -210,6 +275,8 @@ export const languageClientMachine = setup({
},
},
),
patchesToApply: [],
nextPatch: undefined,
};
},
invoke: {
Expand Down Expand Up @@ -287,7 +354,39 @@ export const languageClientMachine = setup({
actions: 'updateDigraph',
},
APPLY_PATCHES: {
actions: 'applyPatches',
actions: assign({
patchesToApply: ({ context, event }) => {
return context.patchesToApply.concat(event);
},
}),
},
},
initial: 'appliedPatches',
states: {
applyingPatches: {
invoke: {
src: 'applyPatches',
input: ({ context }) => ({
context,
event: context.nextPatch!,
}),
onDone: {
target: 'appliedPatches',
},
},
},
appliedPatches: {
always: {
guard: ({ context }) => context.patchesToApply.length > 0,
actions: assign(({ context }) => {
const nextPatch = context.patchesToApply.shift()!;
return {
patchesToApply: context.patchesToApply,
nextPatch,
};
}),
target: 'applyingPatches',
},
},
},
},
Expand Down
3 changes: 3 additions & 0 deletions packages/machine-extractor/src/MachineExtractResult.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,7 @@ export class MachineExtractResult {
}

definition.states?.properties.forEach((stateNode) => {
console.log(249, path);
getSubNodes(stateNode.result, [...path, stateNode.key]);
});
};
Expand Down Expand Up @@ -1895,6 +1896,7 @@ function getPropByPath(ast: RecastObjectExpression, path: (string | number)[]) {
'As we have to return a *prop* the last element of the path must be a string',
);
}
console.log(1899, path);
const pathCopy = [...path];
let segment: (typeof path)[number] | undefined;
let current: RecastNode | undefined | null = ast;
Expand Down Expand Up @@ -1990,6 +1992,7 @@ function getTransitionObject(
obj: RecastObjectExpression,
path: TransitionPath,
) {
console.log(1995, path);
const pathCopy = [...path];
let segment: (typeof path)[number] | undefined;
let current: RecastNode = obj;
Expand Down

0 comments on commit 307659f

Please sign in to comment.