rescript-relay 0.0.0-cli-61b2cdf6 → 0.0.0-next-af0f6500

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/utils.mjs ADDED
@@ -0,0 +1,381 @@
1
+ function getNewObj(maybeNewObj, currentObj) {
2
+ return maybeNewObj || Object.assign({}, currentObj);
3
+ }
4
+
5
+ function getPathName(path) {
6
+ return path.join("_");
7
+ }
8
+
9
+ function makeNewPath(currentPath, newKeys) {
10
+ return [].concat(currentPath, newKeys);
11
+ }
12
+
13
+ function getTypename(v) {
14
+ if (v != null && typeof v === "object") {
15
+ if (v.__typename) {
16
+ return v.__typename;
17
+ }
18
+
19
+ // `v.VAL` relies on internal implementation details in ReScript.
20
+ if (v.VAL != null && typeof v.VAL === "object") {
21
+ return v.VAL.__typename;
22
+ }
23
+ }
24
+ }
25
+
26
+ /**
27
+ * Runs on each object in the tree and follows the provided instructions
28
+ * to apply transforms etc.
29
+ */
30
+ function traverse(
31
+ fullInstructionMap,
32
+ currentPath,
33
+ currentObj,
34
+ instructionMap,
35
+ converters,
36
+ nullableValue,
37
+ instructionPaths,
38
+ addFragmentOnRoot
39
+ ) {
40
+ // We lazily set up a new object for each "level", as we don't want to mutate
41
+ // what comes back from the Relay store, and nor do we want to create new
42
+ // objects unless we need to. And we only need to when we need to change
43
+ // something.
44
+ var newObj;
45
+
46
+ if (addFragmentOnRoot) {
47
+ newObj = getNewObj(newObj, currentObj);
48
+ newObj.fragmentRefs = Object.assign({}, newObj);
49
+ }
50
+
51
+ for (var key in currentObj) {
52
+ if (key === "VAL" || key === "NAME") continue;
53
+
54
+ var isUnion = false;
55
+ var originalValue = currentObj[key];
56
+
57
+ // Instructions are stored by the path in the object where they apply
58
+ var thisPath = makeNewPath(currentPath, [key]);
59
+ var path = getPathName(thisPath);
60
+
61
+ var instructions = instructionMap[path] || {};
62
+
63
+ if (currentObj[key] == null) {
64
+ newObj = getNewObj(newObj, currentObj);
65
+ newObj[key] = nullableValue;
66
+ continue;
67
+ }
68
+
69
+ var shouldConvertRootObj =
70
+ typeof instructions["r"] === "string" &&
71
+ fullInstructionMap[instructions["r"]];
72
+
73
+ var shouldAddFragmentFn = instructions["f"] === "";
74
+
75
+ var shouldConvertEnum =
76
+ typeof instructions["e"] === "string" && !!converters[instructions["e"]];
77
+
78
+ var shouldConvertCustomField =
79
+ typeof instructions["c"] === "string" && !!converters[instructions["c"]];
80
+
81
+ var shouldConvertUnion =
82
+ typeof instructions["u"] === "string" && !!converters[instructions["u"]];
83
+
84
+ var isTopLevelNodeField = typeof instructions["tnf"] === "string";
85
+
86
+ /**
87
+ * Handle arrays
88
+ */
89
+ if (Array.isArray(currentObj[key])) {
90
+ newObj = getNewObj(newObj, currentObj);
91
+ newObj[key] = currentObj[key].map(function (v) {
92
+ if (v == null) {
93
+ return nullableValue;
94
+ }
95
+
96
+ if (shouldConvertRootObj) {
97
+ return traverser(
98
+ v,
99
+ fullInstructionMap,
100
+ converters,
101
+ nullableValue,
102
+ instructions["r"]
103
+ );
104
+ }
105
+
106
+ if (shouldConvertEnum) {
107
+ return converters[instructions["e"]](v);
108
+ }
109
+
110
+ if (shouldConvertCustomField) {
111
+ return converters[instructions["c"]](v);
112
+ }
113
+
114
+ if (shouldConvertUnion && v != null && typeof v === "object") {
115
+ var typename = getTypename(v);
116
+
117
+ if (typename != null) {
118
+ isUnion = true;
119
+ var unionObj = v;
120
+
121
+ // Means we're wrapping, and this will be a ReScript value.
122
+ if (nullableValue === null) {
123
+ // Convert it back to a flat JS value
124
+ unionObj = converters[instructions["u"]](v);
125
+ }
126
+
127
+ var newPath = makeNewPath(currentPath, [key, typename]);
128
+
129
+ var unionRootHasFragment =
130
+ (instructionMap[getPathName(newPath)] || {}).f === "";
131
+
132
+ var traversedValue = traverse(
133
+ fullInstructionMap,
134
+ newPath,
135
+ unionObj,
136
+ instructionMap,
137
+ converters,
138
+ nullableValue,
139
+ instructionPaths,
140
+ unionRootHasFragment
141
+ );
142
+
143
+ // Undefined means we're going from JS to ReScript, in which case we
144
+ // need to run the conversion here rather than earlier.
145
+ return nullableValue === undefined
146
+ ? converters[instructions["u"]](traversedValue)
147
+ : traversedValue;
148
+ }
149
+ }
150
+
151
+ if (shouldAddFragmentFn && typeof v === "object") {
152
+ var objWithFragmentFn = Object.assign({}, v);
153
+ objWithFragmentFn.fragmentRefs = Object.assign({}, objWithFragmentFn);
154
+ return objWithFragmentFn;
155
+ }
156
+
157
+ return v;
158
+ });
159
+ } else {
160
+ /**
161
+ * Handle normal values.
162
+ */
163
+ var v = currentObj[key];
164
+
165
+ if (shouldConvertRootObj) {
166
+ newObj = getNewObj(newObj, currentObj);
167
+ newObj[key] = traverser(
168
+ v,
169
+ fullInstructionMap,
170
+ converters,
171
+ nullableValue,
172
+ instructions["r"]
173
+ );
174
+ }
175
+
176
+ if (isTopLevelNodeField) {
177
+ // If this is a top level node field we should try and convert, ensure
178
+ // it conforms to the desired shape (has the correct typename). If not,
179
+ // null it and return right away.
180
+ if (
181
+ v == null ||
182
+ !v.hasOwnProperty("__typename") ||
183
+ v.__typename !== instructions["tnf"]
184
+ ) {
185
+ newObj = getNewObj(newObj, currentObj);
186
+ newObj[key] = nullableValue;
187
+ return newObj;
188
+ }
189
+ }
190
+
191
+ if (shouldConvertEnum) {
192
+ newObj = getNewObj(newObj, currentObj);
193
+ newObj[key] = converters[instructions["e"]](v);
194
+ }
195
+
196
+ if (shouldConvertCustomField) {
197
+ newObj = getNewObj(newObj, currentObj);
198
+ newObj[key] = converters[instructions["c"]](v);
199
+ }
200
+
201
+ if (shouldConvertUnion && v != null && typeof v === "object") {
202
+ var typename = getTypename(v);
203
+
204
+ if (typename != null) {
205
+ isUnion = true;
206
+ var unionObj = v;
207
+
208
+ // Means we're wrapping, and this will be a ReScript value.
209
+ if (nullableValue === null) {
210
+ // Convert it back to a flat JS value
211
+ unionObj = converters[instructions["u"]](v);
212
+ }
213
+
214
+ var newPath = makeNewPath(currentPath, [key, typename]);
215
+
216
+ var unionRootHasFragment =
217
+ (instructionMap[getPathName(newPath)] || {}).f === "";
218
+
219
+ var traversedValue = traverse(
220
+ fullInstructionMap,
221
+ newPath,
222
+ unionObj,
223
+ instructionMap,
224
+ converters,
225
+ nullableValue,
226
+ instructionPaths,
227
+ unionRootHasFragment
228
+ );
229
+
230
+ newObj = getNewObj(newObj, currentObj);
231
+
232
+ newObj[key] =
233
+ // Undefined means we're going from JS to ReScript, in which case we
234
+ // need to run the conversion here rather than earlier.
235
+ nullableValue === undefined
236
+ ? converters[instructions["u"]](traversedValue)
237
+ : traversedValue;
238
+ }
239
+ }
240
+
241
+ if (shouldAddFragmentFn && typeof v === "object") {
242
+ newObj = getNewObj(newObj, currentObj);
243
+ var objWithFragmentFn = Object.assign({}, v);
244
+ objWithFragmentFn.fragmentRefs = Object.assign({}, objWithFragmentFn);
245
+ newObj[key] = objWithFragmentFn;
246
+ }
247
+ }
248
+
249
+ if (originalValue != null && !isUnion) {
250
+ var nextObj = (newObj && newObj[key]) || currentObj[key];
251
+
252
+ if (typeof nextObj === "object" && !Array.isArray(originalValue)) {
253
+ var traversedObj = traverse(
254
+ fullInstructionMap,
255
+ thisPath,
256
+ nextObj,
257
+ instructionMap,
258
+ converters,
259
+ nullableValue,
260
+ instructionPaths
261
+ );
262
+
263
+ if (traversedObj !== nextObj) {
264
+ newObj = getNewObj(newObj, currentObj);
265
+ newObj[key] = traversedObj;
266
+ }
267
+ } else if (Array.isArray(originalValue)) {
268
+ newObj = getNewObj(newObj, currentObj);
269
+ newObj[key] = nextObj.map(function (o) {
270
+ if (typeof o === "object" && o != null) {
271
+ return traverse(
272
+ fullInstructionMap,
273
+ thisPath,
274
+ o,
275
+ instructionMap,
276
+ converters,
277
+ nullableValue,
278
+ instructionPaths
279
+ );
280
+ } else if (o == null) {
281
+ return nullableValue;
282
+ } else {
283
+ return o;
284
+ }
285
+ });
286
+ }
287
+ }
288
+ }
289
+
290
+ return newObj || currentObj;
291
+ }
292
+
293
+ /**
294
+ * This function takes an object (snapshot from the Relay store) and applies a
295
+ * set of conversions deeply on the object (instructions coming from "converters"-prop).
296
+ * It converts nullable values either to null or undefined, and it wraps/unwraps enums
297
+ * and unions.
298
+ *
299
+ * It preserves structural integrity where possible, and return new objects where properties
300
+ * have been modified.
301
+ */
302
+ function traverser(
303
+ root,
304
+ instructionMaps_,
305
+ theConverters,
306
+ nullableValue,
307
+ rootObjectKey
308
+ ) {
309
+ if (!root) {
310
+ return nullableValue;
311
+ }
312
+
313
+ var instructionMaps = instructionMaps_ || {};
314
+ var instructionMap = instructionMaps[rootObjectKey || "__root"] || {};
315
+
316
+ var converters = theConverters == null ? {} : theConverters;
317
+ var instructionPaths = Object.keys(instructionMap);
318
+
319
+ // We'll add the fragmentRefs reference to the root if needed here.
320
+ var fragmentsOnRoot = (instructionMap[""] || {}).f === "";
321
+ var unionRootConverter = converters[(instructionMap[""] || {}).u];
322
+
323
+ if (Array.isArray(root)) {
324
+ return root.map(function (v) {
325
+ if (v == null) {
326
+ return nullableValue;
327
+ }
328
+
329
+ var n = [];
330
+
331
+ // Since a root level union is treated as a "new root level", we'll need
332
+ // to do a separate check here of whether there's a fragment on the root
333
+ // we need to account for, or not.
334
+ if (unionRootConverter != null) {
335
+ n = [v.__typename];
336
+ fragmentsOnRoot = (instructionMap[v.__typename] || {}).f === "";
337
+ }
338
+
339
+ var traversedObj = traverse(
340
+ instructionMaps,
341
+ n,
342
+ v,
343
+ instructionMap,
344
+ converters,
345
+ nullableValue,
346
+ instructionPaths,
347
+ fragmentsOnRoot
348
+ );
349
+
350
+ return unionRootConverter != null
351
+ ? unionRootConverter(traversedObj)
352
+ : traversedObj;
353
+ });
354
+ }
355
+
356
+ var newObj = Object.assign({}, root);
357
+
358
+ var n = [];
359
+
360
+ // Same as in the union array check above - if there's a fragment in the new
361
+ // root created by the union, we need to account for that separately here.
362
+ if (unionRootConverter != null) {
363
+ n = [newObj.__typename];
364
+ fragmentsOnRoot = (instructionMap[newObj.__typename] || {}).f === "";
365
+ }
366
+
367
+ var v = traverse(
368
+ instructionMaps,
369
+ n,
370
+ newObj,
371
+ instructionMap,
372
+ converters,
373
+ nullableValue,
374
+ instructionPaths,
375
+ fragmentsOnRoot
376
+ );
377
+
378
+ return unionRootConverter != null ? unionRootConverter(v) : v;
379
+ }
380
+
381
+ export { traverser };
package/bin-darwin DELETED
Binary file
package/bin-linux DELETED
Binary file
@@ -1,54 +0,0 @@
1
- #!/usr/bin/env node
2
- const path = require("path");
3
- const { spawn } = require("child_process");
4
-
5
- let relayConfig = require("relay-config").loadConfig();
6
-
7
- if (!relayConfig) {
8
- console.error(
9
- "Could not find relay.config.js. You must configure Relay through relay.config.js for RescriptRelay to work."
10
- );
11
-
12
- process.exit(1);
13
- }
14
-
15
- if (!relayConfig.artifactDirectory) {
16
- console.error(
17
- "RescriptRelay requires you to define 'artifactDirectory' (for outputing generated files in a single directory) in your relay.config.js. Please define it and re-run this command."
18
- );
19
- process.exit(1);
20
- }
21
-
22
- function runRelayCompiler(args) {
23
- const proc = spawn("relay-compiler", args, {
24
- stdio: "inherit",
25
- })
26
- // Propagate the relay compiler's exit code.
27
- .on("close", process.exit.bind(process));
28
-
29
- process.on("SIGINT", () => {
30
- proc.kill("SIGINT");
31
- });
32
- }
33
-
34
- function findArg(name) {
35
- return relayConfig[name];
36
- }
37
-
38
- async function runCompiler() {
39
- const schemaPath = findArg("schema");
40
-
41
- if (schemaPath) {
42
- runRelayCompiler(
43
- [
44
- "--language",
45
- path.resolve(__dirname + "/../language-plugin/dist/index.js"),
46
- process.argv.find((a) => a === "--watch"),
47
- ].filter(Boolean)
48
- );
49
- } else {
50
- runRelayCompiler(["--help"]);
51
- }
52
- }
53
-
54
- runCompiler();
@@ -1 +0,0 @@
1
- module.exports=(()=>{"use strict";var e={338:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.find=void 0,t.find=function(e,t){return function(e,t){if(!e.includes("%relay"))return[];const n=e.match(/(?<=\[%relay)([\s\S]*?)(?=];)/g);if(n)return n.map((e=>({template:e.replace(/({\||\|})/g,""),keyName:null,sourceLocationOffset:{line:1,column:1}})));const r=e.match(/(?<=\%relay\([\s]*`)[\s\S.]+?(?=`[\s]*\))/g);return r?r.map((e=>({template:e,keyName:null,sourceLocationOffset:{line:1,column:1}}))):[]}(e)}},189:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.generateFromFlowTypes=void 0;const r=n(129),o=n(622);t.generateFromFlowTypes=e=>{var t;const n=r.spawnSync(o.resolve(o.join(__dirname,"../RescriptRelayBin.exe")),["generate-from-flow"],{cwd:__dirname,stdio:"pipe",encoding:"utf-8",input:JSON.stringify(e)});if(0!==n.status)throw null!==(t=n.error)&&void 0!==t?t:new Error("Error generating types");return n.output.filter(Boolean).join("")}},571:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.transforms=t.generate=void 0;const r=n(791),o=n(224),a=n(148),i=n(354),s=n(189),l=n(602);function c(e){const t=Object.assign({Int:"int",Float:"float"},e);return Object.keys(t).forEach((e=>{t[e]=l.maskDots(t[e])})),t}t.generate=function(e,t,n){var a;let i=r.generate(e,t,Object.assign(Object.assign({},n),{customScalars:c(n.customScalars)}));const l=o.makeOperationDescriptor(t),d=o.extractOperationInfo(t);return s.generateFromFlowTypes({content:i,operation_type:["Query","Mutation","Subscription"].includes(l.tag)?{operation:l.tag,operation_value:l.value}:{operation:"Fragment",fragment_value:l.value},print_config:{variables_holding_connection_ids:null!==(a=d.variablesHoldingConnectionIds)&&void 0!==a?a:null,connection:d.connection?{at_object_path:d.connection.atObjectPath,field_name:d.connection.fieldName,key:d.connection.key}:null}})},t.transforms=[i.transform,a.transform,...r.transforms]},942:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(366),o=n(622);e.exports=({moduleName:e,documentType:t,concreteText:n,typeText:a,definition:i})=>{let s=null;"Source"===i.loc.kind&&(s=o.basename(i.loc.source.name));const l="ConcreteRequest"===t&&e.toLowerCase().endsWith("query_graphql")?"include RescriptRelay.MakeLoadQuery({\n type variables = Types.variables\n type loadedQueryRef = queryRef\n type response = Types.response\n type node = relayOperationNode\n let query = node\n let convertVariables = Internal.convertVariables\n });":"",{processedText:c,referencedNodes:d}=r.processConcreteText(n),u=`%raw(json\` ${c} \`)`;return[s?`/* @sourceLoc ${s} */`:null,a||"",...d.length>0?[`%%private(let makeNode = (${d.map((({identifier:e})=>e)).join(", ")}): operationType => {`,...d.map((({identifier:e})=>` ignore(${e})`)),` ${u}`,"})",`let node: operationType = makeNode(${d.map((({moduleName:e})=>`${e}_graphql.node`)).join(", ")})`]:[`let node: operationType = ${u}`],"",l,""].filter((e=>null!=e)).join("\n")}},602:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.unmaskDots=t.maskDots=void 0,t.maskDots=e=>e.split(".").join("__oo__"),t.unmaskDots=e=>e.split("__oo__").join(".")},607:(e,t,n)=>{const r=n(571),o=n(942),{find:a}=n(338),i=n(622),s=n(747);function l(e){return t=>{const n=i.join(e,t.relPath);let r="";try{r=s.readFileSync(n,"utf8")}catch(e){return console.warn(`RelaySourceModuleParser: Unable to read the file "${n}". Looks like it was removed.`),!1}return r.indexOf("%relay")>=0}}e.exports=()=>({inputExtensions:["re","res"],outputExtension:"res",schemaExtensions:[],typeGenerator:r,formatModule:o,findGraphQLTags:a,isGeneratedFile:e=>e.endsWith("_graphql.res")||e.endsWith(".js")||e.endsWith(".mjs"),keepExtraFile:e=>e.endsWith(".js")||e.endsWith(".mjs"),getFileFilter:l,getModuleName:e=>`${e}_graphql`})},224:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.makeOperationDescriptor=t.extractOperationInfo=void 0;const r=n(195);function o(e,t,n){if("Root"===e.kind&&["mutation","subscription"].includes(e.operation)){const e=t.directives.filter((e=>["appendNode","prependNode","appendEdge","prependEdge","deleteEdge"].includes(e.name)));e.length>0&&e.forEach((e=>{const t=e.args.find((e=>"connections"===e.name)),r=null==t?void 0:t.value;r&&"Variable"===r.kind&&(n.variablesHoldingConnectionIds?n.variablesHoldingConnectionIds.push(r.variableName):n.variablesHoldingConnectionIds=[r.variableName])}))}}t.extractOperationInfo=function(e){let t={};const n="Fragment"===e.kind?"fragment":"response";return n?(function e(n,a){r.IRVisitor.visit(a,{ScalarField(e){o(a,e,t)},LinkedField(e){const r=e.directives.find((e=>"connection"===e.name));if(r&&!t.connection){let o=null;r.args.forEach((e=>{"key"===e.name&&"Literal"===e.value.kind&&(o=e.value.value)})),o&&(t=Object.assign(Object.assign({},t),{connection:{key:o,atObjectPath:[...n],fieldName:e.alias}}))}o(a,e,t),n.push(e.alias)},InlineFragment(t){t.typeCondition.name&&t.selections.forEach((r=>{e([...n,t.typeCondition.name.toLowerCase()],r)}))}})}([n],e),t):t},t.makeOperationDescriptor=function(e){if("Root"===e.kind)switch(e.operation){case"mutation":return{tag:"Mutation",value:e.name};case"query":return{tag:"Query",value:e.name};case"subscription":return{tag:"Subscription",value:e.name}}else if("Fragment"==e.kind)return{tag:"Fragment",value:[e.name,Boolean(e.metadata&&e.metadata.plural)]};throw new Error("Could not map root node. This should not happen.")}},148:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.transform=void 0;const r=n(724),{createUserError:o}=n(182),a=["and","as","asr","assert","begin","class","constraint","do","while","for","done","while","for","downto","else","end","exception","external","false","for","fun","function","functor","if","in","include","inherit","initializer","land","lazy","let","lor","lsl","lsr","lxor","match","method","mod","module","open","mutable","new","nonrec","object","of","open","open!","or","private","rec","let","module","sig","struct","then","to","true","try","type","val","virtual","val","method","class","when","while","with","switch"];let i=["fragment","t_fragment","subscription","mutation","response","variables","refetchVariables","t","fragmentRef","fragmentRefs","fragmentRefSelector","operationType"];function s(e){if(e.alias){let{disallowed:t,message:n}=function(e){let t=e[0];return/[A-Z]/.test(t)?{disallowed:!0,message:`Field names may not start with an uppercase letter. Please alias the '${e}' field to something starting with a lowercase letter.`}:a.includes(e)?{disallowed:!0,message:`'${e}' is a reserved keyword in ReasonML and therefore cannot be used as a field name. Please alias your field to something else.`}:i.includes(e)?{disallowed:!0,message:`'${e}' is a reserved keyword in RescriptRelay and therefore cannot be used as a field name. Please alias your field to something else.`}:{disallowed:!1,message:""}}(e.alias);if(t)throw o("Found an invalid field name: "+n,[e.loc])}e.selections&&e.selections.forEach(s)}function l(e){return s(e),e}t.transform=function(e){return r.transform(e,{ScalarField:l,LinkedField:l})}},354:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.transform=void 0;const r=n(724),{createUserError:o}=n(182),{hasUnaliasedSelection:a}=n(124);function i(e){const t=this.getContext().getSchema();let n=this.traverse(e);if(t.isAbstractType(t.getRawType(n.type))&&!a(n,"__typename"))throw o('Unions and interfaces must have the field __typename explicitly selected. Please add __typename to the fields selected by "'+e.alias+'" in your operation.',[e.loc]);return n}t.transform=function(e){return r.transform(e,{LinkedField:i})}},366:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.processConcreteText=void 0,t.processConcreteText=function(e){let t=/(require\('.\/)([A-Za-z_.0-9/]+)(.graphql.\w*'\))/gm,n=e;const r=[];let o;for(;null!==(o=t.exec(e));){let[e,t,a]=o;const i=`node_${a}`;r.push({moduleName:a,identifier:i}),n=n.replace(e,`node_${a}`)}return{processedText:n,referencedNodes:r}}},129:e=>{e.exports=require("child_process")},747:e=>{e.exports=require("fs")},622:e=>{e.exports=require("path")},195:e=>{e.exports=require("relay-compiler")},182:e=>{e.exports=require("relay-compiler/lib/core/CompilerError")},724:e=>{e.exports=require("relay-compiler/lib/core/IRTransformer")},791:e=>{e.exports=require("relay-compiler/lib/language/javascript/RelayFlowGenerator")},124:e=>{e.exports=require("relay-compiler/lib/transforms/TransformUtils")}},t={};return function n(r){if(t[r])return t[r].exports;var o=t[r]={exports:{}};return e[r](o,o.exports,n),o.exports}(607)})();